Ejemplo n.º 1
0
def open_file_with_default_application(file_name):
    """
    Launch a program to open an arbitrary file. The file will be opened using
    whatever program is configured on the host as the default program for that
    type of file.

    @param file_path: The path to the file to be opened.
        Example: "c:\\foo.txt"
    @type file_path: string
    @return: nothing
    """
    errstrings = None

    norm_path = os.path.normpath(file_name)
    if not os.path.exists(norm_path):
        display_error_dialog(0, _("File does not exist"))
        return

    if constfunc.win():
        try:
            os.startfile(norm_path)
        except WindowsError, msg:
            display_error_dialog(0, str(msg))

        return
Ejemplo n.º 2
0
    def write_object(self, obj, index=1):
        self.write_primary_tag("object", obj, index)
        handle = obj.get_gramps_id()
        mime_type = obj.get_mime_type()
        path = obj.get_path()
        desc = obj.get_description()
        if desc:
            desc_text = ' description="%s"' % self.fix(desc)
        else:
            desc_text = ''
        if self.strip_photos == 1:
            path = os.path.basename(path)
        elif self.strip_photos == 2 and (len(path)>0 and os.path.isabs(path)):
            drive, path = os.path.splitdrive(path)
            path = path[1:]
        if constfunc.win():
            # Always export path with \ replaced with /. Otherwise import
            # from Windows to Linux of gpkg's path to images does not work. 
            path = path.replace('\\','/')
        self.g.write('%s<file src="%s" mime="%s"%s/>\n'
                     % ("  "*(index+1), self.fix(path), self.fix(mime_type), 
                        desc_text))
        self.write_attribute_list(obj.get_attribute_list())
        self.write_note_list(obj.get_note_list(), index+1)
        dval = obj.get_date_object()
        if not dval.is_empty():
            self.write_date(dval, index+1)
        for citation_handle in obj.get_citation_list():
            self.write_ref("citationref", citation_handle, index+1)

        for tag_handle in obj.get_tag_list():
            self.write_ref("tagref", tag_handle, index+1)

        self.g.write("%s</object>\n" % ("  "*index))
Ejemplo n.º 3
0
def get_identity():
    if constfunc.lin():
        platform = "X11"
    elif constfunc.win():
        platform = "Windows"
    elif constfunc.mac():
        platform = "Macintosh"
    else:
        platform = "Unknown"
    (lang_country, modifier) = locale.getlocale()
    lang = lang_country.replace('_', '-')
    #lang += ", " + lang_country.split('_')[0]
    return "Mozilla/5.0 (%s; U; %s) Gramps/3.2" % (platform, lang)
Ejemplo n.º 4
0
    def load_icons(self, icons, dir):
        """
        Load icons in the iconfactory of gramps, so they can be used in the
        plugin.
        
        ..attribute icons: 
          New stock icons to register. A list of tuples (stock_id, icon_label), 
          eg: 
            [('gramps_myplugin', _('My Plugin')), 
            ('gramps_myplugin_open', _('Open Plugin'))]
          The plugin directory must contain the directories scalable, 48x48, 22x22
          and 16x16 with the icons, eg in dir we have:
            scalable/gramps_myplugin.svg
            48x48/gramps_myplugin.png
            22x22/gramps_myplugin.png
        ..attribute dir: directory from where to load the icons
        """
        if win():
            iconpaths = [
                (os.path.join(dir, '48x48'), '.png'),
                (dir, '.png'),
            ]
        else:
            iconpaths = [
                (os.path.join(dir, 'scalable'), '.svg'),
                (dir, '.svg'),
                (dir, '.png'),
            ]

        #sizes: menu=16, small_toolbar=18, large_toolbar=24,
        #       button=20, dnd=32, dialog=48
        #add to the back of this list to overrule images set at beginning of list
        extraiconsize = [
            (os.path.join(dir, '22x22'), gtk.ICON_SIZE_LARGE_TOOLBAR),
            (os.path.join(dir, '16x16'), gtk.ICON_SIZE_MENU),
            (os.path.join(dir, '22x22'), gtk.ICON_SIZE_BUTTON),
        ]

        items = []
        for stock_id, label in icons:
            items.append((stock_id, label, gtk.gdk.CONTROL_MASK, 0, ''))

        base_reg_stock_icons(iconpaths, extraiconsize, items)
Ejemplo n.º 5
0
def time_val(dirpath):
    """
    Return the last modified time of the database. We do this by looking
    at the modification time of the meta db file. If this file does not 
    exist, we indicate that database as never modified.
    """
    meta = os.path.join(dirpath, META_NAME)
    if os.path.isfile(meta):
        tval = os.stat(meta)[9]
        # This gives creation date in Windows, but correct date in Linux
        if constfunc.win():
            # Try to use last modified date instead in Windows
            # and check that it is later than the creation date.
            tval_mod = os.stat(meta)[8]
            if tval_mod > tval:
                tval = tval_mod
        last = time.strftime('%x %X', time.localtime(tval))
    else:
        tval = 0
        last = _("Never")
    return (tval, last)
Ejemplo n.º 6
0
def time_val(dirpath):
    """
    Return the last modified time of the database. We do this by looking
    at the modification time of the meta db file. If this file does not 
    exist, we indicate that database as never modified.
    """
    meta = os.path.join(dirpath, META_NAME)
    if os.path.isfile(meta):
        tval = os.stat(meta)[9]
        # This gives creation date in Windows, but correct date in Linux
        if constfunc.win():
            # Try to use last modified date instead in Windows
            # and check that it is later than the creation date.
            tval_mod = os.stat(meta)[8]
            if tval_mod > tval:
                tval = tval_mod
        last = time.strftime('%x %X', time.localtime(tval))
    else:
        tval = 0
        last = _("Never")
    return (tval, last)
Ejemplo n.º 7
0
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data, 
        and decide if this is a move or a reorder.
        The only data we accept on mediaview is dropping a file, so URI_LIST. 
        We assume this is what we obtain
        """
        if not sel_data:
            return
        #modern file managers provide URI_LIST. For Windows split sel_data.data
        if constfunc.win():
            files = sel_data.data.split('\n')
        else:
            files = sel_data.get_uris()
        for file in files:
            clean_string = Utils.fix_encoding(
                file.replace('\0', ' ').replace("\r", " ").strip())
            protocol, site, mfile, j, k, l = urlparse.urlparse(clean_string)
            if protocol == "file":
                name = unicode(
                    urllib.url2pathname(
                        mfile.encode(sys.getfilesystemencoding())))
                mime = gen.mime.get_type(name)
                if not gen.mime.is_valid_type(mime):
                    return
                photo = gen.lib.MediaObject()
                base_dir = unicode(Utils.media_path(self.dbstate.db))
                if os.path.exists(base_dir):
                    name = Utils.relative_path(name, base_dir)
                photo.set_path(name)
                photo.set_mime_type(mime)
                basename = os.path.basename(name)
                (root, ext) = os.path.splitext(basename)
                photo.set_description(root)
                with DbTxn(_("Drag Media Object"), self.dbstate.db) as trans:
                    self.dbstate.db.add_object(photo, trans)
        widget.emit_stop_by_name('drag_data_received')
Ejemplo n.º 8
0
import os
import time
import copy
import subprocess
import urlparse
from gen.ggettext import gettext as _
#-------------------------------------------------------------------------
#
# set up logging
#
#-------------------------------------------------------------------------
import logging
LOG = logging.getLogger(".DbManager")

import constfunc
if constfunc.win():
    _RCS_FOUND = os.system("rcs -V >nul 2>nul") == 0
    if _RCS_FOUND and "TZ" not in os.environ:
        # RCS requires the "TZ" variable be set.
        os.environ["TZ"] = str(time.timezone)
else:
    _RCS_FOUND = os.system("rcs -V >/dev/null 2>/dev/null") == 0

#-------------------------------------------------------------------------
#
# GTK/Gnome modules
#
#-------------------------------------------------------------------------
import gtk
from gtk.gdk import ACTION_COPY
import pango
Ejemplo n.º 9
0
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from _DateParser import DateParser
from _DateDisplay import DateDisplay, DateDisplayEn
import constfunc

#-------------------------------------------------------------------------
#
# Constants
#
#-------------------------------------------------------------------------
if not constfunc.win():
    LANG = locale.getlocale(locale.LC_TIME)[0]
else:
    if 'LC_TIME' in os.environ:
        LANG = os.environ['LC_TIME']
    elif 'LANG' in os.environ:
        LANG = os.environ['LANG']
    else:
        LANG = locale.getdefaultlocale(locale.LC_TIME)[0]

# If LANG contains ".UTF-8" use only the part to the left of "."
# Otherwise some date handler will not load.
if LANG and ".UTF-8" in LANG.upper():
    LANG = LANG.split(".")[0]

if not LANG:
Ejemplo n.º 10
0
        unicode(locale.nl_langinfo(locale.ABDAY_3),codeset), # Tuesday
        unicode(locale.nl_langinfo(locale.ABDAY_4),codeset), # Wednesday
        unicode(locale.nl_langinfo(locale.ABDAY_5),codeset), # Thursday
        unicode(locale.nl_langinfo(locale.ABDAY_6),codeset), # Friday
        unicode(locale.nl_langinfo(locale.ABDAY_7),codeset), # Saturday
        )

    tformat = locale.nl_langinfo(locale.D_FMT).replace('%y','%Y')
    # GRAMPS treats dates with '-' as ISO format, so replace separator on 
    # locale dates that use '-' to prevent confict
    tformat = tformat.replace('-', '/') 

except:
    import time

    if constfunc.win() or constfunc.mac():
        codeset = locale.getlocale()[1]
    else:
        codeset = locale.getpreferredencoding()

    month_to_int = {
        unicode(time.strftime('%B',(0,1,1,1,1,1,1,1,1)),codeset).lower() : 1,
        unicode(time.strftime('%b',(0,1,1,1,1,1,1,1,1)),codeset).lower() : 1,
        unicode(time.strftime('%B',(0,2,1,1,1,1,1,1,1)),codeset).lower() : 2,
        unicode(time.strftime('%b',(0,2,1,1,1,1,1,1,1)),codeset).lower() : 2,
        unicode(time.strftime('%B',(0,3,1,1,1,1,1,1,1)),codeset).lower() : 3,
        unicode(time.strftime('%b',(0,3,1,1,1,1,1,1,1)),codeset).lower() : 3,
        unicode(time.strftime('%B',(0,4,1,1,1,1,1,1,1)),codeset).lower() : 4,
        unicode(time.strftime('%b',(0,4,1,1,1,1,1,1,1)),codeset).lower() : 4,
        unicode(time.strftime('%B',(0,5,1,1,1,1,1,1,1)),codeset).lower() : 5,
        unicode(time.strftime('%b',(0,5,1,1,1,1,1,1,1)),codeset).lower() : 5,
Ejemplo n.º 11
0
def register_stock_icons():
    """
    Add the gramps names for its icons (eg gramps-person) to the GTK icon
    factory. This allows all gramps modules to call up the icons by their name
    """
    from gui.pluginmanager import base_reg_stock_icons

    #iconpath to the base image. The front of the list has highest priority
    if constfunc.win():
        iconpaths = [
            (os.path.join(const.IMAGE_DIR, '48x48'), '.png'),
            (const.IMAGE_DIR, '.png'),
        ]
    else:
        iconpaths = [
            (os.path.join(const.IMAGE_DIR, 'scalable'), '.svg'),
            (const.IMAGE_DIR, '.svg'),
            (const.IMAGE_DIR, '.png'),
        ]

    #sizes: menu=16, small_toolbar=18, large_toolbar=24,
    #       button=20, dnd=32, dialog=48
    #add to the back of this list to overrule images set at beginning of list
    extraiconsize = [
        (os.path.join(const.IMAGE_DIR, '22x22'), gtk.ICON_SIZE_LARGE_TOOLBAR),
        (os.path.join(const.IMAGE_DIR, '16x16'), gtk.ICON_SIZE_MENU),
        (os.path.join(const.IMAGE_DIR, '22x22'), gtk.ICON_SIZE_BUTTON),
    ]

    items = [
        ('gramps-db', _('Family Trees'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-address', _('Address'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-attribute', _('Attribute'), gtk.gdk.CONTROL_MASK, 0, ''),
        #('gramps-bookmark', _('Bookmarks'), gtk.gdk.CONTROL_MASK, 0, ''),
        #('gramps-bookmark-delete', _('Delete bookmark'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-bookmark-new', _('_Add bookmark'), gtk.gdk.CONTROL_MASK, 0, ''
         ),
        ('gramps-bookmark-edit', _('Organize Bookmarks'), gtk.gdk.CONTROL_MASK,
         0, ''),
        ('gramps-config', _('Configure'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-date', _('Date'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-date-edit', _('Edit Date'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-event', _('Events'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-family', _('Family'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-fanchart', _('Fan Chart'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-font', _('Font'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-font-color', _('Font Color'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-font-bgcolor', _('Font Background Color'),
         gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-gramplet', _('Gramplets'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-geo', _('Geography'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-geo-mainmap', _('Geography'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-geo-altmap', _('Geography'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('geo-show-person', _('GeoPerson'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('geo-show-family', _('GeoFamily'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('geo-show-event', _('GeoEvents'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('geo-show-place', _('GeoPlaces'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-lock', _('Public'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-media', _('Media'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-merge', _('Merge'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-notes', _('Notes'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-parents', _('Parents'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-parents-add', _('Add Parents'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-parents-open', _('Select Parents'), gtk.gdk.CONTROL_MASK, 0,
         ''),
        ('gramps-pedigree', _('Pedigree'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-person', _('Person'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-place', _('Places'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-relation', _('Relationships'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-reports', _('Reports'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-repository', _('Repositories'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-source', _('Sources'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-spouse', _('Add Spouse'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-tag', _('Tag'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-tag-new', _('New Tag'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-tools', _('Tools'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-tree-group', _('Grouped List'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-tree-list', _('List'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-tree-select', _('Select'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-unlock', _('Private'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-view', _('View'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-viewmedia', _('View'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-zoom-in', _('Zoom In'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-zoom-out', _('Zoom Out'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-zoom-fit-width', _('Fit Width'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-zoom-best-fit', _('Fit Page'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-citation', _('Citations'), gtk.gdk.CONTROL_MASK, 0, ''),
    ]
    # the following icons are not yet in new directory structure
    # they should be ported in the near future
    items_legacy = [
        ('gramps-export', _('Export'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-import', _('Import'), gtk.gdk.CONTROL_MASK, 0, ''),
        ('gramps-undo-history', _('Undo History'), gtk.gdk.CONTROL_MASK, 0,
         ''),
        ('gramps-url', _('URL'), gtk.gdk.CONTROL_MASK, 0, ''),
    ]

    base_reg_stock_icons(iconpaths, extraiconsize, items + items_legacy)
Ejemplo n.º 12
0
def show_settings():
    """
    Shows settings of all of the major components.
    """
    py_str = '%d.%d.%d' % sys.version_info[:3]
    try:
        import gtk
        try:
            gtkver_str = '%d.%d.%d' % gtk.gtk_version
        except:  # any failure to 'get' the version
            gtkver_str = 'unknown version'
        try:
            pygtkver_str = '%d.%d.%d' % gtk.pygtk_version
        except:  # any failure to 'get' the version
            pygtkver_str = 'unknown version'
    except ImportError:
        gtkver_str = 'not found'
        pygtkver_str = 'not found'
    # no DISPLAY is a RuntimeError in an older pygtk (e.g. 2.17 in Fedora 14)
    except RuntimeError:
        gtkver_str = 'DISPLAY not set'
        pygtkver_str = 'DISPLAY not set'
    #exept TypeError: To handle back formatting on version split

    try:
        import gobject
        try:
            gobjectver_str = '%d.%d.%d' % gobject.pygobject_version
        except:  # any failure to 'get' the version
            gobjectver_str = 'unknown version'

    except ImportError:
        gobjectver_str = 'not found'

    try:
        import cairo
        try:
            cairover_str = '%d.%d.%d' % cairo.version_info
        except:  # any failure to 'get' the version
            cairover_str = 'unknown version'

    except ImportError:
        cairover_str = 'not found'

    try:
        import osmgpsmap
        try:
            osmgpsmap_str = osmgpsmap.__version__
        except:  # any failure to 'get' the version
            osmgpsmap_str = 'unknown version'

    except ImportError:
        osmgpsmap_str = 'not found'

    try:
        import pyexiv2
        try:
            pyexiv2_str = '%d.%d.%d' % pyexiv2.version_info
        except:  # any failure to 'get' the version
            pyexiv2_str = 'unknown version'

    except ImportError:
        pyexiv2_str = 'not found'

    try:
        import PIL.Image
        try:
            pil_str = PIL.Image.VERSION
        except:  # any failure to 'get' the version
            pil_str = 'unknown version'

    except ImportError:
        pil_str = 'not found'

    import config
    usebsddb3 = config.get('preferences.use-bsddb3')
    try:
        if usebsddb3:
            import bsddb3 as bsddb
        else:
            import bsddb
        bsddb_str = bsddb.__version__
        bsddb_db_str = str(bsddb.db.version())
    except:
        bsddb_str = 'not found'
        bsddb_db_str = 'not found'

    try:
        import const
        gramps_str = const.VERSION
    except:
        gramps_str = 'not found'

    if hasattr(os, "uname"):
        kernel = os.uname()[2]
    else:
        kernel = None

    lang_str = os.environ.get('LANG', 'not set')
    language_str = os.environ.get('LANGUAGE', 'not set')
    grampsi18n_str = os.environ.get('GRAMPSI18N', 'not set')
    grampshome_str = os.environ.get('GRAMPSHOME', 'not set')
    grampsdir_str = os.environ.get('GRAMPSDIR', 'not set')

    try:
        dotversion_str = Popen(['dot', '-V'],
                               stderr=PIPE).communicate(input=None)[1]
        if dotversion_str:
            dotversion_str = dotversion_str.replace('\n', '')
    except:
        dotversion_str = 'Graphviz not in system PATH'

    try:
        if constfunc.win():
            gsversion_str = Popen(['gswin32c', '--version'],
                                  stdout=PIPE).communicate(input=None)[0]
        else:
            gsversion_str = Popen(['gs', '--version'],
                                  stdout=PIPE).communicate(input=None)[0]
        if gsversion_str:
            gsversion_str = gsversion_str.replace('\n', '')
    except:
        gsversion_str = 'Ghostscript not in system PATH'

    os_path = os.environ.get('PATH', 'not set')
    os_path = os_path.split(os.pathsep)

    print "Gramps Settings:"
    print "----------------"
    print ' python    : %s' % py_str
    print ' gramps    : %s' % gramps_str
    print ' gtk++     : %s' % gtkver_str
    print ' pygtk     : %s' % pygtkver_str
    print ' gobject   : %s' % gobjectver_str
    if usebsddb3:
        print ' Using bsddb3'
    else:
        print ' Not using bsddb3'
    print ' bsddb     : %s' % bsddb_str
    print ' bsddb.db  : %s' % bsddb_db_str
    print ' cairo     : %s' % cairover_str
    print ' osmgpsmap : %s' % osmgpsmap_str
    print ' pyexiv2   : %s' % pyexiv2_str
    print ' PIL       : %s' % pil_str
    print ' o.s.      : %s' % operating_system
    if kernel:
        print ' kernel    : %s' % kernel
    print
    print "Environment settings:"
    print "---------------------"
    print ' LANG      : %s' % lang_str
    print ' LANGUAGE  : %s' % language_str
    print ' GRAMPSI18N: %s' % grampsi18n_str
    print ' GRAMPSHOME: %s' % grampshome_str
    print ' GRAMPSDIR : %s' % grampsdir_str
    print ' PYTHONPATH:'
    for folder in sys.path:
        print "   ", folder
    print
    print "Non-python dependencies:"
    print "------------------------"
    print ' Graphviz  : %s' % dotversion_str
    print ' Ghostscr. : %s' % gsversion_str
    print
    print "System PATH env variable:"
    print "-------------------------"
    for folder in os_path:
        print "    ", folder
    print
Ejemplo n.º 13
0
#
# Ideally, this needs to be done before any Gramps modules are imported, so that
# any code that is executed as the modules are imported can log errors or
# warnings. Errors and warnings are particularly applicable to TransUtils and
# setting up internationalisation in this module. const and constfunc have to be
# imported before this code is executed because they are used in this code.
#-------------------------------------------------------------------------
"""Setup basic logging support."""

# Setup a formatter
form = logging.Formatter(fmt="%(asctime)s.%(msecs).03d: %(levelname)s: "
                         "%(filename)s: line %(lineno)d: %(message)s",
                         datefmt='%Y-%m-%d %H:%M:%S')

# Create the log handlers
if constfunc.win():
    # If running in GUI mode redirect stdout and stderr to log file
    if hasattr(sys.stdout, "fileno") and sys.stdout.fileno() < 0:
        logfile = os.path.join(const.HOME_DIR, "Gramps%s%s.log") % (
            const.VERSION_TUPLE[0], const.VERSION_TUPLE[1])
        # We now carry out the first step in build_user_paths(), to make sure
        # that the user home directory is available to store the log file. When
        # build_user_paths() is called, the call is protected by a try...except
        # block, and any failure will be logged. However, if the creation of the
        # user directory fails here, there is no way to report the failure,
        # because stdout/stderr are not available, and neither is the logfile.
        if os.path.islink(const.HOME_DIR):
            pass  # ok
        elif not os.path.isdir(const.HOME_DIR):
            os.makedirs(const.HOME_DIR)
        sys.stdout = sys.stderr = open(logfile, "w")
Ejemplo n.º 14
0
class PackageWriter(object):
    def __init__(self, database, filename, msg_callback, callback=None):
        self.db = database
        self.callback = callback
        self.msg_callback = msg_callback
        self.filename = filename

    def export(self):
        #        missmedia_action = 0
        #--------------------------------------------------------------
        def remove_clicked():
            # File is lost => remove all references and the object itself
            for p_id in self.db.iter_family_handles():
                p = self.db.get_family_from_handle(p_id)
                nl = p.get_media_list()
                for o in nl:
                    if o.get_reference_handle() == m_id:
                        nl.remove(o)
                p.set_media_list(nl)
                self.db.commit_family(p, None)
            for key in self.db.iter_person_handles():
                p = self.db.get_person_from_handle(key)
                nl = p.get_media_list()
                for o in nl:
                    if o.get_reference_handle() == m_id:
                        nl.remove(o)
                p.set_media_list(nl)
                self.db.commit_person(p, None)
            for key in self.db.get_source_handles():
                p = self.db.get_source_from_handle(key)
                nl = p.get_media_list()
                for o in nl:
                    if o.get_reference_handle() == m_id:
                        nl.remove(o)
                p.set_media_list(nl)
                self.db.commit_source(p, None)
            for key in self.db.get_place_handles():
                p = self.db.get_place_from_handle(key)
                nl = p.get_media_list()
                for o in nl:
                    if o.get_reference_handle() == m_id:
                        nl.remove(o)
                p.set_media_list(nl)
                self.db.commit_place(p, None)
            for key in self.db.get_event_handles():
                p = self.db.get_event_from_handle(key)
                nl = p.get_media_list()
                for o in nl:
                    if o.get_reference_handle() == m_id:
                        nl.remove(o)
                p.set_media_list(nl)
                self.db.commit_event(p, None)
            self.db.remove_object(m_id, None)

        def leave_clicked():
            # File is lost => do nothing, leave as is
            pass

        def select_clicked():
            # File is lost => select a file to replace the lost one
            def fs_close_window(obj):
                pass

            def fs_ok_clicked(obj):
                name = Utils.get_unicode_path_from_file_chooser(
                    fs_top.get_filename())
                if os.path.isfile(name):
                    archive.add(name)

            fs_top = gtk.FileChooserDialog(
                "%s - GRAMPS" % _("Select file"),
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK,
                         gtk.RESPONSE_OK))
            response = fs_top.run()
            if response == gtk.RESPONSE_OK:
                fs_ok_clicked(fs_top)
            elif response == gtk.RESPONSE_CANCEL:
                fs_close_window(fs_top)

            fs_top.destroy()

        #---------------------------------------------------------------

        try:
            archive = tarfile.open(self.filename, 'w:gz')
        except EnvironmentError, msg:
            log.warn(str(msg))
            self.msg_callback(
                _('Failure writing %s') % self.filename, str(msg))
            return 0

        # Write media files first, since the database may be modified
        # during the process (i.e. when removing object)
        for m_id in self.db.get_media_object_handles(sort_handles=True):
            mobject = self.db.get_object_from_handle(m_id)
            filename = Utils.media_path_full(self.db, mobject.get_path())
            archname = str(mobject.get_path())
            if os.path.isfile(filename) and os.access(filename, os.R_OK):
                archive.add(filename, archname)
#             else:
#                 # File is lost => ask what to do
#                 if missmedia_action == 0:
#                     mmd = MissingMediaDialog(
#                         _("Media object could not be found"),
#                         _("%(file_name)s is referenced in the database, "
#                           "but no longer exists. The file may have been "
#                           "deleted or moved to a different location. "
#                           "You may choose to either remove the reference "
#                           "from the database, keep the reference to the "
#                           "missing file, or select a new file."
#                           ) % { 'file_name' : filename },
#                         remove_clicked, leave_clicked, select_clicked)
#                     missmedia_action = mmd.default_action
#                 elif missmedia_action == 1:
#                     remove_clicked()
#                 elif missmedia_action == 2:
#                     leave_clicked()
#                 elif missmedia_action == 3:
#                     select_clicked()

# Write XML now
        g = StringIO()
        gfile = XmlWriter(self.db, self.msg_callback, self.callback, 2)
        gfile.write_handle(g)
        tarinfo = tarfile.TarInfo('data.gramps')
        tarinfo.size = len(g.getvalue())
        tarinfo.mtime = time.time()
        if not constfunc.win():
            tarinfo.uid = os.getuid()
            tarinfo.gid = os.getgid()
        g.seek(0)
        archive.addfile(tarinfo, g)
        archive.close()
        g.close()

        return True
Ejemplo n.º 15
0
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data,
        and decide if this is a move or a reorder.
        """
        if sel_data and sel_data.data:
            try:
                (mytype, selfid, obj, row_from) = pickle.loads(sel_data.data)

                # make sure this is the correct DND type for this object
                if mytype == self._DND_TYPE.drag_type:

                    # determine the destination row
                    data = self.iconlist.get_dest_item_at_pos(x, y)
                    if data:
                        (path, pos) = data
                        row = path[0]

                        if pos == gtk.ICON_VIEW_DROP_LEFT:
                            row = max(row, 0)
                        elif pos == gtk.ICON_VIEW_DROP_RIGHT:
                            row = min(row, len(self.get_data()))
                        elif pos == gtk.ICON_VIEW_DROP_INTO:
                            row = min(row + 1, len(self.get_data()))
                    else:
                        row = len(self.get_data())

                    # if the is same object, we have a move, otherwise,
                    # it is a standard drag-n-drop

                    if id(self) == selfid:
                        self._move(row_from, row, obj)
                    else:
                        self._handle_drag(row, obj)
                    self.rebuild()
                elif mytype == DdTargets.MEDIAOBJ.drag_type:
                    oref = gen.lib.MediaRef()
                    oref.set_reference_handle(obj)
                    self.get_data().append(oref)
                    self.changed = True
                    self.rebuild()
                elif self._DND_EXTRA and mytype == self._DND_EXTRA.drag_type:
                    self.handle_extra_type(mytype, obj)
            except pickle.UnpicklingError:
                #modern file managers provide URI_LIST. For Windows split sel_data.data
                if constfunc.win():
                    files = sel_data.data.split('\n')
                else:
                    files = sel_data.get_uris()
                for file in files:
                    d = Utils.fix_encoding(file.replace('\0', ' ').strip())
                    protocol, site, mfile, j, k, l = urlparse.urlparse(d)
                    if protocol == "file":
                        name = Utils.fix_encoding(mfile)
                        name = unicode(
                            urllib.url2pathname(
                                name.encode(sys.getfilesystemencoding())))
                        mime = gen.mime.get_type(name)
                        if not gen.mime.is_valid_type(mime):
                            return
                        photo = gen.lib.MediaObject()
                        base_dir = unicode(Utils.media_path(self.dbstate.db))
                        if os.path.exists(base_dir):
                            name = Utils.relative_path(name, base_dir)
                        photo.set_path(name)
                        photo.set_mime_type(mime)
                        basename = os.path.basename(name)
                        (root, ext) = os.path.splitext(basename)
                        photo.set_description(root)
                        with DbTxn(_("Drag Media Object"),
                                   self.dbstate.db) as trans:
                            self.dbstate.db.add_object(photo, trans)
                            oref = gen.lib.MediaRef()
                            oref.set_reference_handle(photo.get_handle())
                            self.get_data().append(oref)
                            self.changed = True
                    self.rebuild()