The gramps.gen.utils Module

Generic utilities useful for users of the gen package

Utilities

Callback

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.

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(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(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]
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

This package implements access to Gramps configuration.

class gramps.gen.utils.configmanager.ConfigManager(filename=None, plugins=None)[source]

Bases: object

Class to construct the singleton CONFIGMAN where all settings are stored.

PLUGINS = {}
check_type(value1, value2)[source]

Check if value1 and value2 are different types.

connect(key, func)[source]

Connect a callback func that gets called when key is changed.

disconnect(callback_id)[source]

Removes a callback given its callback ID. The ID is generated and returned when the function is connected to the key (section.setting).

emit(key)[source]

Emits the signal “key” which will call the callbacks associated with that setting.

get(key)[source]

Get the setting’s value. raise an error if an invalid section.setting. Key is a sting in the “section.setting” format.

get_default(key)[source]

Get the setting’s default value. Raises an error if invalid key is give. Key is a sting in the “section.setting” format.

get_manager(name)[source]
get_section_settings(section)[source]

Return all section setting names.

get_sections()[source]

Return all section names.

has_default(key)[source]

Does the setting have a default value? Returns True if it does, False otherwise. Key is a sting in the “section.setting” format.

has_manager(name)[source]
init()[source]

Either loads from an existing ini file, or saves to it.

is_set(key)[source]

Does the setting exist? Returns True if does, False otherwise. Key is a sting in the “section.setting” format.

load(filename=None, oldstyle=False)[source]

Loads an .ini into self.data.

register(key, default)[source]

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_manager(name, override=u'', use_plugins_path=True, use_config_path=False)[source]

Register a plugin manager.

Parameters:
  • name – is used as the key of the config manager singleton. It is also be used as the base filename (unless an override is given, or use_config_path or use_plugins_path is True).
  • override – is used to override the default location of the .ini file.
  • use_config_path – if True, use this ConfigManager’s path as the new manager’s path, ignoring any path given in override.

Override is either:

  • a full path+filename ending in .ini
  • a filename ending in .ini
  • a dir path to put ini file into
  • a full path+filename to get dir to put ini file into
  • a ConfigManager instance

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
reset(key=None)[source]

Resets one, a section, or all settings values to their defaults. This does not disconnect callbacks.

save(filename=None)[source]

Saves the current section/settings to an .ini file. Optional filename will override the default filename to save to, if given.

set(key, value)[source]

Set the setting’s value. There are only two ways to get into the data dictionary: via the load() method that reads a file, or from this method.

gramps.gen.utils.configmanager.safe_eval(exp)[source]

Configuration based utilities

gramps.gen.utils.config.get_researcher()[source]

Return a new database owner with the default values from the config file.

Database

A utility to make a best guess if a person is alive. This is used to provide privacy in reports and exports.

class gramps.gen.utils.alive.ProbablyAlive(db, max_sib_age_diff=None, max_age_prob_alive=None, avg_generation_gap=None)[source]

Bases: object

An object to hold the parameters for considering someone alive.

probably_alive_range(person, is_spouse=False)[source]
gramps.gen.utils.alive.probably_alive(person, db, current_date=None, limit=0, max_sib_age_diff=None, max_age_prob_alive=None, avg_generation_gap=None, return_range=False)[source]

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:
  • current_date – a date object that is not estimated or modified (defaults to today)
  • limit – number of years to check beyond death_date
  • max_sib_age_diff – maximum sibling age difference, in years
  • max_age_prob_alive – maximum age of a person, in years
  • avg_generation_gap – average generation gap, in years
gramps.gen.utils.alive.probably_alive_range(person, db, max_sib_age_diff=None, max_age_prob_alive=None, avg_generation_gap=None)[source]

Computes estimated birth and death dates. Returns: (birth_date, death_date, explain_text, related_person)

gramps.gen.utils.alive.update_constants()[source]

Used to update the constants that are cached in this module.

Utilities for getting information from the database.

gramps.gen.utils.db.family_name(family, db, noname='unknown')[source]

Builds a name for the family from the parents names

gramps.gen.utils.db.find_children(db, p)[source]

Return the list of all children’s IDs for a person.

gramps.gen.utils.db.find_parents(db, p)[source]

Return the unique list of all parents’ IDs for a person.

gramps.gen.utils.db.find_witnessed_people(db, p)[source]
gramps.gen.utils.db.for_each_ancestor(db, start, func, data)[source]

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.

gramps.gen.utils.db.get_age(db, person, fallback=True, calendar='gregorian')[source]

Compute the age of person.

Parameters:
  • person – person handle or person object
  • fallback – Allow fallback events if True
Returns:

tuple of year, month day if valid, None otherwise

gramps.gen.utils.db.get_birth_or_fallback(db, person, format=None)[source]

Get BIRTH event from a person, or fallback to an event around the time of birth.

gramps.gen.utils.db.get_citation_referents(citation_handle, db)[source]

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.

gramps.gen.utils.db.get_death_or_fallback(db, person, format=None)[source]

Get a DEATH event from a person, or fallback to an event around the time of death.

gramps.gen.utils.db.get_divorce_or_fallback(db, family, format=None)[source]

Get a DIVORCE event from a family, or fallback to an alternative event type.

gramps.gen.utils.db.get_event_ref(db, family, event_type)[source]

Return a reference to a primary family event of the given event type.

gramps.gen.utils.db.get_marriage_or_fallback(db, family, format=None)[source]

Get a MARRIAGE event from a family, or fallback to an alternative event type.

gramps.gen.utils.db.get_media_referents(media_handle, db)[source]

Find objects that refer the media object.

This function finds all primary objects that refer to a given media handle in a given database.

gramps.gen.utils.db.get_note_referents(note_handle, db)[source]

Find objects that refer a note object.

This function finds all primary objects that refer to a given note handle in a given database.

gramps.gen.utils.db.get_participant_from_event(db, event_handle, all_=False)[source]

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.

gramps.gen.utils.db.get_primary_event_ref_list(db, family)[source]

Return a reference to the primary events of the family.

gramps.gen.utils.db.get_referents(handle, db, primary_objects)[source]

Find objects that refer to an object.

This function is the base for other get_<object>_referents functions.

gramps.gen.utils.db.get_source_and_citation_referents(source_handle, db)[source]

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.

Objects -> Citations -> Source
e.g.
Media object M1 -> Citation C1 -> Source S1
Media object M2 -> Citation C1 -> Source S1
Person object P1 -> Citation C2 -> Source S1

The returned structure is rather ugly, but provides all the information in a way that is consistent with the other Util functions.

(
tuple of objects that refer to the source - only first element is present
([C1, C2],),
list of citations with objects that refer to them
[
(C1,
tuple of reference lists
P, F, E, Pl, S, M, R
([], [], [], [], [], [M1, M2]. [])
)
(C2,
tuple of reference lists
P, F, E, Pl, S, M, R
([P1], [], [], [], [], []. [])
)
]
)
gramps.gen.utils.db.get_source_referents(source_handle, db)[source]

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

gramps.gen.utils.db.get_timeperiod(db, person)[source]

Compute the timeperiod a person lived in

Parameters:person – person handle or person object
Returns:the year, None otherwise
gramps.gen.utils.db.navigation_label(db, nav_type, handle)[source]
gramps.gen.utils.db.preset_name(basepers, name, sibling=False)[source]

Fill up name with all family common names of basepers. If sibling=True, pa/matronymics are retained.

Make an ‘Unknown’ primary object

gramps.gen.utils.unknown.add_personref_to_family(family, person)[source]

Given a family and person, set the parent/child references in the family, that match the person.

gramps.gen.utils.unknown.create_explanation_note(dbase)[source]

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.

gramps.gen.utils.unknown.make_unknown(class_arg, explanation, class_func, commit_func, transaction, **argv)[source]

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:
  • class_arg (unspecified) – The argument the class_func needs, typically a kind of id.
  • explanation (str) – Handle of a note that explains the origin of primary obj
  • class_func (method) – Method to create primary object.
  • commit_func (method) – Method to store primary object in db.
  • transactino – Database transaction handle
  • argv – Possible additional parameters
Returns:

List of newly created objects.

Return type:

list

File

File and folder related utility functions

gramps.gen.utils.file.create_checksum(full_path)[source]

Create a md5 hash for the given file.

gramps.gen.utils.file.find_file(filename)[source]
gramps.gen.utils.file.find_folder(filename)[source]
gramps.gen.utils.file.get_empty_tempdir(dirname)[source]

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)

gramps.gen.utils.file.get_new_filename(ext, folder='~/')[source]
gramps.gen.utils.file.media_path(db)[source]

Given a database, return the mediapath to use as basedir for media

gramps.gen.utils.file.media_path_full(db, filename)[source]

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

gramps.gen.utils.file.relative_path(original, base)[source]

Calculate the relative path from base to original, with base a directory, and original an absolute path On problems, original is returned unchanged

gramps.gen.utils.file.rm_tempdir(path)[source]

Remove a tempdir created with get_empty_tempdir

gramps.gen.utils.file.search_for(name)[source]

Image

Image manipulation routines.

gramps.gen.utils.image.crop_percentage_to_pixel(width, height, crop)[source]
gramps.gen.utils.image.crop_percentage_to_subpixel(width, height, crop)[source]

Convert from Gramps cropping coordinates [0, 100] to pixels, given image width and height. No rounding to pixel resolution.

gramps.gen.utils.image.image_actual_size(x_cm, y_cm, x, y)[source]

Calculate what the actual width & height of the image should be.

Parameters:
  • x_cm – width in centimeters
  • y_cm – height in centimeters
  • x – desired width in pixels
  • y – desired height in pixels
Return type:

tuple(int, int)

Returns:

a tuple consisting of the width and height in centimeters

gramps.gen.utils.image.image_dpi(source)[source]

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)
gramps.gen.utils.image.image_size(source)[source]

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
gramps.gen.utils.image.resize_to_buffer(source, size, crop=None)[source]

Loads the image and resizes it. Instead of saving the file, the data is returned in a buffer.

Parameters:
  • source (unicode) – source image file, in any format that gtk recognizes
  • size (list) – desired size of the destination image ([width, height])
  • crop (array of integers ([start_x, start_y, end_x, end_y])) – cropping coordinates
Return type:

buffer of data

Returns:

raw data

gramps.gen.utils.image.resize_to_jpeg(source, destination, width, height, crop=None)[source]

Create the destination, derived from the source, resizing it to the specified size, while converting to JPEG.

Parameters:
  • source (unicode) – source image file, in any format that gtk recognizes
  • destination (unicode) – destination image file, output written in jpeg format
  • width (int) – desired width of the destination image
  • height (int) – desired height of the destination image
  • crop (array of integers ([start_x, start_y, end_x, end_y])) – cropping coordinates
gramps.gen.utils.image.resize_to_jpeg_buffer(source, size, crop=None)[source]

Loads the image, converting the file to JPEG, and resizing it. Instead of saving the file, the data is returned in a buffer.

Parameters:
  • source (unicode) – source image file, in any format that gtk recognizes
  • size (list) – desired size of the destination image ([width, height])
  • crop (array of integers ([start_x, start_y, end_x, end_y])) – cropping coordinates
Return type:

buffer of data

Returns:

jpeg image as raw data

Locale

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(locale)[source]

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

date_displayer[source]

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

date_parser[source]

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(format, val, grouping=False, monetary=False)[source]

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_string(format, val, grouping=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_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
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.

class gramps.gen.utils.grampslocale.GrampsNullTranslations(fp=None)[source]

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.

language()[source]

The null translation returns the raw msgids, which are in English

lexgettext(msgid, sep='|')
sgettext(msgid, sep='|')[source]
class gramps.gen.utils.grampslocale.GrampsTranslations(fp=None)[source]

Bases: gettext.GNUTranslations

Overrides and extends gettext.GNUTranslations. See the Python gettext “Class API” documentation for how to use this.

gettext(msgid)[source]

Obtain translation of gettext, return a unicode object

Parameters:msgid (unicode) – The string to translated.
Returns:Translation or the original.
Return type:unicode
language()[source]

Return the target languge of this translations object.

lexgettext(msgid)[source]

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:

  1. “Uninflectable”
  2. “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))
ngettext(singular, plural, num)[source]

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:
  • singular (unicode) – The singular form of the string to be translated. may contain a context seperator
  • plural (unicode) – The plural form of the string to be translated.
  • num (int) – the amount for which to decide the translation
Returns:

Translation or the original.

Return type:

unicode

sgettext(msgid, sep='|')[source]

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:
  • msgid (unicode) – The string to translated.
  • sep (unicode) – The separator marking the context.
Returns:

Translation or the original with context stripped.

Return type:

unicode

class gramps.gen.utils.grampslocale.Lexeme[source]

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.

f[source]

Dictionary of the lexeme forms

variants()[source]

All lexeme forms, in the same order as given upon construction. The first one returned is the default form, which is used when the Lexeme instance is used in lieu of a string object.

Same as f.values()

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”.

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.

Keyword translation interface

gramps.gen.utils.keyword.get_keyword_from_translation(word)[source]

Return the keyword of translation

gramps.gen.utils.keyword.get_keywords()[source]

Get all keywords, longest to shortest

gramps.gen.utils.keyword.get_translation_from_keyword(keyword)[source]

Return the translation of keyword

gramps.gen.utils.keyword.get_translations()[source]

Get all translations, longest to shortest

Place

gramps.gen.utils.place.atanh(x)[source]

arctangent hyperbolicus

gramps.gen.utils.place.conv_lat_lon(latitude, longitude, format=u'D.D4')[source]

Convert given string latitude and longitude to a required format.

Parameters:
  • latitude (string) – Latitude
  • longitude (string) – Longitude
  • format (string) – Ouput format
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:

  • -90 <= latitude <= +90 with +00 the equator
  • -180 <= longitude < +180 with +000 prime meridian and -180 the 180th meridian

Other

Utility functions to cast types

gramps.gen.utils.cast.cast_to_bool(val)[source]
gramps.gen.utils.cast.conv_dbstr_to_unicode(x)
gramps.gen.utils.cast.get_type_converter(val)[source]

Return function that converts strings into the type of val.

gramps.gen.utils.cast.get_type_converter_by_name(val_str)[source]

Return function that converts strings into the type given by val_str.

Only numbers and strings are supported. The rest becomes strings (unicode).

gramps.gen.utils.cast.type_name(val)[source]

Return the name the type of val.

Only numbers and strings are supported. The rest becomes strings (unicode).

Utilities to create unique identifiers

gramps.gen.utils.id.create_id()[source]
gramps.gen.utils.id.create_uid(self, handle=None)[source]

Parses the lds.xml file to build the temple/code maps

class gramps.gen.utils.lds.LdsTemples[source]

Bases: object

Parsing class for the LDS temples file

code(name)[source]

returns the LDS Temple code that corresponds to the name

is_valid_code(code)[source]

returns True if the code is a valid LDS temple code according to the lds.xml file

is_valid_name(name)[source]

returns True if the name matches a temple name (not code) in the lds.xml file

name(code)[source]

returns the name associated with the LDS Temple code

name_code_data()[source]

returns a list of temple codes, temple name tuples

String mappings for constants

gramps.gen.utils.string.format_gender(type)[source]

Table Of Contents

Previous topic

The gramps.gen.proxy Module

Next topic

The cli Module

This Page