The gramps.gen.utils Module

Generic utilities useful for users of the gen package

Utilities

Callback

Introduction

Gramps is divided into two parts. The database code, that does not require any particular GUI libraries, and the gtk-based UI code that requires gtk and gnome libraries. The gtk-based code can use the gobject signal support to manage callback signals but the database code can not.

The module provides a subset of the signal mechanisms that are available from the gobject framework. It enables the database code to use signals to communicate events to any callback methods in either the database code or the UI code.

class gramps.gen.utils.callback.Callback[source]

Bases: object

Callback and signal support objects.

Declaring signals

Classes that want to emit signals need to inherit from the DBCallback class and ensure that its __init__() method is called. They then need to declare the signals that they can emit and the types of each callbacks arguments. For example:

class TestSignals(Callback):

    __signals__ = {
              'test-signal' : (int, ),
              'test-noarg'  : None
             }

    def __init__(self):
        Callback.__init__(self)

The type signature is a tuple of types or classes. The type checking code uses the isinstance method to check that the argument passed to the emit call is an instance of the type in the signature declaration.

If the signal does not have an argument use None as the signature.

The signals will be inherited by any subclasses. Duplicate signal names in subclasses are not alowed.

Emitting signals

Signals are emitted using the emit method. e.g.:

def emit_signal(self):
    self.emit('test-signal', (1, ))

The parameters are passed as a tuple so a single parameter must be passed as a 1 element tuple.

Connecting callbacks to signals

Attaching a callback to the signals is similar to the gtk connect methods. e.g.:

# connect to a function.
def fn(i):
    print 'got signal value = ', i

t = TestSignals()
t.connect('test-signal', fn)

# connect to a bound method
class C:

    def cb_func(self, i):
        print 'got class signal = ', 1

r = R()
t.connect('test-signal', r.cb_func)

Disconnecting callbacks

If you want to disconnect a callback from a signals you must remember the key returned from the connect call. This key can be passed to the disconnect method to remove the callback from the signals callback list.

e.g.:

t = TestSignals()

# connect to a bound method
class C:

    def cb_func(self, i):
        print 'got class signal = ', 1

r = R()
key = t.connect('test-signal', r.cb_func)

...

t.disconnect(key)

Stopping and starting signals

Signals can be blocked on a per instance bassis or they can be blocked for all instances of the Callback class. disable_signals() can be used to block the signals for a single instance and disable_all_signals() can be used to block signals for the class:

e.g.:

class TestSignals(Callback):

 __signals__ = {
           'test-signal' : (int, ),
           'test-noarg'  : None
          }

 def __init__(self):
     Callback.__init__(self)

 def emit_signal(self):
     self.emit('test-signal', (1, ))

 t = TestSignals()

 # block signals from instance t
 t.disable_signals()

 ...

 # unblock
 t.enable_signals()

 # block all signals
 Callback.disable_all_signals()

 ...

 # unblock all signals
 Callback.enable_all_signals()

Any signals emitted whilst signals are blocked will be lost.

Debugging signal callbacks

To help with debugging the signals and callbacks you can turn on lots of logging information. To switch on logging for a single instance call enable_logging(), to switch it off again call disable_logging(). To switch on logging for all instance you can toggle Callback.__LOG_ALL to True.

connect(signal_name, callback)[source]

Connect a callable to a signal_name. The callable will be called with the signal is emitted. The callable must accept the argument types declared in the signals signature.

returns a unique key that can be passed to disconnect().

classmethod disable_all_signals()[source]
disable_logging()[source]
disable_signals()[source]
disconnect(key)[source]

Disconnect a callback.

disconnect_all()[source]
emit(signal_name, args=())[source]

Emit the signal called signal_name. The args must be a tuple of arguments that match the types declared for the signals signature.

classmethod enable_all_signals()[source]
enable_logging()[source]
enable_signals()[source]
classmethod log_all(enable)[source]
gramps.gen.utils.callback.log(text, /)

Write string to stream. Returns the number of characters written (which is always equal to the length of the string).

Module providing support for callback handling in the GUI
  • track object handles

  • register new handles

  • manage callback functions

class gramps.gen.utils.callman.CallbackManager(database)[source]

Bases: object

Manage callback handling from GUI to the db. It is unique to a db and some GUI element. When a db is changed, one should destroy the CallbackManager and set up a new one (or delete the GUI element as it shows info from a previous db).

Track changes to your relevant objects, calling callback functions as needed.

add_db_signal(name, callback)[source]

Do a custom db connect signal outside of the primary object ones managed automatically.

connect_all(keys=None)[source]

Convenience function, connects all database signals related to the primary objects given in keys to the callbacks attached to self. Note that only those callbacks registered with register_callbacks will effectively result in an action, so one can connect to all keys even if not all keys have a registered callback.

Parameters:

keys – list of keys of primary objects for which to connect the signals, default is no connects being done. One can enable signal activity to needed objects by passing a list, eg keys=[callman.SOURCEKEY, callman.PLACEKEY], or to all with keys=callman.KEYS

disconnect_all()[source]

Disconnect from all signals from the database This method should always be called before a the callback methods become invalid.

register_callbacks(callbackdict)[source]

register callback functions that need to be called for a specific db action. This function can be called several times, adding to and if needed overwriting, existing callbacks. No db connects are done. If a signal already is connected to the db, it is removed from the connect list of the db.

Parameters:

callbackdict – a dictionary with key one of KEYS+METHODS, or one of KEYS, and value a function to be called when signal is raised.

register_handles(ahandledict)[source]

Register handles that need to be tracked by the manager. This function can be called several times, adding to existing registered handles.

Parameters:

ahandledict – a dictionary with key one of the KEYS, and value a list of handles to track

register_obj(baseobj, directonly=False)[source]

Convenience method, will register all directly and not directly referenced prim objects connected to baseobj with the CallbackManager If directonly is True, only directly registered objects will be registered. Note that baseobj is not registered itself as it can be a sec obj.

unregister_all()[source]

Unregister all handles that are registered

unregister_handles(ahandledict)[source]

All handles in handledict are no longer tracked

Parameters:

handledict – a dictionary with key one of the KEYS, and value a list of handles to track

gramps.gen.utils.callman.directhandledict(baseobj)[source]

Build a handledict from baseobj with all directly referenced objects

gramps.gen.utils.callman.handledict(baseobj)[source]

Build a handledict from baseobj with all directly and not directly referenced base obj that are present

Configuration

Database

File

Image

Locale

GrampsLocale encapsulates localization and locale initialization. There’s a default locale object but more can be created with a different locale and translation binding to enable generating reports in languages and locales other than the one used for the user interface.

class gramps.gen.utils.grampslocale.GrampsLocale(localedir=None, lang=None, domain=None, languages=None)[source]

Bases: object

Encapsulate a locale. This class is a sort-of-singleton: The first instance created will query the environment and OSX defaults for missing parameters (precedence is parameters passed to the constructor, environment variables LANG, LC_COLLATE, LC_TIME, etc., and LANGUAGE, OSX defaults settings when that’s the platform). Subsequent calls to the constructor with no or identical parameters will return the same Grampslocale object. Construction with different parameters will result in a new GrampsLocale instance with the specified parameters, but any parameters left out will be filled in from the first instance.

Parameters:
  • localedir – The full path to the top level directory containing the translation files. Defaults to sys.prefix/share/locale.

  • lang – A single locale value which is used for unset locale.LC_FOO settings.

  • domain – The name of the applicable translation file. The default is “gramps”, indicating files in LC_MESSAGES named gramps.mo.

  • languages – String with a ‘:’-separated list of two or five character codes corresponding to subidrectries in the localedir, e.g.: “fr” or “zh_CN”.

DEFAULT_TRANSLATION_STR = 'default'
check_available_translations(loc)[source]

Test a locale for having a translation available locale – string with standard language code, locale code, or name

property date_displayer

Return the locale’s date displayer; if it hasn’t already been cached, set it from datehandler.LANG_TO_DISPLAY. If one isn’t available for the selected locale, attempt to fall back on the first_instance’s locale before settling on the ‘C’ displayer.

Note

This is the getter for the date_displayer property

property date_parser

Return the locale’s date parser; if it hasn’t already been cached, set it from datehandler.LANG_TO_PARSER. If one isn’t available for the selected locale, attempt to fall back on the first_instance’s locale before settling on the ‘C’ parser.

Note

This is the getter for the date_parser property

encoding = None
float(val)[source]

Parse a string to a floating point number. Uses locale.atof(), in future with ICU present will use icu.NumberFormat.parse().

format_string(fmt, val, grouping=False, monetary=False)[source]

Format a string in the current numeric locale. See python’s locale.format_string for details. ICU’s message formatting codes are incompatible with locale’s, so just use locale.format_string for now.

get_addon_translator(filename, domain='addon', languages=None)[source]

Get a translator for an addon.

Parameters:
  • filename – filename of a file in directory with full path, or None to get from self.

  • domain – the name of the .mo file under the LANG/LC_MESSAGES dir

  • languages – a list of languages to force

Returns:

a gettext.translation object

Example:

_ = glocale.get_addon_translator(languages=["fr_BE.utf8"]).gettext

See also

the python gettext documentation.

Assumes path/filename = path/locale/LANG/LC_MESSAGES/addon.mo.

get_available_translations(localedir=None, localedomain=None)[source]

Get a list of available translations.

Returns:

A list of translation languages.

Return type:

unicode[]

get_collation()[source]

Return the collation without any character encoding.

get_date(date)[source]

Return a string representing the date appropriate for the language being translated.

Parameters:

date (Date) – The date to be represented.

Returns:

The date as text in the proper language.

Return type:

unicode

get_language_dict()[source]

return a dictionary of language names : codes for use by language pickers.

get_language_list()[source]

Return the list of configured languages. Used by ViewManager.check_for_updates to select the language for the addons descriptions.

get_localedomain()[source]

Get the LOCALEDOMAIN used for the Gramps application. Required by gui/glade.py to pass to Gtk.Builder

get_type(name)[source]

Return a string representing the name appropriate for the language being translated.

Parameters:

name – The name type to be represented.

Returns:

The name as text in the proper language.

Return type:

unicode

locale_code()[source]

Return the locale code.

sort_key(string)[source]

Return a value suitable to pass to the “key” parameter of sorted()

strcoll(string1, string2)[source]

Given two localized strings, compare them and return -1 if string1 would sort first, 1 if string2 would, and 0 if they are the same.

trans_objclass(objclass_str)[source]

Translates objclass_str into “… %s”, where objclass_str is ‘Person’, ‘person’, ‘Family’, ‘family’, etc.

There is something of a mismatch between native Mac localization and that of Gtk applications like Gramps because Apple chose to use IBM’s more modern and more complete International Components for Unicode (ICU) for the purpose rather than the older POSIX and gettext based localization used by Gtk (and most other Linux applications).

For Gramps, the system defaults settings will be used only if the user hasn’t set the corresponding environment variable already.

Apple’s language list maps nicely to gettext’s LANGUAGE environment variable, so we use that if it’s set. There’s an additional MULTI-TRANSLATION environment variable which the user can set to allow incomplete translations to be supplemented from other translations on the list before resorting to the default english. Many users find this disconcerting, though, so it’s not enabled by default. If the user hasn’t set a translation list (this happens occasionally), we’ll check the locale and collation settings and use either to set $LANGUAGE if it’s set to a non-english locale.

Similarly, Apple provides an “Order for sorted lists” which maps directly to LC_COLLATE, and a Format>Region which maps to LANG. (Those are the names of the controls in System Preferences; the names in the defaults system are AppleCollationOrder and AppleLocale, respectively.)

The user can override the calendar, and thise value is appended to AppleLocale and parsed below. But Gramps sets the calendar in its own preferences, so it is ignored.

Where the mismatch becomes a problem is in date and number formatting. POSIX specifies a locale for this, but ICU uses format strings, and there is no good way to map those strings into one of the available locales. Users who whan to specify particular ways of formatting different from their base locales will have to figure out the appropriate locale on their own and set LC_TIME appropriately. The “Formats” page on the Languages & Text (International in Leopard) System Preferences pane is a good way to quickly assess the formats in various locales.

Neither Gramps nor Gtk supply a separate English translation, so if we encounter English in the language list we substitute “C”; if we must set $LANGUAGE from either locale or collation, we ignore an English locale, leaving $LANGUAGE unset (which is the same as setting it to “C”.

gramps.gen.utils.maclocale.mac_setup_localization(glocale)[source]

Set up the localization parameters from OSX’s “defaults” system, permitting environment variables to override the settings.

Place

Other