Generic utilities useful for users of the gen package
Introduction
Gramps is devided 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.
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(object):
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(object):
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 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().
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.
Do a custom db connect signal outside of the primary object ones managed automatically.
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 from all signals from the database This method should always be called before a the callback methods become invalid.
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 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 |
---|
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.
This package implements access to Gramps configuration.
Bases: object
Class to construct the singleton CONFIGMAN where all settings are stored.
Removes a callback given its callback ID. The ID is generated and returned when the function is connected to the key (section.setting).
Emits the signal “key” which will call the callbacks associated with that setting.
Get the setting’s value. raise an error if an invalid section.setting. Key is a sting in the “section.setting” format.
Get the setting’s default value. Raises an error if invalid key is give. Key is a sting in the “section.setting” format.
Does the setting have a default value? Returns True if it does, False otherwise. Key is a sting in the “section.setting” format.
Does the setting exist? Returns True if does, False otherwise. Key is a sting in the “section.setting” format.
Register a section.setting, and set the default. Will overwrite any previously set default, and set setting if not one. The default value deterimines the type of the setting.
Register a plugin manager.
Parameters: |
|
---|
Override is either:
Examples:
>>> config.register_manager("Simple", use_plugins_path=False)
# will use the calling programs directory, and "Simple.ini"
>>> config.register_manager("Simple", __file__,
use_plugins_path=False)
# will use the __file__'s directory, and "Simple.ini"
>>> config.register_manager("Simple", "c:\temp",
use_plugins_path=False)
# will use the given directory, "c:\temp\Simple.ini"
>>> config.register_manager("Simple", use_config_path=True)
# will use config's path: ~/.gramps/gramps32/Simple.ini
>>> config.register_manager("Simple", "Other.ini")
# will use config + plugins path: ~/.gramps/gramps32/plugins/Other.ini
>>> config.register_manager("Simple", "/tmp/Other.ini",
use_plugins_path=False)
# will use /tmp/Other.ini
Resets one, a section, or all settings values to their defaults. This does not disconnect callbacks.
Configuration based utilities
A utility to make a best guess if a person is alive. This is used to provide privacy in reports and exports.
Bases: object
An object to hold the parameters for considering someone alive.
Return true if the person may be alive on current_date.
This works by a process of elimination. If we can’t find a good reason to believe that someone is dead then we assume they must be alive.
Parameters: |
|
---|
Computes estimated birth and death dates. Returns: (birth_date, death_date, explain_text, related_person)
Used to update the constants that are cached in this module.
Utilities for getting information from the database.
Builds a name for the family from the parents names
Return the list of all children’s IDs for a person.
Return the unique list of all parents’ IDs for a person.
Recursively iterate (breadth-first) over ancestors of people listed in start. Call func(data, pid) for the Id of each person encountered. Exit and return 1, as soon as func returns true. Return 0 otherwise.
Compute the age of person.
Parameters: |
|
---|---|
Returns: | tuple of year, month day if valid, None otherwise |
Get BIRTH event from a person, or fallback to an event around the time of birth.
Find objects that refer the citation.
This function finds all primary objects that refer (directly or through secondary child-objects) to a given citation handle in a given database.
Get a DEATH event from a person, or fallback to an event around the time of death.
Get a DIVORCE event from a family, or fallback to an alternative event type.
Return a reference to a primary family event of the given event type.
Get a MARRIAGE event from a family, or fallback to an alternative event type.
Find objects that refer the media object.
This function finds all primary objects that refer to a given media handle in a given database.
Find objects that refer a note object.
This function finds all primary objects that refer to a given note handle in a given database.
Obtain the first primary or family participant to an event we find in the database. Note that an event can have more than one primary or family participant, only one is returned, adding ellipses if there are more. If the all_ parameter is true a comma-space separated string with the names of all primary participants is returned and no ellipses is used.
Return a reference to the primary events of the family.
Find objects that refer to an object.
This function is the base for other get_<object>_referents functions.
Find all citations that refer to the sources, and recursively, all objects that refer to the sources.
This function finds all primary objects that refer (directly or through secondary child-objects) to a given source handle in a given database.
The returned structure is rather ugly, but provides all the information in a way that is consistent with the other Util functions.
Find objects that refer the source.
This function finds all primary objects that refer (directly or through secondary child-objects) to a given source handle in a given database.
Only Citations can refer to sources, so that is all we need to check
Compute the timeperiod a person lived in
Parameters: | person – person handle or person object |
---|---|
Returns: | the year, None otherwise |
Fill up name with all family common names of basepers. If sibling=True, pa/matronymics are retained.
Make an ‘Unknown’ primary object
Given a family and person, set the parent/child references in the family, that match the person.
When creating objects to fill missing primary objects in imported files, those objects of type “Unknown” need a explanatory note. This funcion provides such a note for import methods.
Make a primary object and set some property so that it qualifies as “Unknown”.
Some object types need extra parameters: Family: db, Event: type (optional), Citation: methods to create/store source.
Some theoretical underpinning This function exploits the fact that all import methods basically do the same thing: Create an object of the right type, fill it with some attributes, store it in the database. This function does the same, so the observation is why not use the creation and storage methods that the import routines use themselves, that makes nice reuse of code. To do this formally correct we would need to specify a interface (in the OOP sence) which the import methods would need to implement. For now, that is deemed too restrictive and here we just slip through because of the similarity in code of both GEDCOM and XML import methods.
Parameters: |
|
---|---|
Returns: | List of newly created objects. |
Return type: | list |
File and folder related utility functions
Return path to TEMP_DIR/dirname, a guaranteed empty directory
makes intervening directories if required fails if _file_ by that name already exists, or for inadequate permissions to delete dir/files or create dir(s)
Given a database, return the mediapath to use as basedir for media
Given a database and a filename of a media, return the media filename is full form, eg ‘graves/tomb.png’ becomes ‘/home/me/genea/graves/tomb.png
Image manipulation routines.
Convert from Gramps cropping coordinates [0, 100] to pixels, given image width and height. No rounding to pixel resolution.
Calculate what the actual width & height of the image should be.
Parameters: |
|
---|---|
Return type: | tuple(int, int) |
Returns: | a tuple consisting of the width and height in centimeters |
Return the dpi found in the image header. Use a sensible default of the screen DPI or 96.0 dpi if N/A.
Parameters: | source (unicode) – source image file, in any format that PIL recognizes |
---|---|
Return type: | int |
Returns: | (x_dpi, y_dpi) |
Return the width and size of the specified image.
Parameters: | source (unicode) – source image file, in any format that gtk recongizes |
---|---|
Return type: | tuple(int, int) |
Returns: | a tuple consisting of the width and height |
Loads the image and resizes it. Instead of saving the file, the data is returned in a buffer.
Parameters: |
|
---|---|
Return type: | buffer of data |
Returns: | raw data |
Create the destination, derived from the source, resizing it to the specified size, while converting to JPEG.
Parameters: |
|
---|
Loads the image, converting the file to JPEG, and resizing it. Instead of saving the file, the data is returned in a buffer.
Parameters: |
|
---|---|
Return type: | buffer of data |
Returns: | jpeg image as raw data |
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: |
|
---|
Test a locale for having a translation available locale – string with standard language code, locale code, or name
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
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
Parse a string to a floating point number. Uses locale.atof(), in future with ICU present will use icu.NumberFormat.parse().
Format a number in the current numeric locale. See python’s locale.format for details. ICU’s formatting codes are incompatible with locale’s, so just use locale.format for now.
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 a translator for an addon.
Parameters: |
|
---|---|
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 a list of available translations.
Returns: | A list of translation languages. |
---|---|
Return type: | unicode[] |
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 |
return a dictionary of language names : codes for use by language pickers.
Return the list of configured languages. Used by ViewManager.check_for_updates to select the language for the addons descriptions.
Get the LOCALEDOMAIN used for the Gramps application. Required by gui/glade.py to pass to Gtk.Builder
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 |
Bases: gettext.NullTranslations
Extends gettext.NullTranslations to provide the sgettext method.
Note that it’s necessary for msgid to be unicode. If it’s not, neither will be the returned string.
Bases: gettext.GNUTranslations
Overrides and extends gettext.GNUTranslations. See the Python gettext “Class API” documentation for how to use this.
Obtain translation of gettext, return a unicode object
Parameters: | msgid (unicode) – The string to translated. |
---|---|
Returns: | Translation or the original. |
Return type: | unicode |
Extract all inflections of the same lexeme, stripping the ‘|’-separated context using sgettext()
The resulting message provided by the translator is supposed to be ‘|’-separated as well. The possible formats are either (1) a single string for a language with no inflections, or (2) a list of <inflection name>=<inflected form>, separated with ‘|’. For example:
- “Uninflectable”
- “n=Inflected-nominative|g=Inflected-genitive|d=Inflected-dative”
See Lexeme documentation for detailed explanation and example.
Parameters: | msgid (unicode) – The string to translated. |
---|---|
Returns: | Translation or the original with context stripped. |
Return type: | unicode (for option (1)) / Lexeme (option (2)) |
The translation of singular/plural is returned unless the translation is not available and the singular contains the separator. In that case, the returned value is the singular.
Parameters: |
|
---|---|
Returns: | Translation or the original. |
Return type: | unicode |
Strip the context used for resolving translation ambiguities.
The translation of msgid is returned unless the translation is not available and the msgid contains the separator. In that case, the returned value is the portion of msgid following the last separator. Default separator is ‘|’.
Parameters: |
|
---|---|
Returns: | Translation or the original with context stripped. |
Return type: | unicode |
Bases: unicode
Created with lexgettext()
Example
Python code:
_ = lexgettext
dec = _("localized lexeme inflections||December")
xmas = _("lexeme||Christmas")
text = _("{holiday} is celebrated in {month}".format(
holiday=xmas, month=dec))
greeting = _("Merry {holiday}!").format(holiday=xmas)
XMAS = xmas.upper()
print ("\n".join([XMAS, text, greeting]))
Translation database (Russian example):
msgid "lexeme||December"
msgstr "NOMINATIVE=декабрь|GENITIVE=декабря|ABLATIVE=декабрём|LOCATIVE=декабре"
msgid "lexeme||Christmas"
msgstr "NOMINATIVE=рождество|GENITIVE=рождества|ABLATIVE=рождеством"
msgid "{holiday} is celebrated in {month}"
msgstr "{holiday} празднуют в {month.f[LOCATIVE]}"
msgid "Merry {holiday}!"
msgstr "Счастливого {holiday.f[GENITIVE]}!"
Prints out:
In English locale:
CHRISTMAS
Christmas is celebrated in December
Merry Christmas!
In Russian locale:
РОЖДЕСТВО
рождество празднуют в декабре
Счастливого рождества!
Description
Stores an arbitrary number of forms, e.g., inflections. These forms are accessible under dictionary keys for each form. The names of the forms are language-specific. They are assigned by the human translator of the corresponding language (in XX.po) as in the example above, see lexgettext() docs for more info.
The translated format string can then refer to a specific form of the lexeme using .f and square brackets: {holiday.f[GENITIVE]} expects holiday to be a Lexeme which has a form 'GENITIVE' in it.
An instance of Lexeme can also be used as a regular unicode string. In this case, the work will be delegated to the string for the very first form provided in the translated string. In the example above, {holiday} in the translated string will expand to the Russian nominative form for Christmas, and xmas.upper() will produce the same nominative form in capital letters.
Motivation
Lexeme is the term used in linguistics for the set of forms taken by a particular word, e.g. cases for a noun or tenses for a verb.
Gramps often needs to compose sentences from several blocks of text and single words, often by using python string formatting.
For instance, formatting a date range is done similarly to this:
_("Between {startdate_month} {startdate_year}"
"and {enddate_month} {enddate_year}").format(
startdate_month = m1,
startdate_year = y1,
enddate_month = m2,
enddate_year = y2)
To make such text translatable, the arguments injected into format string need to bear all the linguistical information on how to plug them into a sentence, i.e., the forms, depending on the linguistic context of where the argument appears. The format string needs to select the relevant linguistic form. This is why m1 and m2 are instances of Lexeme.
On the other hand, for languages where there is no linguistic variation in such sentences, the code needs not to be aware of the underlying Lexeme complexity; and so they can be processed just like simple strings both when passed around in the code and when formatted.
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 currency and calendar, and those values are appended to AppleLocale and parsed below. But Gramps makes no use of currency and sets the calendar in its own preferences, so they’re 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 and LC_NUMERIC 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”.
Set up the localization parameters from OSX’s “defaults” system, permitting environment variables to override the settings.
Keyword translation interface
Return the keyword of translation
Convert given string latitude and longitude to a required format.
Parameters: |
|
---|---|
Returns: | a tuple of 2 strings, or a string (for ISO formats). If conversion fails: returns: (None, None) or None (for ISO formats) |
Possible formats:
Format | Description |
---|---|
‘D.D4’ | degree notation, 4 decimals eg +12.0154 , -124.3647 |
‘D.D8’ | degree notation, 8 decimals (precision like ISO-DMS) eg +12.01543265 , -124.36473268 |
‘DEG’ | degree, minutes, seconds notation eg 50°52‘21.92’‘N , 124°52‘21.92’‘E ° has UTF-8 code c2b00a or N50º52‘21.92” , E14º52‘21.92” º has UTF-8 code c2ba0a or N50º52.3456’ , E14º52.9876’ ; decimal minutes, no seconds |
‘DEG-:’ | degree, minutes, seconds notation with : eg -50:52:21.92 , 124:52:21.92 |
‘ISO-D’ | ISO 6709 degree notation i.e. ±DD.DDDD±DDD.DDDD |
‘ISO-DM’ | ISO 6709 degree, minutes notation i.e. ±DDMM.MMM±DDDMM.MMM |
‘ISO-DMS’ | ISO 6709 degree, minutes, seconds notation i.e. ±DDMMSS.SS±DDDMMSS.SS |
‘RT90’ | Output format for the Swedish coordinate system RT90 |
Some generalities:
Utility functions to cast types
Return function that converts strings into the type of val.
Return function that converts strings into the type given by val_str.
Only numbers and strings are supported. The rest becomes strings (unicode).
Return the name the type of val.
Only numbers and strings are supported. The rest becomes strings (unicode).
Utilities to create unique identifiers
Parses the lds.xml file to build the temple/code maps
Bases: object
Parsing class for the LDS temples file
returns True if the code is a valid LDS temple code according to the lds.xml file
String mappings for constants