Example #1
0
def export_file(db, filename, user):
    """
    Export the db to a file (such as a GEDCOM file).

    >>> export_file(DbDjango(), "/home/user/Untitled_1.ged", User())
    """
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False, user=user) # do not load db_loader
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    (name, ext) = os.path.splitext(os.path.basename(filename))
    format = ext[1:].lower()
    export_list = pmgr.get_reg_exporters()
    for pdata in export_list:
        if format == pdata.extension:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                for item in pmgr.get_fail_list():
                    name, error_tuple, pdata = item
                    etype, exception, traceback = error_tuple
                    print("ERROR:", name, exception)
                return False
            export_function = getattr(mod, pdata.export_function)
            export_function(db, filename, user)
            return True
    return False
Example #2
0
def import_file(db, filename, user):
    """
    Import a file (such as a GEDCOM file) into the given db.

    >>> import_file(DbDjango(), "/home/user/Untitled_1.ged", User())
    """
    from .grampsdb.models import Person
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False,
                            user=user)  # do not load db_loader
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    (name, ext) = os.path.splitext(os.path.basename(filename))
    format = ext[1:].lower()
    import_list = pmgr.get_reg_importers()
    for pdata in import_list:
        if format == pdata.extension:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                for item in pmgr.get_fail_list():
                    name, error_tuple, pdata = item
                    # (filename, (exception-type, exception, traceback), pdata)
                    etype, exception, traceback = error_tuple
                    print("ERROR:", name, exception)
                return False
            import_function = getattr(mod, pdata.import_function)
            db.prepare_import()
            retval = import_function(db, filename, user)
            db.commit_import()
            return retval
    return False
Example #3
0
    def __handle_import_option(self, value, family_tree_format):
        """
        Handle the "-i" or "--import" option.
        Only Files supported by a plugin can be imported, so not Family Trees.
        """
        # Need to convert path/filename to unicode before opening
        # For non latin characters in Windows path/file/user names
        fname = conv_to_unicode(value, sys.stdin.encoding)
        fullpath = os.path.abspath(os.path.expanduser(fname))
        if fname != '-' and not os.path.exists(fullpath):
            self.__error(_('Error: Import file %s not found.') % fname)
            sys.exit(0)

        if family_tree_format is None:
            # Guess the file format based on the file extension.
            # This will get the lower case extension without a period,
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        for plugin in pmgr.get_import_plugins():
            if family_tree_format == plugin.get_extension():
                plugin_found = True

        if plugin_found:
            self.imports.append((fname, family_tree_format))
        else:
            self.__error(
                _('Error: Unrecognized type: "%(format)s" for '
                  'import file: %(filename)s') % {
                      'format': family_tree_format,
                      'filename': fname
                  })
            sys.exit(0)
Example #4
0
    def __handle_import_option(self, value, family_tree_format):
        """
        Handle the "-i" or "--import" option.
        Only Files supported by a plugin can be imported, so not Family Trees.
        """
        fname = value
        fullpath = os.path.abspath(os.path.expanduser(fname))
        if fname != '-' and not os.path.exists(fullpath):
            self.__error(_('Error: Import file %s not found.') % fname)
            sys.exit(1)

        if family_tree_format is None:
            # Guess the file format based on the file extension.
            # This will get the lower case extension without a period,
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        for plugin in pmgr.get_import_plugins():
            if family_tree_format == plugin.get_extension():
                plugin_found = True

        if plugin_found:
            self.imports.append((fname, family_tree_format))
        else:
            self.__error(_('Error: Unrecognized type: "%(format)s" for '
                           'import file: %(filename)s'
                          ) % {'format'   : family_tree_format,
                               'filename' : fname})
            sys.exit(1)
Example #5
0
def export_file(db, filename, user):
    """
    Export the db to a file (such as a GEDCOM file).

    >>> export_file(DbDjango(), "/home/user/Untitled_1.ged", User())
    """
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False,
                            user=user)  # do not load db_loader
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    (name, ext) = os.path.splitext(os.path.basename(filename))
    format = ext[1:].lower()
    export_list = pmgr.get_reg_exporters()
    for pdata in export_list:
        if format == pdata.extension:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                for item in pmgr.get_fail_list():
                    name, error_tuple, pdata = item
                    etype, exception, traceback = error_tuple
                    print("ERROR:", name, exception)
                return False
            export_function = getattr(mod, pdata.export_function)
            export_function(db, filename, user)
            return True
    return False
Example #6
0
    def __init__(self,
                 database,
                 name,
                 category,
                 option_class,
                 options_str_dict,
                 noopt=False):

        pmgr = BasePluginManager.get_instance()
        self.__textdoc_plugins = []
        self.__drawdoc_plugins = []
        self.__bookdoc_plugins = []
        for plugin in pmgr.get_docgen_plugins():
            if plugin.get_text_support() and plugin.get_extension():
                self.__textdoc_plugins.append(plugin)
            if plugin.get_draw_support() and plugin.get_extension():
                self.__drawdoc_plugins.append(plugin)
            if (plugin.get_extension() and plugin.get_text_support()
                    and plugin.get_draw_support()):
                self.__bookdoc_plugins.append(plugin)

        self.database = database
        self.category = category

        self.options_dict = None  # keep pylint happy
        self.options_help = None
        self.paper = None
        self.orien = None
        self.marginl = None
        self.marginr = None
        self.margint = None
        self.marginb = None
        self.doc_options = None
        self.doc_option_class = None
        self.selected_style = None
        self.style_list = None
        self.css_filename = None
        self.format = None
        self.raw_name = name

        self.option_class = option_class(name, database)
        if category == CATEGORY_GRAPHVIZ:
            # Need to include Graphviz options
            self.__gvoptions = graphdoc.GVOptions()
            menu = self.option_class.menu
            self.__gvoptions.add_menu_options(menu)
            for name in menu.get_all_option_names():
                if name not in self.option_class.options_dict:
                    self.option_class.options_dict[
                        name] = menu.get_option_by_name(name).get_value()
        self.option_class.load_previous_values()
        _validate_options(self.option_class, database)
        self.show = options_str_dict.pop('show', None)

        self.options_str_dict = options_str_dict
        self.init_standard_options(noopt)
        self.init_report_options()
        self.parse_options()
        self.init_report_options_help()
        self.show_options()
Example #7
0
def get_report_profile(
    db_handle: DbReadBase, plugin_manager: BasePluginManager, report_data
):
    """Extract and return report attributes and options."""
    module = plugin_manager.load_plugin(report_data)
    option_class = getattr(module, report_data.optionclass)
    report = CommandLineReport(
        db_handle, report_data.name, report_data.category, option_class, {}
    )
    icondir = report_data.icondir or ""
    options_help = report.options_help
    if REPORT_FILTERS:
        for report_type in REPORT_FILTERS:
            for item in options_help["off"][2]:
                if item[: len(report_type)] == report_type:
                    del options_help["off"][2][options_help["off"][2].index(item)]
                    break
    return {
        "authors": report_data.authors,
        "authors_email": report_data.authors_email,
        "category": report_data.category,
        "description": report_data.description,
        "id": report_data.id,
        "name": report_data.name,
        "options_dict": report.options_dict,
        "options_help": options_help,
        "report_modes": report_data.report_modes,
        "version": report_data.version,
    }
Example #8
0
def import_file(db, filename, user):
    """
    Import a file (such as a GEDCOM file) into the given db.

    >>> import_file(DbDjango(), "/home/user/Untitled_1.ged", User())
    """
    from .grampsdb.models import Person
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False, user=user) # do not load db_loader
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    (name, ext) = os.path.splitext(os.path.basename(filename))
    format = ext[1:].lower()
    import_list = pmgr.get_reg_importers()
    for pdata in import_list:
        if format == pdata.extension:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                for item in pmgr.get_fail_list():
                    name, error_tuple, pdata = item
                    # (filename, (exception-type, exception, traceback), pdata)
                    etype, exception, traceback = error_tuple
                    print("ERROR:", name, exception)
                return False
            import_function = getattr(mod, pdata.import_function)
            #db.prepare_import()
            retval = import_function(db, filename, user)
            #db.commit_import()
            return retval
    return False
Example #9
0
    def __init__(self):
        """ This function should only be run once by get_instance() """
        if GuiPluginManager.__instance is not 1:
            raise Exception("This class is a singleton. " "Use the get_instance() method")

        Callback.__init__(self)
        self.basemgr = BasePluginManager.get_instance()
        self.__hidden_plugins = set(config.get("plugin.hiddenplugins"))
        self.__hidden_changed()
Example #10
0
 def __init__(self, dbstate, setloader, user):
     self.dbstate = dbstate
     if setloader:
         self.db_loader = CLIDbLoader(self.dbstate)
     else:
         self.db_loader = None
     self.file_loaded = False
     self._pmgr = BasePluginManager.get_instance()
     self.user = user
Example #11
0
    def __init__(self):
        """ This function should only be run once by get_instance() """
        if GuiPluginManager.__instance != 1:
            raise Exception("This class is a singleton. "
                            "Use the get_instance() method")

        Callback.__init__(self)
        self.basemgr = BasePluginManager.get_instance()
        self.__hidden_plugins = set(config.get('plugin.hiddenplugins'))
Example #12
0
 def __init__(self, dbstate, setloader, user):
     self.dbstate = dbstate
     if setloader:
         self.db_loader = CLIDbLoader(self.dbstate)
     else:
         self.db_loader = None
     self.file_loaded = False
     self._pmgr = BasePluginManager.get_instance()
     self.user = user
Example #13
0
    def __init__(self, database, name, category, option_class, options_str_dict,
                 noopt=False):

        pmgr = BasePluginManager.get_instance()
        self.__textdoc_plugins = []
        self.__drawdoc_plugins = []
        self.__bookdoc_plugins = []
        for plugin in pmgr.get_docgen_plugins():
            if plugin.get_text_support() and plugin.get_extension():
                self.__textdoc_plugins.append(plugin)
            if plugin.get_draw_support() and plugin.get_extension():
                self.__drawdoc_plugins.append(plugin)
            if (plugin.get_extension()
                    and plugin.get_text_support()
                    and plugin.get_draw_support()):
                self.__bookdoc_plugins.append(plugin)

        self.database = database
        self.category = category

        self.options_dict = None # keep pylint happy
        self.options_help = None
        self.paper = None
        self.orien = None
        self.marginl = None
        self.marginr = None
        self.margint = None
        self.marginb = None
        self.doc_options = None
        self.doc_option_class = None
        self.selected_style = None
        self.style_list = None
        self.css_filename = None
        self.format = None
        self.raw_name = name

        self.option_class = option_class(name, database)
        if category == CATEGORY_GRAPHVIZ:
            # Need to include Graphviz options
            self.__gvoptions = graphdoc.GVOptions()
            menu = self.option_class.menu
            self.__gvoptions.add_menu_options(menu)
            for name in menu.get_all_option_names():
                if name not in self.option_class.options_dict:
                    self.option_class.options_dict[
                        name] = menu.get_option_by_name(name).get_value()
        self.option_class.load_previous_values()
        _validate_options(self.option_class, database)
        self.show = options_str_dict.pop('show', None)

        self.options_str_dict = options_str_dict
        self.init_standard_options(noopt)
        self.init_report_options()
        self.parse_options()
        self.init_report_options_help()
        self.show_options()
Example #14
0
 def cl_export(self, filename, family_tree_format):
     """
     Command-line export routine.
     Try to write into filename using the family_tree_format.
     """
     pmgr = BasePluginManager.get_instance()
     for plugin in pmgr.get_export_plugins():
         if family_tree_format == plugin.get_extension():
             export_function = plugin.get_export_function()
             export_function(self.dbstate.db, filename, self.user)
Example #15
0
 def cl_export(self, filename, family_tree_format):
     """
     Command-line export routine. 
     Try to write into filename using the family_tree_format.
     """
     pmgr = BasePluginManager.get_instance()
     for plugin in pmgr.get_export_plugins():
         if family_tree_format == plugin.get_extension():
             export_function = plugin.get_export_function()
             export_function(self.dbstate.db, filename, self.user)
Example #16
0
def get_reports(db_handle: DbReadBase, report_id: str = None):
    """Extract and return report attributes and options."""
    reload_custom_filters()
    plugin_manager = BasePluginManager.get_instance()
    reports = []
    for report_data in plugin_manager.get_reg_reports(gui=False):
        if report_id is not None and report_data.id != report_id:
            continue
        if report_data.category not in REPORT_DEFAULTS:
            continue
        report = get_report_profile(db_handle, plugin_manager, report_data)
        reports.append(report)
    return reports
Example #17
0
def run_report(
    db_handle: DbReadBase,
    report_id: str,
    report_options: Dict,
    allow_file: bool = False,
):
    """Generate the report."""
    if "off" in report_options and report_options["off"] in REPORT_FILTERS:
        abort(422)
    _resources = ResourcePath()
    os.environ["GRAMPS_RESOURCES"] = str(Path(_resources.data_dir).parent)
    reload_custom_filters()
    plugin_manager = BasePluginManager.get_instance()
    for report_data in plugin_manager.get_reg_reports(gui=False):
        if report_data.id == report_id:
            if report_data.category not in REPORT_DEFAULTS:
                abort(404)
            if "off" not in report_options:
                report_options["off"] = REPORT_DEFAULTS[report_data.category]
            file_type = "." + report_options["off"]
            file_type = _EXTENSION_MAP.get(file_type) or file_type
            if file_type not in MIME_TYPES:
                current_app.logger.error(
                    "Can not find {} in MIME_TYPES".format(file_type)
                )
                abort(500)
            if current_app.config.get("REPORT_DIR"):
                report_path = current_app.config.get("REPORT_DIR")
            else:
                report_path = tempfile.gettempdir()
            file_name = os.path.join(
                report_path, "{}{}".format(uuid.uuid4(), file_type)
            )
            report_options["of"] = file_name
            report_profile = get_report_profile(db_handle, plugin_manager, report_data)
            validate_options(report_profile, report_options, allow_file=allow_file)
            module = plugin_manager.load_plugin(report_data)
            option_class = getattr(module, report_data.optionclass)
            report_class = getattr(module, report_data.reportclass)

            cl_report(
                db_handle,
                report_data.name,
                report_data.category,
                report_class,
                option_class,
                report_options,
            )
            return file_name, file_type
    abort(404)
Example #18
0
def get_exporters(extension: str = None):
    """Extract and return list of exporters."""
    exporters = []
    plugin_manager = BasePluginManager.get_instance()
    for plugin in plugin_manager.get_export_plugins():
        if extension is not None and extension != plugin.get_extension():
            continue
        exporter = {
            "description": plugin.get_description(),
            "extension": plugin.get_extension(),
            "module": plugin.get_module_name(),
        }
        exporters.append(exporter)
    return exporters
Example #19
0
def run_import(db_handle: DbReadBase, file_obj: IO[bytes],
               extension: str) -> None:
    """Generate the import."""
    tmp_dir = tempfile.gettempdir()
    file_name = os.path.join(tmp_dir, f"{uuid.uuid4()}.{extension}")
    plugin_manager = BasePluginManager.get_instance()
    for plugin in plugin_manager.get_import_plugins():
        if extension == plugin.get_extension():
            import_function = plugin.get_import_function()
            with open(file_name, "wb") as f:
                f.write(file_obj.read())
            result = import_function(db_handle, file_name, User())
            os.remove(file_name)
            if not result:
                abort(500)
            return
Example #20
0
    def __handle_export_option(self, value, family_tree_format):
        """
        Handle the "-e" or "--export" option.

        .. note:: this can only happen in the CLI version.
        """
        if self.gui:
            return
        fname = value
        if fname == '-':
            fullpath = '-'
        else:
            fullpath = os.path.abspath(os.path.expanduser(fname))
            if os.path.exists(fullpath):
                message = _(
                    "WARNING: Output file already exists!\n"
                    "WARNING: It will be overwritten:\n   %s") % fullpath
                accepted = self.user.prompt(_('OK to overwrite?'),
                                            message,
                                            _('yes'),
                                            _('no'),
                                            default_label=_('yes'))
                if accepted:
                    self.__error(
                        _("Will overwrite the existing file: %s") % fullpath)
                else:
                    sys.exit(1)

        if family_tree_format is None:
            # Guess the file format based on the file extension.
            # This will get the lower case extension without a period,
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        for plugin in pmgr.get_export_plugins():
            if family_tree_format == plugin.get_extension():
                plugin_found = True

        if plugin_found:
            self.exports.append((fullpath, family_tree_format))
        else:
            self.__error(
                _("ERROR: Unrecognized format for export file %s") % fname)
            sys.exit(1)
Example #21
0
def get_thumbnailers():
    if len(THUMBNAILERS):
        return THUMBNAILERS

    plugman = BasePluginManager.get_instance()
    for pdata in plugman.get_reg_thumbnailers():
        module = plugman.load_plugin(pdata)
        if not module:
            print("Error loading thumbnailer '%s': skipping content" %
                  pdata.name)
            continue
        thumbnailer = getattr(module, pdata.thumbnailer)()
        if pdata.order == START:
            THUMBNAILERS.insert(0, thumbnailer)
        else:
            THUMBNAILERS.append(thumbnailer)
    return THUMBNAILERS
Example #22
0
def get_importers(extension: str = None):
    """Extract and return list of importers."""
    importers = []
    plugin_manager = BasePluginManager.get_instance()
    for plugin in plugin_manager.get_import_plugins():
        if extension is not None and extension != plugin.get_extension():
            continue
        if extension in DISABLED_IMPORTERS:
            continue
        importer = {
            "name": plugin.get_name(),
            "description": plugin.get_description(),
            "extension": plugin.get_extension(),
            "module": plugin.get_module_name(),
        }
        importers.append(importer)
    return importers
Example #23
0
def get_plugin_options(db, pid):
    """
    Get the default options and help for this plugin.
    """
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False, user=GUser()) # do not load db_loader
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    pdata = pmgr.get_plugin(pid)
    if hasattr(pdata, "optionclass") and pdata.optionclass:
        mod = pmgr.load_plugin(pdata)
        optionclass = eval("mod." + pdata.optionclass)
        optioninstance = optionclass("Name", db)
        optioninstance.load_previous_values()
        return optioninstance.options_dict, optioninstance.options_help
    else:
        return {}, {}
Example #24
0
def run_report(db, name, **options_str_dict):
    """
    Given a database, run a given report.

    db is a Db database

    name is the name of a report

    options_str_dict is the same kind of options
    given at the command line. For example:

    >>> run_report(db, "ancestor_report", off="txt",
                   of="ancestor-007.txt", pid="I37")

    returns CommandLineReport (clr) if successfully runs the report,
    None otherwise.

    You can see:
       options and values used in  clr.option_class.options_dict
       filename in clr.option_class.get_output()
    """
    dbstate = DbState()
    climanager = CLIManager(dbstate, False, User()) # don't load db
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    cl_list = pmgr.get_reg_reports()
    clr = None
    for pdata in cl_list:
        if name == pdata.id:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                #import of plugin failed
                return clr
            category = pdata.category
            report_class = getattr(mod, pdata.reportclass)
            options_class = getattr(mod, pdata.optionclass)
            if category in (CATEGORY_BOOK, CATEGORY_CODE):
                options_class(db, name, category,
                              options_str_dict)
            else:
                clr = cl_report(db, name, category,
                                report_class, options_class,
                                options_str_dict)
                return clr
    return clr
Example #25
0
    def __handle_export_option(self, value, family_tree_format):
        """
        Handle the "-e" or "--export" option.

        .. note:: this can only happen in the CLI version.
        """
        if self.gui:
            return
        # Need to convert path/filename to unicode before opening
        # For non latin characters in Windows path/file/user names
        fname = conv_to_unicode(value, sys.stdin.encoding)
        if fname == '-':
            fullpath = '-'
        else:
            fullpath = os.path.abspath(os.path.expanduser(fname))
            if os.path.exists(fullpath):
                message = _("WARNING: Output file already exists!\n"
                            "WARNING: It will be overwritten:\n   %s"
                            ) % fullpath
                accepted = self.user.prompt(_('OK to overwrite?'), message,
                        _('yes'), _('no'))
                if accepted:
                    self.__error(_("Will overwrite the existing file: %s")
                                   % fullpath)
                else:
                    sys.exit(0)

        if family_tree_format is None:
            # Guess the file format based on the file extension.
            # This will get the lower case extension without a period,
            # or an empty string.
            family_tree_format = os.path.splitext(fname)[-1][1:].lower()

        pmgr = BasePluginManager.get_instance()
        plugin_found = False
        for plugin in pmgr.get_export_plugins():
            if family_tree_format == plugin.get_extension():
                plugin_found = True

        if plugin_found:
            self.exports.append((fullpath, family_tree_format))
        else:
            self.__error(_("ERROR: Unrecognized format for export file %s")
                            % fname)
            sys.exit(0)
Example #26
0
def run_report(db, name, **options_str_dict):
    """
    Given a database, run a given report.

    db is a Db database

    name is the name of a report

    options_str_dict is the same kind of options
    given at the command line. For example:
    
    >>> run_report(db, "ancestor_report", off="txt",
                   of="ancestor-007.txt", pid="I37")

    returns CommandLineReport (clr) if successfully runs the report,
    None otherwise.

    You can see:
       options and values used in  clr.option_class.options_dict
       filename in clr.option_class.get_output()
    """
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False, user=User()) # don't load db
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    cl_list = pmgr.get_reg_reports()
    clr = None
    for pdata in cl_list:
        if name == pdata.id:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                #import of plugin failed
                return clr
            category = pdata.category
            report_class = getattr(mod, pdata.reportclass)
            options_class = getattr(mod, pdata.optionclass)
            if category in (CATEGORY_BOOK, CATEGORY_CODE):
                options_class(db, name, category, 
                              options_str_dict)
            else:
                clr = cl_report(db, name, category, 
                                report_class, options_class,
                                options_str_dict)
                return clr
    return clr
Example #27
0
def get_plugin_options(db, pid):
    """
    Get the default options and help for this plugin.
    """
    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=False,
                            user=GUser())  # do not load db_loader
    climanager.do_reg_plugins(dbstate, None)
    pmgr = BasePluginManager.get_instance()
    pdata = pmgr.get_plugin(pid)
    if hasattr(pdata, "optionclass") and pdata.optionclass:
        mod = pmgr.load_plugin(pdata)
        optionclass = eval("mod." + pdata.optionclass)
        optioninstance = optionclass("Name", db)
        optioninstance.load_previous_values()
        return optioninstance.options_dict, optioninstance.options_help
    else:
        return {}, {}
Example #28
0
def run_export(db_handle: DbReadBase, extension: str, options):
    """Generate the export."""
    export_path = TEMP_DIR
    if current_app.config.get("EXPORT_PATH"):
        export_path = current_app.config.get("EXPORT_PATH")
    file_name = os.path.join(export_path,
                             "{}.{}".format(uuid.uuid4(), extension))
    _resources = ResourcePath()
    os.environ["GRAMPS_RESOURCES"] = str(Path(_resources.data_dir).parent)
    filters.reload_custom_filters()
    plugin_manager = BasePluginManager.get_instance()
    for plugin in plugin_manager.get_export_plugins():
        if extension == plugin.get_extension():
            export_function = plugin.get_export_function()
            result = export_function(db_handle, file_name, User(), options)
            if not result:
                abort(500)
            return file_name, "." + extension
Example #29
0
def GetReportClasses(name):
    """Get Report and Options class for this module"""
    report_class = None
    options_class = None

    pmgr = BasePluginManager.get_instance()
    _cl_list = pmgr.get_reg_reports(gui=False)
    for pdata in _cl_list:
        if name == pdata.id:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                return report_class, options_class
            report_class_str = pdata.reportclass + "Report"
            report_class = eval('mod.' + report_class_str)
            options_class_str = name + "Options"
            options_class = eval('mod.' + options_class_str)

            return report_class, options_class

    return report_class, options_class
Example #30
0
def GetReportClasses(name):
    """Get Report and Options class for this module"""
    report_class = None
    options_class = None

    pmgr = BasePluginManager.get_instance()
    _cl_list = pmgr.get_reg_reports(gui=False)
    for pdata in _cl_list:
        if name == pdata.id:
            mod = pmgr.load_plugin(pdata)
            if not mod:
                return report_class, options_class
            report_class_str = pdata.reportclass + "Report"
            report_class = eval('mod.' + report_class_str)
            options_class_str = name + "Options"
            options_class = eval('mod.' + options_class_str)

            return report_class, options_class

    return report_class, options_class
Example #31
0
      displayFeatureInfo(evt.pixel);
    });
  };
"""

# variables for alphabet_navigation()
_KEYPERSON, _KEYPLACE, _KEYEVENT, _ALPHAEVENT = 0, 1, 2, 3

COLLATE_LANG = glocale.collation

_NAME_STYLE_SHORT = 2
_NAME_STYLE_DEFAULT = 1
_NAME_STYLE_FIRST = 0
_NAME_STYLE_SPECIAL = None

PLUGMAN = BasePluginManager.get_instance()
CSS = PLUGMAN.process_plugin_data('WEBSTUFF')

#_NAME_COL = 3

_WRONGMEDIAPATH = []

_HTML_DBL_QUOTES = re.compile(r'([^"]*) " ([^"]*) " (.*)', re.VERBOSE)
_HTML_SNG_QUOTES = re.compile(r"([^']*) ' ([^']*) ' (.*)", re.VERBOSE)

# Events that are usually a family event
_EVENTMAP = set([EventType.MARRIAGE, EventType.MARR_ALT,
                 EventType.MARR_SETTL, EventType.MARR_LIC,
                 EventType.MARR_CONTR, EventType.MARR_BANNS,
                 EventType.ENGAGEMENT, EventType.DIVORCE,
                 EventType.DIV_FILING])
Example #32
0
    def parse_args(self):
        """
        Fill in lists with open, exports, imports, and actions options.

        Any errors are added to self.errors
        """
        try:
            options, leftargs = getopt.getopt(self.args[1:],
                                              SHORTOPTS, LONGOPTS)
        except getopt.GetoptError as msg:
            # Extract the arguments in the list.
            # The % operator replaces the list elements
            # with repr() of the list elements
            # which is OK for latin characters,
            # but not for non latin characters in list elements
            cliargs = "[ "
            for arg in range(len(self.args) - 1):
                cliargs += self.args[arg + 1] + " "
            cliargs += "]"
            # Must first do str() of the msg object.
            msg = str(msg)
            self.errors += [(_('Error parsing the arguments'),
                             msg + '\n' +
                             _("Error parsing the arguments: %s \n"
                               "Type gramps --help for an overview of "
                               "commands, or read the manual pages."
                              ) % cliargs)]
            return

        # Some args can work on a list of databases:
        if leftargs:
            for opt_ix in range(len(options)):
                option, value = options[opt_ix]
                if option in ['-L', '-l', '-t']:
                    self.database_names = leftargs
                    leftargs = []

        if leftargs:
            # if there were an argument without option,
            # use it as a file to open and return
            self.open_gui = leftargs[0]
            print(_("Trying to open: %s ..."
                   ) % leftargs[0],
                  file=sys.stderr)
            #see if force open is on
            for opt_ix in range(len(options)):
                option, value = options[opt_ix]
                if option in ('-u', '--force-unlock'):
                    self.force_unlock = True
                    break
            return

        # Go over all given option and place them into appropriate lists
        cleandbg = []
        need_to_quit = False
        for opt_ix in range(len(options)):
            option, value = options[opt_ix]
            if option in ['-O', '--open']:
                self.open = value
            elif option in ['-C', '--create']:
                self.create = value
            elif option in ['-i', '--import']:
                family_tree_format = None
                if (opt_ix < len(options) - 1
                        and options[opt_ix + 1][0] in ('-f', '--format')):
                    family_tree_format = options[opt_ix + 1][1]
                self.imports.append((value, family_tree_format))
            elif option in ['-r', '--remove']:
                self.removes.append(value)
            elif option in ['-e', '--export']:
                family_tree_format = None
                if (opt_ix < len(options) - 1
                        and options[opt_ix + 1][0] in ('-f', '--format')):
                    family_tree_format = options[opt_ix + 1][1]
                self.exports.append((value, family_tree_format))
            elif option in ['-a', '--action']:
                action = value
                if action not in ('report', 'tool', 'book'):
                    print(_("Unknown action: %s. Ignoring."
                           ) % action,
                          file=sys.stderr)
                    continue
                options_str = ""
                if (opt_ix < len(options)-1
                        and options[opt_ix+1][0] in ('-p', '--options')):
                    options_str = options[opt_ix+1][1]
                self.actions.append((action, options_str))
            elif option in ['-d', '--debug']:
                print(_('setup debugging'), value, file=sys.stderr)
                logger = logging.getLogger(value)
                logger.setLevel(logging.DEBUG)
                cleandbg += [opt_ix]
            elif option in ['-l']:
                self.list = True
            elif option in ['-L']:
                self.list_more = True
            elif option in ['-t']:
                self.list_table = True
            elif option in ['-s', '--show']:
                print(_("Gramps config settings from %s:"
                       ) % config.filename)
                for sect in config.data:
                    for setting in config.data[sect]:
                        print("%s.%s=%s" % (sect, setting,
                                            repr(config.data[sect][setting])))
                    print()
                sys.exit(0)
            elif option in ['-b', '--databases']:
                default = config.data["database"]["backend"]
                pmgr = BasePluginManager.get_instance()
                pmgr.reg_plugins(PLUGINS_DIR, self, None)
                pmgr.reg_plugins(USER_PLUGINS, self, None, load_on_reg=True)
                for plugin in pmgr.get_reg_databases():
                    pdata = pmgr.get_plugin(plugin.id)
                    mod = pmgr.load_plugin(pdata)
                    if mod:
                        database = getattr(mod, pdata.databaseclass)
                        summary = database.get_class_summary()
                        print("Database backend ID:",
                              pdata.id,
                              "(default)" if pdata.id == default else "")
                        for key in sorted(summary.keys()):
                            print("   ", _("%s:") % key, summary[key])
                sys.exit(0)
            elif option in ['-c', '--config']:
                cfg_name = value
                set_value = False
                if cfg_name:
                    if ":" in cfg_name:
                        cfg_name, new_value = cfg_name.split(":", 1)
                        set_value = True
                    if config.has_default(cfg_name):
                        setting_value = config.get(cfg_name)
                        print(_("Current Gramps config setting: "
                                "%(name)s:%(value)s"
                               ) % {'name'  : cfg_name,
                                    'value' : repr(setting_value)},
                              file=sys.stderr)
                        if set_value:
                            # does a user want the default config value?
                            if new_value in ("DEFAULT", _("DEFAULT")):
                                new_value = config.get_default(cfg_name)
                            else:
                                converter = get_type_converter(setting_value)
                                new_value = converter(new_value)
                            config.set(cfg_name, new_value)
                            # translators: indent "New" to match "Current"
                            print(_("    New Gramps config setting: "
                                    "%(name)s:%(value)s"
                                   ) % {'name'  : cfg_name,
                                        'value' : repr(config.get(cfg_name))},
                                  file=sys.stderr)
                        else:
                            need_to_quit = True
                    else:
                        print(_("Gramps: no such config setting: '%s'"
                               ) % cfg_name,
                              file=sys.stderr)
                        need_to_quit = True
                cleandbg += [opt_ix]
            elif option in ['-h', '-?', '--help']:
                self.help = True
            elif option in ['-u', '--force-unlock']:
                self.force_unlock = True
            elif option in ['--usage']:
                self.usage = True
            elif option in ['-y', '--yes']:
                self.auto_accept = True
            elif option in ['-q', '--quiet']:
                self.quiet = True

        #clean options list
        cleandbg.reverse()
        for ind in cleandbg:
            del options[ind]

        if (len(options) > 0
                and self.open is None
                and self.imports == []
                and self.removes == []
                and not (self.list
                         or self.list_more
                         or self.list_table
                         or self.help)):
            # Extract and convert to unicode the arguments in the list.
            # The % operator replaces the list elements with repr() of
            # the list elements, which is OK for latin characters
            # but not for non-latin characters in list elements
            cliargs = "[ "
            for arg in range(len(self.args) - 1):
                cliargs += self.args[arg + 1] + ' '
            cliargs += "]"
            self.errors += [(_('Error parsing the arguments'),
                             _("Error parsing the arguments: %s \n"
                               "To use in the command-line mode, supply at "
                               "least one input file to process."
                              ) % cliargs)]
        if need_to_quit:
            sys.exit(0)
Example #33
0
    def import_new_db(self, filename, user):
        """
        Attempt to import the provided file into a new database.
        A new database will only be created if an appropriate importer was 
        found.

        :param filename: a fully-qualified path, filename, and
                         extension to open.

        :param user: a :class:`.cli.user.User` or :class:`.gui.user.User`
                     instance for managing user interaction.
        
        :returns: A tuple of (new_path, name) for the new database
                  or (None, None) if no import was performed.
        """
        pmgr = BasePluginManager.get_instance()
        # check to see if it isn't a filename directly:
        if not os.path.isfile(filename):
            # Allow URL names here; make temp file if necessary
            url = urlparse(filename)
            if url.scheme != "":
                if url.scheme == "file":
                    filename = url2pathname(filename[7:])
                else:
                    url_fp = urlopen(filename) # open URL
                    # make a temp local file:
                    ext = os.path.splitext(url.path)[1]
                    fd, filename = tempfile.mkstemp(suffix=ext)
                    temp_fp = os.fdopen(fd, "w")
                    # read from URL:
                    data = url_fp.read()
                    # write locally:
                    temp_fp.write(data)
                    url_fp.close()
                    from  gen.db.dbconst import BDBVERSFN
                    versionpath = os.path.join(name, BDBVERSFN)
                    _LOG.debug("Write bsddb version %s" % str(dbase.version()))
                    with open(versionpath, "w") as version_file:
                        version_file.write(str(dbase.version()))
                    temp_fp.close()

        (name, ext) = os.path.splitext(os.path.basename(filename))
        format = ext[1:].lower()

        for plugin in pmgr.get_import_plugins():
            if format == plugin.get_extension():

                new_path, name = self._create_new_db(name)
    
                # Create a new database
                self.__start_cursor(_("Importing data..."))

                dbase = self.dbstate.make_database("bsddb")
                dbase.load(new_path, user.callback)
    
                import_function = plugin.get_import_function()
                import_function(dbase, filename, user)
    
                # finish up
                self.__end_cursor()
                dbase.close()
                
                return new_path, name
        return None, None
def build_report_set():

    reports = []

    ##################################################################
    # Load plugins
    ##################################################################

    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader=True, user=None)
    climanager.do_reg_plugins(dbstate, uistate=None)
    gpr = PluginRegister.get_instance()

    PLUGMAN = BasePluginManager.get_instance()
    CSS = PLUGMAN.process_plugin_data('WEBSTUFF')

    ##################################################################
    # GRAMPS native plugins
    ##################################################################

    # GRPH_FMT = ['odt', 'ps', 'pdf', 'svg']
    GRPH_FMT = ['pdf', 'svg']
    # GRPH_FMT = ['svg']
    GRPH_REP = [
        {
            'report': 'ancestor_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0006',
            },
        },
        {
            'report': 'descend_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0104',
            },
        },
        {
            'report': 'family_descend_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0104',
            },
        },
        {
            'report': 'fan_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0006',
            },
        },
        {
            'report': 'statistics_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
            },
        },
        {
            'report': 'timeline',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
            },
        },
        {
            'report': 'calendar',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
            },
        },
        {
            'report': 'familylines_graph',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'gidlist': 'I0104 I0045',
                'limitchildren': True,
                'maxchildren': 20,
            },
        },
        {
            'report': 'hourglass_graph',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0044',
                'maxascend': 2,
                'maxdescend': 2,
            },
        },
        {
            'report': 'rel_graph',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0044',
                'filter': 3,
                'event_choice': 2,
            },
        },
    ]

    # TEXT_FMT = ['ps', 'pdf', 'html', 'odt', 'tex', 'rtf', 'txt']
    TEXT_FMT = ['html', 'pdf', 'txt']
    # TEXT_FMT = ['html', 'txt']
    TEXT_REP = [
        {
            'report': 'ancestor_report',
            'options': {
                'maxgen': 6,
                'pid': 'I0006',
            },
        },
        {
            'report': 'descend_report',
            'options': {
                'pid': 'I0104',
            },
        },
        {
            'report': 'det_ancestor_report',
            'options': {
                'pid': 'I0006',
            },
        },
        {
            'report': 'det_descendant_report',
            'options': {
                'pid': 'I0104',
            },
        },
        {
            'report': 'family_group',
            'options': {
                'family_id': 'F0017',
            },
        },
        {
            'report': 'birthday_report',
            'options': {},
        },
        {
            'report': 'endofline_report',
            'options': {
                'pid': 'I0006',
            },
        },
        {
            'report': 'indiv_complete',
            'options': {},
        },
        {
            'report': 'kinship_report',
            'options': {
                'pid': 'I0044',
            },
        },
        {
            'report': 'tag_report',
            'options': {
                'tag': 'ToDo',
            },
        },
        {
            'report': 'number_of_ancestors',
            'options': {
                'pid': 'I0006',
            },
        },
        {
            'report': 'place_report',
            'options': {
                'places': 'P1678 P1679 P1680',
            },
        },
        {
            'report': 'summary',
            'options': {},
        },
        {
            'report': 'records',
            'options': {},
        },
        {
            'report': 'notelinkreport',
            'options': {},
        },
    ]

    # Single run with all native reports (except web) in all formats
    for (rep_list, formats) in [
        (TEXT_REP, TEXT_FMT),
        (GRPH_REP, GRPH_FMT),
    ]:
        for rep_info in TEXT_REP:
            report = rep_info['report']
            options = rep_info['options']
            plugin = gpr.get_plugin(report)
            if not plugin:
                print('Unknown plugin: %s' % report)
                continue
            for fmt in TEXT_FMT:
                of = os.path.join(GRAMPS_REP_DIR, report + '.' + fmt)
                new_options = {
                    'name': report,
                    'off': fmt,
                    'of': of,
                    # 'show': 'all',
                }
                new_options.update(options)
                reports.append({
                    'title':
                    '"%s" in format "%s"' % (plugin.name, fmt),
                    'name':
                    plugin.name,
                    'result':
                    of,
                    'type':
                    'Native',
                    'category':
                    plugin.category,
                    'version':
                    plugin.version,
                    'options':
                    new_options,
                })

    ##################################################################
    # GRAMPS native web reports
    ##################################################################

    full_options = {
        'linkhome': True,
        'showdeath': True,
        'showpartner': True,
        'showparents': True,
        'showhalfsiblings': True,
        'inc_families': True,
        'inc_repository': True,
        'inc_gendex': True,
        'inc_addressbook': True,
        'placemappages': True,
        'familymappages': True,
    }

    for (i, (css, full)) in enumerate([
        ['default', False],
        ['Mainz', True],
    ]):
        report = 'navwebpage'
        plugin = gpr.get_plugin(report)
        opts = {
            'name': report,
            'target': os.path.join(GRAMPS_REP_DIR, 'example_NAVWEB%i' % i),
            'css': CSS[css]['id'],
            'living': _INCLUDE_LIVING_VALUE,
        }
        if (full): opts.update(full_options)
        reports.append({
            'title':
            '"%s" report example %i' % (plugin.name, i),
            'name':
            report,
            'result':
            os.path.join(GRAMPS_REP_DIR, 'example_NAVWEB%i' % i, 'index.html'),
            'type':
            'Native',
            'category':
            plugin.category,
            'version':
            VERSION,
            'options':
            opts,
        })

    full_options = {
        'alive': False,
        'fullyear': True,
        'makeoneday': True,
        'link_to_narweb': True,
    }

    for (i, (css, full)) in enumerate([
        ['default', False],
        ['Mainz', True],
    ]):
        report = 'WebCal'
        plugin = gpr.get_plugin(report)
        opts = {
            'name': report,
            'target': os.path.join(GRAMPS_REP_DIR, 'example_WebCal%i' % i),
            'css': CSS[css]['id'],
            'home_link': '../../example_NAVWEB%i/index.html' % i,
            'prefix': '../../example_NAVWEB%i/' % i,
        }
        page = 'January.html'
        if (full):
            opts.update(full_options)
            page = 'fullyearlinked.html'
        reports.append({
            'title':
            '"%s" report example %i' % (plugin.name, i),
            'name':
            report,
            'result':
            os.path.join(GRAMPS_REP_DIR, 'example_WebCal%i' % i,
                         str(Today().get_year()), page),
            'type':
            'Native',
            'category':
            plugin.category,
            'version':
            VERSION,
            'options':
            opts,
        })

    ##################################################################
    # GRAMPS addons reports
    ##################################################################

    addons = []

    ########## AncestorFill

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'AncestorFill.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'AncestorFill',
            'options': {
                'off': fmt,
                'of': of,
            },
        })

    ########## d3-ancestralcollapsibletree

    addons.append({
        'title':
        '"%s" report example',
        'result':
        os.path.join(ADDONS_REP_DIR, 'd3-ancestralcollapsibletree',
                     'index.html'),
        'i':
        'd3-ancestralcollapsibletree',
        'options': {
            'dest_path':
            os.path.join(ADDONS_REP_DIR, 'd3-ancestralcollapsibletree'),
            'dest_file':
            'index.html',
            'pid':
            'I0006',
            'maxgen':
            6,
        },
    })

    ########## d3-ancestralfanchart

    addons.append({
        'title':
        '"%s" report example',
        'result':
        os.path.join(ADDONS_REP_DIR, 'd3-ancestralfanchart', 'index.html'),
        'i':
        'd3-ancestralfanchart',
        'options': {
            'dest_path': os.path.join(ADDONS_REP_DIR, 'd3-ancestralfanchart'),
            'dest_file': 'index.html',
            'pid': 'I0006',
            'maxgen': 6,
        },
    })

    ########## d3-descendantindentedtree

    addons.append({
        'title':
        '"%s" report example',
        'result':
        os.path.join(ADDONS_REP_DIR, 'd3-descendantindentedtree',
                     'index.html'),
        'i':
        'd3-descendantindentedtree',
        'options': {
            'dest_path': os.path.join(ADDONS_REP_DIR,
                                      'd3-descendantindentedtree'),
            'dest_file': 'index.html',
            'pid': 'I0104',
            'max_gen': 6,
            'inc_private': True,
            'inc_living': _INCLUDE_LIVING_VALUE,
        },
    })

    ########## denominoviso

    for (i, (mode, type, dir, pid, full)) in enumerate([
        [0, 0, 0, 'I0001', True],
        [0, 3, 2, 'I0001', False],
        [0, 4, 2, 'I0001', False],
        [1, 0, 0, 'I0044', True],
        [1, 1, 0, 'I0044', False],
    ]):
        addons.append({
            'title':
            '"%%s" report example %i' % i,
            'result':
            os.path.join(ADDONS_REP_DIR, 'DenominoViso%i.xhtml' % i),
            'i':
            'denominoviso',
            'options': {
                'DNMfilename':
                os.path.join(ADDONS_REP_DIR, 'DenominoViso%i.xhtml' % i),
                'DNMchart_mode':
                mode,
                'DNMpid':
                pid,
                'DNMchart_type':
                type,
                'DNMinc_attributes_m':
                '"True, "',
                'DNMinc_addresses':
                full,
                'DNMinc_notes':
                full,
                'DNMinc_url':
                full,
                'DNMinc_url_desc':
                full,
                'DNMinc_sources':
                full,
                'DNMinc_img':
                full,
                'DNMcopy_img_m':
                '"%s, %s%i"' %
                (str(full), os.path.join(ADDONS_REP_DIR, 'DenominoViso'), i),
            },
        })

    ########## DescendantBook

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'DescendantBook.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'DescendantBook',
            'options': {
                'off': fmt,
                'of': of,
            },
        })

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'DetailedDescendantBook.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'DetailedDescendantBook',
            'options': {
                'off': fmt,
                'of': of,
            },
        })

    ########## Descendants Lines

    for fmt in GRPH_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'DescendantsLines.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'Descendants Lines',
            'options': {
                'off': fmt,
                'of': of,
                'pid': 'I0006',
            },
        })

    ########## database-differences-report

    for fmt in ['html']:
        of = os.path.join(ADDONS_REP_DIR, 'database-differences-report.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'database-differences-report',
            'options': {
                'off':
                fmt,
                'of':
                of,
                'filename':
                os.path.join(os.environ['GRAMPS_RESOURCES'], 'example',
                             'gramps', 'example.gramps'),
            },
        })

    ########## DynamicWeb

    addons.extend(report_set_DynamicWeb.addon_set())

    ########## FamilyTree

    for fmt in GRPH_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'FamilyTree.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'FamilyTree',
            'options': {
                'off': fmt,
                'of': of,
                'pid': 'I0006',
                'max_ancestor_generations': 3,
                'max_descendant_generations': 3,
                'papero': 1,
                'protect_private': False,
                'color': 1,
            },
        })

    ########## LastChangeReport

    for fmt in ['html']:
        of = os.path.join(ADDONS_REP_DIR, 'LastChangeReport.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'LastChangeReport',
            'options': {
                'off': fmt,
                'of': of,
                'what_types': '"True,True,True,True,True,True"'
            },
        })

    ########## LinesOfDescendency

    for fmt in ['html']:
        of = os.path.join(ADDONS_REP_DIR, 'LinesOfDescendency.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'LinesOfDescendency',
            'options': {
                'off': fmt,
                'of': of,
                'pid': 'I0006',
                'ancestor': 'I0104',
            },
        })

    ########## ListeEclair

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'ListeEclair.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'ListeEclair',
            'options': {
                'off': fmt,
                'of': of,
            },
        })

    ########## PedigreeChart

    for fmt in GRPH_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'PedigreeChart.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'PedigreeChart',
            'options': {
                'off': fmt,
                'of': of,
                'maxgen': 6,
                'pid': 'I0006',
            },
        })

    ########## PersonEverythingReport

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'PersonEverythingReport.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'PersonEverythingReport',
            'options': {
                'off': fmt,
                'of': of,
            },
        })

    ########## Repositories Report

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'RepositoriesReportOptions.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'Repositories Report Options',
            'options': {
                'off': fmt,
                'of': of,
            },
        })

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'RepositoriesReport.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'Repositories Report',
            'options': {
                'off': fmt,
                'of': of,
            },
        })

    ########## TodoReport

    reports = []
    addons = []
    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'TodoReport.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'TodoReport',
            'options': {
                'off': fmt,
                'of': of,
                'tag': 'ToDo',
            },
        })

    ########## Check if addon exists in the addons listings

    for addon in addons:
        plugin = gpr.get_plugin(addon['i'])
        if not plugin:
            print('Unknown plugin: %s' % addon['i'])
            continue
        addon['options'].update({
            'name': addon['i'],
        })
        addon.update({
            'title': addon['title'] % plugin.name,
            'name': plugin.name,
            'type': 'Addon',
            'category': plugin.category,
            'version': plugin.version,
        })
        del addon['i']
        reports.append(addon)

    return reports
Example #35
0
    def cl_action(self, action, options_str):
        """
        Command-line action routine. Try to perform specified action.
        """
        pmgr = BasePluginManager.get_instance()
        if action == "report":
            try:
                options_str_dict = _split_options(options_str)
            except:
                options_str_dict = {}
                print(_("Ignoring invalid options string."), file=sys.stderr)

            name = options_str_dict.pop('name', None)
            _cl_list = pmgr.get_reg_reports(gui=False)
            if name:
                for pdata in _cl_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return
                        category = pdata.category
                        report_class = eval('mod.' + pdata.reportclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        if category in (CATEGORY_BOOK, CATEGORY_CODE):
                            options_class(self.dbstate.db, name, category,
                                          options_str_dict)
                        else:
                            cl_report(self.dbstate.db, name, category,
                                      report_class, options_class,
                                      options_str_dict)
                        return
                # name exists, but is not in the list of valid report names
                msg = _("Unknown report name.")
            else:
                msg = _("Report name not given. "
                        "Please use one of %(donottranslate)s=reportname") % \
                        {'donottranslate' : '[-p|--options] name'}

            print(_("%s\n Available names are:") % msg, file=sys.stderr)
            for pdata in sorted(_cl_list, key=lambda pdata: pdata.id.lower()):
                # Print cli report name ([item[0]), GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print("   %s%s- %s" % (pdata.id, " " *
                                           (26 - len(pdata.id)), pdata.name),
                          file=sys.stderr)
                else:
                    print("   %s\t- %s" % (pdata.id, pdata.name),
                          file=sys.stderr)

        elif action == "tool":
            from gramps.gui.plug import tool
            try:
                options_str_dict = dict([
                    tuple(chunk.split('=')) for chunk in options_str.split(',')
                ])
            except:
                options_str_dict = {}
                print(_("Ignoring invalid options string."), file=sys.stderr)

            name = options_str_dict.pop('name', None)
            _cli_tool_list = pmgr.get_reg_tools(gui=False)
            if name:
                for pdata in _cli_tool_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return
                        category = pdata.category
                        tool_class = eval('mod.' + pdata.toolclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        tool.cli_tool(dbstate=self.dbstate,
                                      name=name,
                                      category=category,
                                      tool_class=tool_class,
                                      options_class=options_class,
                                      options_str_dict=options_str_dict,
                                      user=self.user)
                        return
                msg = _("Unknown tool name.")
            else:
                msg = _("Tool name not given. "
                        "Please use one of %(donottranslate)s=toolname.") % \
                        {'donottranslate' : '[-p|--options] name'}

            print(_("%s\n Available names are:") % msg, file=sys.stderr)
            for pdata in sorted(_cli_tool_list,
                                key=lambda pdata: pdata.id.lower()):
                # Print cli report name ([item[0]), GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print("   %s%s- %s" % (pdata.id, " " *
                                           (26 - len(pdata.id)), pdata.name),
                          file=sys.stderr)
                else:
                    print("   %s\t- %s" % (pdata.id, pdata.name),
                          file=sys.stderr)

        elif action == "book":
            try:
                options_str_dict = _split_options(options_str)
            except:
                options_str_dict = {}
                print(_("Ignoring invalid options string."), file=sys.stderr)

            name = options_str_dict.pop('name', None)
            book_list = BookList('books.xml', self.dbstate.db)
            if name:
                if name in book_list.get_book_names():
                    cl_book(self.dbstate.db, name, book_list.get_book(name),
                            options_str_dict)
                    return
                msg = _("Unknown book name.")
            else:
                msg = _("Book name not given. "
                        "Please use one of %(donottranslate)s=bookname.") % \
                        {'donottranslate' : '[-p|--options] name'}

            print(_("%s\n Available names are:") % msg, file=sys.stderr)
            for name in sorted(book_list.get_book_names()):
                print("   %s" % name, file=sys.stderr)

        else:
            print(_("Unknown action: %s.") % action, file=sys.stderr)
            sys.exit(0)
Example #36
0
def available_updates():
    whattypes = config.get('behavior.check-for-addon-update-types')
    do_not_show_prev = config.get(
        'behavior.do-not-show-previously-seen-addon-updates')
    prev_seen = config.get('behavior.previously-seen-addon-updates')

    LOG.debug("Checking for updated addons...")
    langs = glocale.get_language_list()
    langs.append("en")
    # now we have a list of languages to try:
    f_ptr = None
    for lang in langs:
        url = ("%s/listings/addons-%s.txt" %
               (config.get("behavior.addons-url"), lang))
        LOG.debug("   trying: %s", url)
        try:
            f_ptr = urlopen_maybe_no_check_cert(url)
        except:
            try:
                url = ("%s/listings/addons-%s.txt" %
                       (config.get("behavior.addons-url"), lang[:2]))
                f_ptr = urlopen_maybe_no_check_cert(url)
            except Exception as err:  # some error
                LOG.warning("Failed to open addon metadata for %s %s: %s",
                            lang, url, err)
                f_ptr = None
        if f_ptr and f_ptr.getcode() == 200:  # ok
            break

    try:
        wfp = open(os.path.join(VERSION_DIR, "new_addons.txt"), mode='wt',
                   encoding='utf-8')
    except Exception as err:
        LOG.warning("Failed to open addon status file: %s", err)

    pmgr = BasePluginManager.get_instance()
    addon_update_list = []
    if f_ptr and f_ptr.getcode() == 200:
        lines = list(f_ptr.readlines())
        count = 0
        for line in lines:
            line = line.decode('utf-8')
            try:
                plugin_dict = safe_eval(line)
                if type(plugin_dict) != type({}):
                    raise TypeError("Line with addon metadata is not "
                                    "a dictionary")
            except:
                LOG.warning("Skipped a line in the addon listing: " +
                            str(line))
                continue
            if wfp:
                wfp.write(str(plugin_dict) + '\n')
            pid = plugin_dict["i"]
            plugin = pmgr.get_plugin(pid)
            if plugin:
                LOG.debug("Comparing %s > %s",
                          version_str_to_tup(plugin_dict["v"], 3),
                          version_str_to_tup(plugin.version, 3))
                if (version_str_to_tup(plugin_dict["v"], 3) >
                        version_str_to_tup(plugin.version, 3)):
                    LOG.debug("   Downloading '%s'...", plugin_dict["z"])
                    if "update" in whattypes:
                        if (not do_not_show_prev or
                                plugin_dict["i"] not in prev_seen):
                            addon_update_list.append(
                                (_("Updated"), "%s/download/%s" %
                                 (config.get("behavior.addons-url"),
                                  plugin_dict["z"]), plugin_dict))
                else:
                    LOG.debug("   '%s' is ok", plugin_dict["n"])
            else:
                LOG.debug("   '%s' is not installed", plugin_dict["n"])
                if "new" in whattypes:
                    if (not do_not_show_prev or
                            plugin_dict["i"] not in prev_seen):
                        addon_update_list.append(
                            (_("updates|New"), "%s/download/%s" %
                             (config.get("behavior.addons-url"),
                              plugin_dict["z"]), plugin_dict))
        config.set("behavior.last-check-for-addon-updates",
                   datetime.date.today().strftime("%Y/%m/%d"))
        count += 1
        if f_ptr:
            f_ptr.close()
        if wfp:
            wfp.close()
    else:
        LOG.debug("Checking Addons Failed")
    LOG.debug("Done checking!")

    return addon_update_list
Example #37
0
 def __init__(self, dbstate: DbState, user):
     """Initialize self."""
     self.dbstate = dbstate
     self._pmgr = BasePluginManager.get_instance()
     self.user = user
Example #38
0
 def get_backend_name_from_dbid(self, dbid):
     pmgr = BasePluginManager.get_instance()
     for plugin in pmgr.get_reg_databases():
         if plugin.id == dbid:
             return plugin._name
     return _("Unknown")
Example #39
0
    def import_new_db(self, filename, user):
        """
        Attempt to import the provided file into a new database.
        A new database will only be created if an appropriate importer was
        found.

        :param filename: a fully-qualified path, filename, and
                         extension to open.

        :param user: a :class:`.cli.user.User` or :class:`.gui.user.User`
                     instance for managing user interaction.

        :returns: A tuple of (new_path, name) for the new database
                  or (None, None) if no import was performed.
        """
        pmgr = BasePluginManager.get_instance()
        # check to see if it isn't a filename directly:
        if not os.path.isfile(filename):
            # Allow URL names here; make temp file if necessary
            url = urlparse(filename)
            if url.scheme != "":
                if url.scheme == "file":
                    filename = url2pathname(filename[7:])
                else:
                    url_fp = urlopen(filename)  # open URL
                    # make a temp local file:
                    ext = os.path.splitext(url.path)[1]
                    fd, filename = tempfile.mkstemp(suffix=ext)
                    temp_fp = os.fdopen(fd, "w")
                    # read from URL:
                    data = url_fp.read()
                    # write locally:
                    temp_fp.write(data)
                    url_fp.close()
                    temp_fp.close()

        (name, ext) = os.path.splitext(os.path.basename(filename))
        format = ext[1:].lower()

        for plugin in pmgr.get_import_plugins():
            if format == plugin.get_extension():

                dbid = config.get('database.backend')
                new_path, name = self._create_new_db(name,
                                                     dbid=dbid,
                                                     edit_entry=False)

                # Create a new database
                self.__start_cursor(_("Importing data..."))

                dbase = make_database(dbid)
                dbase.load(new_path, user.callback)

                import_function = plugin.get_import_function()
                import_function(dbase, filename, user)

                # finish up
                self.__end_cursor()
                dbase.close()

                return new_path, name
        return None, None
Example #40
0
def available_updates():
    whattypes = config.get('behavior.check-for-addon-update-types')
    do_not_show_prev = config.get(
        'behavior.do-not-show-previously-seen-addon-updates')
    prev_seen = config.get('behavior.previously-seen-addon-updates')

    LOG.debug("Checking for updated addons...")
    langs = glocale.get_language_list()
    langs.append("en")
    # now we have a list of languages to try:
    f_ptr = None
    for lang in langs:
        url = ("%s/listings/addons-%s.txt" %
               (config.get("behavior.addons-url"), lang))
        LOG.debug("   trying: %s", url)
        try:
            f_ptr = urlopen_maybe_no_check_cert(url)
        except:
            try:
                url = ("%s/listings/addons-%s.txt" %
                       (config.get("behavior.addons-url"), lang[:2]))
                f_ptr = urlopen_maybe_no_check_cert(url)
            except Exception as err:  # some error
                LOG.warning("Failed to open addon metadata for %s %s: %s",
                            lang, url, err)
                f_ptr = None
        if f_ptr and f_ptr.getcode() == 200 or f_ptr.file:  # ok
            break

    try:
        wfp = open(os.path.join(VERSION_DIR, "new_addons.txt"), mode='wt',
                   encoding='utf-8')
    except Exception as err:
        LOG.warning("Failed to open addon status file: %s", err)

    pmgr = BasePluginManager.get_instance()
    addon_update_list = []
    if f_ptr and f_ptr.getcode() == 200 or f_ptr.file:
        lines = list(f_ptr.readlines())
        count = 0
        for line in lines:
            line = line.decode('utf-8')
            try:
                plugin_dict = safe_eval(line)
                if type(plugin_dict) != type({}):
                    raise TypeError("Line with addon metadata is not "
                                    "a dictionary")
            except:
                LOG.warning("Skipped a line in the addon listing: " +
                            str(line))
                continue
            if wfp:
                wfp.write(str(plugin_dict) + '\n')
            pid = plugin_dict["i"]
            plugin = pmgr.get_plugin(pid)
            if plugin:
                LOG.debug("Comparing %s > %s",
                          version_str_to_tup(plugin_dict["v"], 3),
                          version_str_to_tup(plugin.version, 3))
                if (version_str_to_tup(plugin_dict["v"], 3) >
                        version_str_to_tup(plugin.version, 3)):
                    LOG.debug("   Downloading '%s'...", plugin_dict["z"])
                    if "update" in whattypes:
                        if (not do_not_show_prev or
                                plugin_dict["i"] not in prev_seen):
                            addon_update_list.append(
                                (_("Updated"), "%s/download/%s" %
                                 (config.get("behavior.addons-url"),
                                  plugin_dict["z"]), plugin_dict))
                else:
                    LOG.debug("   '%s' is ok", plugin_dict["n"])
            else:
                LOG.debug("   '%s' is not installed", plugin_dict["n"])
                if "new" in whattypes:
                    if (not do_not_show_prev or
                            plugin_dict["i"] not in prev_seen):
                        addon_update_list.append(
                            (_("updates|New"), "%s/download/%s" %
                             (config.get("behavior.addons-url"),
                              plugin_dict["z"]), plugin_dict))
        config.set("behavior.last-check-for-addon-updates",
                   datetime.date.today().strftime("%Y/%m/%d"))
        count += 1
        if f_ptr:
            f_ptr.close()
        if wfp:
            wfp.close()
    else:
        LOG.debug("Checking Addons Failed")
    LOG.debug("Done checking!")

    return addon_update_list
Example #41
0
 def get_backend_name_from_dbid(self, dbid):
     pmgr = BasePluginManager.get_instance()
     for plugin in pmgr.get_reg_databases():
         if plugin.id == dbid:
             return plugin._name
     return UNAVAILABLE
Example #42
0
      displayFeatureInfo(evt.pixel);
    });
  };
"""

# variables for alphabet_navigation()
_KEYPERSON, _KEYPLACE, _KEYEVENT, _ALPHAEVENT = 0, 1, 2, 3

COLLATE_LANG = glocale.collation

_NAME_STYLE_SHORT = 2
_NAME_STYLE_DEFAULT = 1
_NAME_STYLE_FIRST = 0
_NAME_STYLE_SPECIAL = None

PLUGMAN = BasePluginManager.get_instance()
CSS = PLUGMAN.process_plugin_data('WEBSTUFF')

#_NAME_COL = 3

_WRONGMEDIAPATH = []

_HTML_DBL_QUOTES = re.compile(r'([^"]*) " ([^"]*) " (.*)', re.VERBOSE)
_HTML_SNG_QUOTES = re.compile(r"([^']*) ' ([^']*) ' (.*)", re.VERBOSE)

# Events that are usually a family event
_EVENTMAP = set([
    EventType.MARRIAGE, EventType.MARR_ALT, EventType.MARR_SETTL,
    EventType.MARR_LIC, EventType.MARR_CONTR, EventType.MARR_BANNS,
    EventType.ENGAGEMENT, EventType.DIVORCE, EventType.DIV_FILING
])
Example #43
0
    def parse_args(self):
        """
        Fill in lists with open, exports, imports, and actions options.

        Any errors are added to self.errors
        """
        try:
            options, leftargs = getopt.getopt(self.args[1:], SHORTOPTS,
                                              LONGOPTS)
        except getopt.GetoptError as msg:
            # Extract the arguments in the list.
            # The % operator replaces the list elements with repr() of the list elemements
            # which is OK for latin characters, but not for non latin characters in list elements
            cliargs = "[ "
            for arg in range(len(self.args) - 1):
                cliargs += self.args[arg + 1] + " "
            cliargs += "]"
            # Must first do str() of the msg object.
            msg = str(msg)
            self.errors += [
                (_('Error parsing the arguments'), msg + '\n' +
                 _("Error parsing the arguments: %s \n"
                   "Type gramps --help for an overview of commands, or "
                   "read the manual pages.") % cliargs)
            ]
            return

        # Some args can work on a list of databases:
        if leftargs:
            for opt_ix in range(len(options)):
                option, value = options[opt_ix]
                if option in ['-L', '-l', '-t']:
                    self.database_names = leftargs
                    leftargs = []

        if leftargs:
            # if there were an argument without option,
            # use it as a file to open and return
            self.open_gui = leftargs[0]
            print(_("Trying to open: %s ...") % leftargs[0], file=sys.stderr)
            #see if force open is on
            for opt_ix in range(len(options)):
                option, value = options[opt_ix]
                if option in ('-u', '--force-unlock'):
                    self.force_unlock = True
                    break
            return

        # Go over all given option and place them into appropriate lists
        cleandbg = []
        need_to_quit = False
        for opt_ix in range(len(options)):
            option, value = options[opt_ix]
            if option in ['-O', '--open']:
                self.open = value
            elif option in ['-C', '--create']:
                self.create = value
            elif option in ['-i', '--import']:
                family_tree_format = None
                if opt_ix < len(options) - 1 \
                   and options[opt_ix + 1][0] in ( '-f', '--format'):
                    family_tree_format = options[opt_ix + 1][1]
                self.imports.append((value, family_tree_format))
            elif option in ['-r', '--remove']:
                self.removes.append(value)
            elif option in ['-e', '--export']:
                family_tree_format = None
                if opt_ix < len(options) - 1 \
                   and options[opt_ix + 1][0] in ( '-f', '--format'):
                    family_tree_format = options[opt_ix + 1][1]
                self.exports.append((value, family_tree_format))
            elif option in ['-a', '--action']:
                action = value
                if action not in ('report', 'tool', 'book'):
                    print(_("Unknown action: %s. Ignoring.") % action,
                          file=sys.stderr)
                    continue
                options_str = ""
                if opt_ix < len(options)-1 \
                            and options[opt_ix+1][0] in ( '-p', '--options' ):
                    options_str = options[opt_ix + 1][1]
                self.actions.append((action, options_str))
            elif option in ['-d', '--debug']:
                print(_('setup debugging'), value, file=sys.stderr)
                logger = logging.getLogger(value)
                logger.setLevel(logging.DEBUG)
                cleandbg += [opt_ix]
            elif option in ['-l']:
                self.list = True
            elif option in ['-L']:
                self.list_more = True
            elif option in ['-t']:
                self.list_table = True
            elif option in ['-s', '--show']:
                print(_("Gramps config settings from %s:") % config.filename)
                for section in config.data:
                    for setting in config.data[section]:
                        print("%s.%s=%s" %
                              (section, setting,
                               repr(config.data[section][setting])))
                    print()
                sys.exit(0)
            elif option in ['-b', '--databases']:
                default = config.data["behavior"]["database-backend"]
                pmgr = BasePluginManager.get_instance()
                pmgr.reg_plugins(PLUGINS_DIR, self, None)
                pmgr.reg_plugins(USER_PLUGINS, self, None, load_on_reg=True)
                for plugin in pmgr.get_reg_databases():
                    pdata = pmgr.get_plugin(plugin.id)
                    mod = pmgr.load_plugin(pdata)
                    if mod:
                        database = getattr(mod, pdata.databaseclass)
                        summary = database.get_class_summary()
                        print("Database backend ID:", pdata.id,
                              "(default)" if pdata.id == default else "")
                        for key in sorted(summary.keys()):
                            print("   ", "%s:" % key, summary[key])
                sys.exit(0)
            elif option in ['-c', '--config']:
                setting_name = value
                set_value = False
                if setting_name:
                    if ":" in setting_name:
                        setting_name, new_value = setting_name.split(":", 1)
                        set_value = True
                    if config.has_default(setting_name):
                        setting_value = config.get(setting_name)
                        print(_("Current Gramps config setting: "
                                "%(name)s:%(value)s") % {
                                    'name': setting_name,
                                    'value': repr(setting_value)
                                },
                              file=sys.stderr)
                        if set_value:
                            # does a user want the default config value?
                            if new_value in ("DEFAULT", _("DEFAULT")):
                                new_value = config.get_default(setting_name)
                            else:
                                converter = get_type_converter(setting_value)
                                new_value = converter(new_value)
                            config.set(setting_name, new_value)
                            # translators: indent "New" to match "Current"
                            print(_("    New Gramps config setting: "
                                    "%(name)s:%(value)s") % {
                                        'name': setting_name,
                                        'value': repr(config.get(setting_name))
                                    },
                                  file=sys.stderr)
                        else:
                            need_to_quit = True
                    else:
                        print(_("Gramps: no such config setting: '%s'") %
                              setting_name,
                              file=sys.stderr)
                        need_to_quit = True
                cleandbg += [opt_ix]
            elif option in ['-h', '-?', '--help']:
                self.help = True
            elif option in ['-u', '--force-unlock']:
                self.force_unlock = True
            elif option in ['--usage']:
                self.usage = True
            elif option in ['-y', '--yes']:
                self.auto_accept = True
            elif option in ['-q', '--quiet']:
                self.quiet = True

        #clean options list
        cleandbg.reverse()
        for ind in cleandbg:
            del options[ind]

        if (len(options) > 0 and self.open is None and self.imports == []
                and self.removes == []
                and not (self.list or self.list_more or self.list_table
                         or self.help)):
            # Extract and convert to unicode the arguments in the list.
            # The % operator replaces the list elements with repr() of
            # the list elements, which is OK for latin characters
            # but not for non-latin characters in list elements
            cliargs = "[ "
            for arg in range(len(self.args) - 1):
                cliargs += self.args[arg + 1] + ' '
            cliargs += "]"
            self.errors += [(_('Error parsing the arguments'),
                             _("Error parsing the arguments: %s \n"
                               "To use in the command-line mode, supply at "
                               "least one input file to process.") % cliargs)]
        if need_to_quit:
            sys.exit(0)
def build_report_set():

    reports = []

    ##################################################################
    # Load plugins
    ##################################################################

    dbstate = DbState()
    climanager = CLIManager(dbstate, setloader = True, user = None)
    climanager.do_reg_plugins(dbstate, uistate = None)
    gpr = PluginRegister.get_instance()

    PLUGMAN = BasePluginManager.get_instance()
    CSS = PLUGMAN.process_plugin_data('WEBSTUFF')

    ##################################################################
    # GRAMPS native plugins
    ##################################################################

    # GRPH_FMT = ['odt', 'ps', 'pdf', 'svg']
    GRPH_FMT = ['pdf', 'svg']
    # GRPH_FMT = ['svg']
    GRPH_REP = [
        {
            'report': 'ancestor_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0006',
            },
        },
        {
            'report': 'descend_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0104',
            },
        },
        {
            'report': 'family_descend_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0104',
            },
        },
        {
            'report': 'fan_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0006',
            },
        },
        {
            'report': 'statistics_chart',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
           },
        },
        {
            'report': 'timeline',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
            },
        },
        {
            'report': 'calendar',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
            },
        },
        {
            'report': 'familylines_graph',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'gidlist': 'I0104 I0045',
                'limitchildren': True,
                'maxchildren': 20,
            },
        },
        {
            'report': 'hourglass_graph',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0044',
                'maxascend': 2,
                'maxdescend': 2,
            },
        },
        {
            'report': 'rel_graph',
            'options': {
                'scale_tree': 2,
                'maxgen': 6,
                'pid': 'I0044',
                'filter': 3,
                'event_choice': 2,
            },
        },
    ]

    # TEXT_FMT = ['ps', 'pdf', 'html', 'odt', 'tex', 'rtf', 'txt']
    TEXT_FMT = ['html', 'pdf', 'txt']
    # TEXT_FMT = ['html', 'txt']
    TEXT_REP = [
        {
            'report': 'ancestor_report',
            'options': {
                'maxgen': 6,
                'pid': 'I0006',
            },
        },
        {
            'report': 'descend_report',
            'options': {
                'pid': 'I0104',
            },
        },
        {
            'report': 'det_ancestor_report',
            'options': {
                'pid': 'I0006',
            },
        },
        {
            'report': 'det_descendant_report',
            'options': {
                'pid': 'I0104',
            },
        },
        {
            'report': 'family_group',
            'options': {
                'family_id': 'F0017',
            },
        },
        {
            'report': 'birthday_report',
            'options': {},
        },
        {
            'report': 'endofline_report',
            'options': {
                'pid': 'I0006',
            },
        },
        {
            'report': 'indiv_complete',
            'options': {},
        },
        {
            'report': 'kinship_report',
            'options': {
                'pid': 'I0044',
            },
        },
        {
            'report': 'tag_report',
            'options': {
                'tag': 'ToDo',
            },
        },
        {
            'report': 'number_of_ancestors',
            'options': {
                'pid': 'I0006',
            },
        },
        {
            'report': 'place_report',
            'options': {
                'places': 'P1678 P1679 P1680',
            },
        },
        {
            'report': 'summary',
            'options': {},
        },
        {
            'report': 'records',
            'options': {},
        },
        {
            'report': 'notelinkreport',
            'options': {},
        },
    ]


    # Single run with all native reports (except web) in all formats
    for (rep_list, formats) in [
        (TEXT_REP, TEXT_FMT),
        (GRPH_REP, GRPH_FMT),
    ]:
        for rep_info in TEXT_REP:
            report = rep_info['report']
            options = rep_info['options']
            plugin = gpr.get_plugin(report)
            if not plugin:
                print('Unknown plugin: %s' % report)
                continue
            for fmt in TEXT_FMT:
                of = os.path.join(GRAMPS_REP_DIR, report + '.' + fmt)
                new_options = {
                    'name': report,
                    'off': fmt,
                    'of': of,
                    # 'show': 'all',
                }
                new_options.update(options)
                reports.append({
                    'title': '"%s" in format "%s"' % (plugin.name, fmt),
                    'name': plugin.name,
                    'result': of,
                    'type': 'Native',
                    'category': plugin.category,
                    'version': plugin.version,
                    'options': new_options,
                })

    ##################################################################
    # GRAMPS native web reports
    ##################################################################

    full_options = {
        'linkhome': True,
        'showdeath': True,
        'showpartner': True,
        'showparents': True,
        'showhalfsiblings': True,
        'inc_families': True,
        'inc_repository': True,
        'inc_gendex': True,
        'inc_addressbook': True,
        'placemappages': True,
        'familymappages': True,
    }

    for (i, (css, full)) in enumerate([
        ['default', False],
        ['Mainz', True],
    ]):
        report = 'navwebpage'
        plugin = gpr.get_plugin(report)
        opts = {
            'name': report,
            'target': os.path.join(GRAMPS_REP_DIR, 'example_NAVWEB%i' % i),
            'css':  CSS[css]['id'],
            'living': _INCLUDE_LIVING_VALUE,
        }
        if (full): opts.update(full_options)
        reports.append({
            'title': '"%s" report example %i' % (plugin.name, i),
            'name': report,
            'result': os.path.join(GRAMPS_REP_DIR, 'example_NAVWEB%i' % i, 'index.html'),
            'type': 'Native',
            'category': plugin.category,
            'version': VERSION,
            'options': opts,
        })


    full_options = {
        'alive': False,
        'fullyear': True,
        'makeoneday': True,
        'link_to_narweb': True,
    }

    for (i, (css, full)) in enumerate([
        ['default', False],
        ['Mainz', True],
    ]):
        report = 'WebCal'
        plugin = gpr.get_plugin(report)
        opts = {
            'name': report,
            'target': os.path.join(GRAMPS_REP_DIR, 'example_WebCal%i' % i),
            'css':  CSS[css]['id'],
            'home_link': '../../example_NAVWEB%i/index.html' % i,
            'prefix': '../../example_NAVWEB%i/' % i,
        }
        page = 'January.html'
        if (full):
            opts.update(full_options)
            page = 'fullyearlinked.html'
        reports.append({
            'title': '"%s" report example %i' % (plugin.name, i),
            'name': report,
            'result': os.path.join(GRAMPS_REP_DIR, 'example_WebCal%i' % i, str(Today().get_year()), page),
            'type': 'Native',
            'category': plugin.category,
            'version': VERSION,
            'options': opts,
        })


    ##################################################################
    # GRAMPS addons reports
    ##################################################################


    addons=[]


    ########## AncestorFill

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'AncestorFill.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'AncestorFill',
            'options': {
                'off': fmt,
                'of': of,
            },
        })


    ########## d3-ancestralcollapsibletree

    addons.append({
        'title': '"%s" report example',
        'result': os.path.join(ADDONS_REP_DIR, 'd3-ancestralcollapsibletree', 'index.html'),
        'i': 'd3-ancestralcollapsibletree',
        'options': {
            'dest_path': os.path.join(ADDONS_REP_DIR, 'd3-ancestralcollapsibletree'),
            'dest_file': 'index.html',
            'pid': 'I0006',
            'maxgen': 6,
        },
    })


    ########## d3-ancestralfanchart

    addons.append({
        'title': '"%s" report example',
        'result': os.path.join(ADDONS_REP_DIR, 'd3-ancestralfanchart', 'index.html'),
        'i': 'd3-ancestralfanchart',
        'options': {
            'dest_path': os.path.join(ADDONS_REP_DIR, 'd3-ancestralfanchart'),
            'dest_file': 'index.html',
            'pid': 'I0006',
            'maxgen': 6,
        },
    })


    ########## d3-descendantindentedtree

    addons.append({
        'title': '"%s" report example',
        'result': os.path.join(ADDONS_REP_DIR, 'd3-descendantindentedtree', 'index.html'),
        'i': 'd3-descendantindentedtree',
        'options': {
            'dest_path': os.path.join(ADDONS_REP_DIR, 'd3-descendantindentedtree'),
            'dest_file': 'index.html',
            'pid': 'I0104',
            'max_gen': 6,
            'inc_private': True,
            'inc_living': _INCLUDE_LIVING_VALUE,
        },
    })


    ########## denominoviso

    for (i, (mode, type, dir, pid, full)) in enumerate([
        [0, 0, 0, 'I0001', True],
        [0, 3, 2, 'I0001', False],
        [0, 4, 2, 'I0001', False],
        [1, 0, 0, 'I0044', True],
        [1, 1, 0, 'I0044', False],
    ]):
        addons.append({
            'title': '"%%s" report example %i' % i,
            'result': os.path.join(ADDONS_REP_DIR, 'DenominoViso%i.xhtml' % i),
            'i': 'denominoviso',
            'options': {
                'DNMfilename': os.path.join(ADDONS_REP_DIR, 'DenominoViso%i.xhtml' % i),
                'DNMchart_mode': mode,
                'DNMpid': pid,
                'DNMchart_type': type,
                'DNMinc_attributes_m': '"True, "',
                'DNMinc_addresses': full,
                'DNMinc_notes': full,
                'DNMinc_url': full,
                'DNMinc_url_desc': full,
                'DNMinc_sources': full,
                'DNMinc_img': full,
                'DNMcopy_img_m': '"%s, %s%i"' % (str(full), os.path.join(ADDONS_REP_DIR, 'DenominoViso'), i),
            },
        })


    ########## DescendantBook

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'DescendantBook.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'DescendantBook',
            'options': {
                'off': fmt,
                'of': of,
            },
        })

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'DetailedDescendantBook.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'DetailedDescendantBook',
            'options': {
                'off': fmt,
                'of': of,
            },
        })


    ########## Descendants Lines

    for fmt in GRPH_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'DescendantsLines.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'Descendants Lines',
            'options': {
                'off': fmt,
                'of': of,
                'pid': 'I0006',
            },
        })


    ########## database-differences-report

    for fmt in ['html']:
        of = os.path.join(ADDONS_REP_DIR, 'database-differences-report.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'database-differences-report',
            'options': {
                'off': fmt,
                'of': of,
                'filename': os.path.join(os.environ['GRAMPS_RESOURCES'], 'example', 'gramps', 'example.gramps'),
            },
        })


    ########## DynamicWeb

    addons.extend(report_set_DynamicWeb.addon_set())


    ########## FamilyTree

    for fmt in GRPH_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'FamilyTree.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'FamilyTree',
            'options': {
                'off': fmt,
                'of': of,
                'pid': 'I0006',
                'max_ancestor_generations': 3,
                'max_descendant_generations': 3,
                'papero': 1,
                'protect_private': False,
                'color': 1,
            },
        })


    ########## LastChangeReport

    for fmt in ['html']:
        of = os.path.join(ADDONS_REP_DIR, 'LastChangeReport.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'LastChangeReport',
            'options': {
                'off': fmt,
                'of': of,
                'what_types': '"True,True,True,True,True,True"'
            },
        })


    ########## LinesOfDescendency

    for fmt in ['html']:
        of = os.path.join(ADDONS_REP_DIR, 'LinesOfDescendency.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'LinesOfDescendency',
            'options': {
                'off': fmt,
                'of': of,
                'pid': 'I0006',
                'ancestor': 'I0104',
            },
        })


    ########## ListeEclair

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'ListeEclair.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'ListeEclair',
            'options': {
                'off': fmt,
                'of': of,
            },
        })


    ########## PedigreeChart

    for fmt in GRPH_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'PedigreeChart.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'PedigreeChart',
            'options': {
                'off': fmt,
                'of': of,
                'maxgen': 6,
                'pid': 'I0006',
            },
        })


    ########## PersonEverythingReport

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'PersonEverythingReport.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'PersonEverythingReport',
            'options': {
                'off': fmt,
                'of': of,
            },
        })


    ########## Repositories Report

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'RepositoriesReportOptions.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'Repositories Report Options',
            'options': {
                'off': fmt,
                'of': of,
            },
        })

    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'RepositoriesReport.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'Repositories Report',
            'options': {
                'off': fmt,
                'of': of,
            },
        })


    ########## TodoReport

    reports=[]
    addons=[]
    for fmt in TEXT_FMT:
        of = os.path.join(ADDONS_REP_DIR, 'TodoReport.' + fmt)
        addons.append({
            'title': '"%%s" in format "%s"' % fmt,
            'result': of,
            'i': 'TodoReport',
            'options': {
                'off': fmt,
                'of': of,
                'tag': 'ToDo',
            },
        })


    ########## Check if addon exists in the addons listings

    for addon in addons:
        plugin = gpr.get_plugin(addon['i'])
        if not plugin:
            print('Unknown plugin: %s' % addon['i'])
            continue
        addon['options'].update({
            'name': addon['i'],
        })
        addon.update({
            'title': addon['title'] % plugin.name,
            'name': plugin.name,
            'type': 'Addon',
            'category': plugin.category,
            'version': plugin.version,
        })
        del addon['i']
        reports.append(addon)

    return reports
Example #45
0
    def cl_action(self, action, options_str):
        """
        Command-line action routine. Try to perform specified action.
        """
        pmgr = BasePluginManager.get_instance()
        if action == "report":
            try:
                options_str_dict = _split_options(options_str)
            except:
                options_str_dict = {}
                print(_("Ignoring invalid options string."),
                      file=sys.stderr)

            name = options_str_dict.pop('name', None)
            _cl_list = pmgr.get_reg_reports(gui=False)
            if name:
                for pdata in _cl_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return
                        category = pdata.category
                        report_class = eval('mod.' + pdata.reportclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        if category in (CATEGORY_BOOK, CATEGORY_CODE):
                            options_class(self.dbstate.db, name, category,
                                          options_str_dict)
                        else:
                            cl_report(self.dbstate.db, name, category,
                                      report_class, options_class,
                                      options_str_dict)
                        return
                # name exists, but is not in the list of valid report names
                msg = _("Unknown report name.")
            else:
                msg = _("Report name not given. "
                        "Please use one of %(donottranslate)s=reportname"
                       ) % {'donottranslate' : '[-p|--options] name'}

            print(_("%s\n Available names are:") % msg, file=sys.stderr)
            for pdata in sorted(_cl_list, key=lambda pdata: pdata.id.lower()):
                # Print cli report name ([item[0]), GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print("   %s%s- %s" % (pdata.id,
                                           " " * (26 - len(pdata.id)),
                                           pdata.name),
                          file=sys.stderr)
                else:
                    print("   %s\t- %s" % (pdata.id, pdata.name),
                          file=sys.stderr)

        elif action == "tool":
            from gramps.gui.plug import tool
            try:
                options_str_dict = dict([tuple(chunk.split('='))
                                         for chunk in options_str.split(',')])
            except:
                options_str_dict = {}
                print(_("Ignoring invalid options string."),
                      file=sys.stderr)

            name = options_str_dict.pop('name', None)
            _cli_tool_list = pmgr.get_reg_tools(gui=False)
            if name:
                for pdata in _cli_tool_list:
                    if name == pdata.id:
                        mod = pmgr.load_plugin(pdata)
                        if not mod:
                            #import of plugin failed
                            return
                        category = pdata.category
                        tool_class = eval('mod.' + pdata.toolclass)
                        options_class = eval('mod.' + pdata.optionclass)
                        tool.cli_tool(dbstate=self.dbstate,
                                      name=name,
                                      category=category,
                                      tool_class=tool_class,
                                      options_class=options_class,
                                      options_str_dict=options_str_dict,
                                      user=self.user)
                        return
                msg = _("Unknown tool name.")
            else:
                msg = _("Tool name not given. "
                        "Please use one of %(donottranslate)s=toolname."
                       ) % {'donottranslate' : '[-p|--options] name'}

            print(_("%s\n Available names are:") % msg, file=sys.stderr)
            for pdata in sorted(_cli_tool_list,
                                key=lambda pdata: pdata.id.lower()):
                # Print cli report name ([item[0]), GUI report name (item[4])
                if len(pdata.id) <= 25:
                    print("   %s%s- %s" % (pdata.id,
                                           " " * (26 - len(pdata.id)),
                                           pdata.name),
                          file=sys.stderr)
                else:
                    print("   %s\t- %s" % (pdata.id, pdata.name),
                          file=sys.stderr)

        elif action == "book":
            try:
                options_str_dict = _split_options(options_str)
            except:
                options_str_dict = {}
                print(_("Ignoring invalid options string."),
                      file=sys.stderr)

            name = options_str_dict.pop('name', None)
            book_list = BookList('books.xml', self.dbstate.db)
            if name:
                if name in book_list.get_book_names():
                    cl_book(self.dbstate.db, name, book_list.get_book(name),
                            options_str_dict)
                    return
                msg = _("Unknown book name.")
            else:
                msg = _("Book name not given. "
                        "Please use one of %(donottranslate)s=bookname."
                       ) % {'donottranslate' : '[-p|--options] name'}

            print(_("%s\n Available names are:") % msg, file=sys.stderr)
            for name in sorted(book_list.get_book_names()):
                print("   %s" % name, file=sys.stderr)

        else:
            print(_("Unknown action: %s.") % action, file=sys.stderr)
            sys.exit(1)