Пример #1
0
    def setup_style_frame(self):
        """Set up the style frame of the dialog.  This function relies
        on other routines to create the default style for this report,
        and to read in any user-defined styles for this report.  It
        then builds a menu of all the available styles for the user to
        choose from."""
        # Build the default style set for this report.
        self.default_style = StyleSheet()
        self.options.make_default_style(self.default_style)

        if self.default_style.is_empty():
            # Don't display the option if no styles are used
            return

        # Styles Frame
        label = Gtk.Label(label="%s:" % _("Style"))
        label.set_alignment(0.0, 0.5)

        self.style_menu = StyleComboBox()
        self.style_button = Gtk.Button("%s..." % _("Style Editor"))
        self.style_button.connect('clicked', self.on_style_edit_clicked)

        self.tbl.attach(label, 1, 2, self.row, self.row + 1,
                        Gtk.AttachOptions.SHRINK | Gtk.AttachOptions.FILL)
        self.tbl.attach(self.style_menu,
                        2,
                        3,
                        self.row,
                        self.row + 1,
                        yoptions=Gtk.AttachOptions.SHRINK)
        self.tbl.attach(self.style_button,
                        3,
                        4,
                        self.row,
                        self.row + 1,
                        xoptions=Gtk.AttachOptions.SHRINK
                        | Gtk.AttachOptions.FILL,
                        yoptions=Gtk.AttachOptions.SHRINK)
        self.row += 1

        # Build the initial list of available styles sets.  This
        # includes the default style set and any style sets saved from
        # previous invocations of gramps.
        self.style_sheet_list = StyleSheetList(
            self.options.handler.get_stylesheet_savefile(), self.default_style)

        # Now build the actual menu.
        style = self.options.handler.get_default_stylesheet_name()
        self.build_style_menu(style)
Пример #2
0
    def parse_options(self):
        """
        Load the options that the user has entered.
        """
        if not hasattr(self.option_class, "menu"):
            menu = None
        else:
            menu = self.option_class.menu
            menu_opt_names = menu.get_all_option_names()

        _format_str = self.options_str_dict.pop('off', None)
        if _format_str:
            self.options_dict['off'] = _format_str

        self.css_filename = None
        _chosen_format = None

        self.doc_option_class = None
        if self.category in [CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_BOOK]:
            if self.category == CATEGORY_TEXT:
                plugins = self.__textdoc_plugins
                self.css_filename = self.options_dict['css']
            elif self.category == CATEGORY_DRAW:
                plugins = self.__drawdoc_plugins
            elif self.category == CATEGORY_BOOK:
                plugins = self.__bookdoc_plugins
            for plugin in plugins:
                if plugin.get_extension() == self.options_dict['off']:
                    self.format = plugin.get_basedoc()
                    self.doc_option_class = plugin.get_doc_option_class()
            if self.format is None:
                # Pick the first one as the default.
                plugin = plugins[0]
                self.format = plugin.get_basedoc()
                self.doc_option_class = plugin.get_doc_option_class()
                _chosen_format = plugin.get_extension()
        elif self.category == CATEGORY_GRAPHVIZ:
            for graph_format in graphdoc.FORMATS:
                if graph_format['type'] == self.options_dict['off']:
                    if not self.format:  # choose the first one, not the last
                        self.format = graph_format["class"]
            if self.format is None:
                # Pick the first one as the default.
                self.format = graphdoc.FORMATS[0]["class"]
                _chosen_format = graphdoc.FORMATS[0]["type"]
        else:
            self.format = None
        if _chosen_format and _format_str:
            print(_("Ignoring '%(notranslate1)s=%(notranslate2)s' "
                    "and using '%(notranslate1)s=%(notranslate3)s'.") % {
                        'notranslate1': "off",
                        'notranslate2': self.options_dict['off'],
                        'notranslate3': _chosen_format
                    },
                  file=sys.stderr)
            print(_("Use '%(notranslate)s' to see valid values.") %
                  {'notranslate': "show=off"},
                  file=sys.stderr)

        self.do_doc_options()

        for opt in self.options_str_dict:
            if opt in self.options_dict:
                self.options_dict[opt] = \
                    _convert_str_to_match_type(self.options_str_dict[opt],
                                               self.options_dict[opt])

                self.option_class.handler.options_dict[opt] = \
                                                      self.options_dict[opt]

                if menu and opt in menu_opt_names:
                    option = menu.get_option_by_name(opt)
                    option.set_value(self.options_dict[opt])

            else:
                print(_("Ignoring unknown option: %s") % opt, file=sys.stderr)
                print(_("   Valid options are:"),
                      ", ".join(list(self.options_dict.keys())),
                      file=sys.stderr)
                print(_("   Use '%(donottranslate)s' to see description "
                        "and acceptable values") %
                      {'donottranslate': "show=option"},
                      file=sys.stderr)

        self.option_class.handler.output = self.options_dict['of']

        self.paper = paper_sizes[0]  # make sure one exists
        for paper in paper_sizes:
            if paper.get_name() == self.options_dict['papers']:
                self.paper = paper
        self.option_class.handler.set_paper(self.paper)

        self.orien = self.options_dict['papero']

        self.marginl = self.options_dict['paperml']
        self.marginr = self.options_dict['papermr']
        self.margint = self.options_dict['papermt']
        self.marginb = self.options_dict['papermb']

        if self.category in (CATEGORY_TEXT, CATEGORY_DRAW):
            default_style = StyleSheet()
            self.option_class.make_default_style(default_style)

            # Read all style sheets available for this item
            style_file = self.option_class.handler.get_stylesheet_savefile()
            self.style_list = StyleSheetList(style_file, default_style)

            # Get the selected stylesheet
            style_name = self.option_class.handler.get_default_stylesheet_name(
            )
            self.selected_style = self.style_list.get_style_sheet(style_name)
Пример #3
0
    def init_standard_options(self, noopt):
        """
        Initialize the options that are hard-coded into the report system.
        """
        self.options_dict = {
            'of'        : self.option_class.handler.module_name,
            'off'       : self.option_class.handler.get_format_name(),
            'style'     : \
                    self.option_class.handler.get_default_stylesheet_name(),
            'papers'    : self.option_class.handler.get_paper_name(),
            'papero'    : self.option_class.handler.get_orientation(),
            'paperml'   : self.option_class.handler.get_margins()[0],
            'papermr'   : self.option_class.handler.get_margins()[1],
            'papermt'   : self.option_class.handler.get_margins()[2],
            'papermb'   : self.option_class.handler.get_margins()[3],
            'css'       : self.option_class.handler.get_css_filename(),
            }

        self.options_help = {
            'of': [_("=filename"),
                   _("Output file name. MANDATORY"), ""],
            'off': [_("=format"), _("Output file format."), []],
            'style': [_("=name"), _("Style name."), ""],
            'papers': [_("=name"), _("Paper size name."), ""],
            'papero': [_("=number"),
                       _("Paper orientation number."), ""],
            'paperml': [_("=number"),
                        _("Left paper margin"),
                        _("Size in cm")],
            'papermr':
            [_("=number"),
             _("Right paper margin"),
             _("Size in cm")],
            'papermt': [_("=number"),
                        _("Top paper margin"),
                        _("Size in cm")],
            'papermb':
            [_("=number"),
             _("Bottom paper margin"),
             _("Size in cm")],
            'css': [
                _("=css filename"),
                _("CSS filename to use, "
                  "html format only"), ""
            ],
        }

        if noopt:
            return

        self.options_help['of'][2] = os.path.join(USER_HOME, "whatever_name")

        if self.category == CATEGORY_TEXT:
            for plugin in self.__textdoc_plugins:
                self.options_help['off'][2].append(plugin.get_extension() +
                                                   "\t" +
                                                   plugin.get_description())
        elif self.category == CATEGORY_DRAW:
            for plugin in self.__drawdoc_plugins:
                self.options_help['off'][2].append(plugin.get_extension() +
                                                   "\t" +
                                                   plugin.get_description())
        elif self.category == CATEGORY_BOOK:
            for plugin in self.__bookdoc_plugins:
                self.options_help['off'][2].append(plugin.get_extension() +
                                                   "\t" +
                                                   plugin.get_description())
        elif self.category == CATEGORY_GRAPHVIZ:
            for graph_format in graphdoc.FORMATS:
                self.options_help['off'][2].append(graph_format["type"] +
                                                   "\t" +
                                                   graph_format["descr"])
        else:
            self.options_help['off'][2] = "NA"

        self.options_help['papers'][2] = \
            [ paper.get_name() for paper in paper_sizes
                        if paper.get_name() != 'Custom Size' ]

        self.options_help['papero'][2] = [
            "%d\tPortrait" % PAPER_PORTRAIT,
            "%d\tLandscape" % PAPER_LANDSCAPE
        ]

        self.options_help['css'][2] = os.path.join(USER_HOME,
                                                   "whatever_name.css")

        if self.category in (CATEGORY_TEXT, CATEGORY_DRAW):
            default_style = StyleSheet()
            self.option_class.make_default_style(default_style)

            # Read all style sheets available for this item
            style_file = self.option_class.handler.get_stylesheet_savefile()
            self.style_list = StyleSheetList(style_file, default_style)

            self.options_help['style'][2] = self.style_list.get_style_names()
Пример #4
0
class CommandLineReport(object):
    """
    Provide a way to generate report from the command line.
    """
    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_text_support() and \
               plugin.get_draw_support() and \
               plugin.get_extension():
                self.__bookdoc_plugins.append(plugin)

        self.database = database
        self.category = category
        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()

    def init_standard_options(self, noopt):
        """
        Initialize the options that are hard-coded into the report system.
        """
        self.options_dict = {
            'of'        : self.option_class.handler.module_name,
            'off'       : self.option_class.handler.get_format_name(),
            'style'     : \
                    self.option_class.handler.get_default_stylesheet_name(),
            'papers'    : self.option_class.handler.get_paper_name(),
            'papero'    : self.option_class.handler.get_orientation(),
            'paperml'   : self.option_class.handler.get_margins()[0],
            'papermr'   : self.option_class.handler.get_margins()[1],
            'papermt'   : self.option_class.handler.get_margins()[2],
            'papermb'   : self.option_class.handler.get_margins()[3],
            'css'       : self.option_class.handler.get_css_filename(),
            }

        self.options_help = {
            'of': [_("=filename"),
                   _("Output file name. MANDATORY"), ""],
            'off': [_("=format"), _("Output file format."), []],
            'style': [_("=name"), _("Style name."), ""],
            'papers': [_("=name"), _("Paper size name."), ""],
            'papero': [_("=number"),
                       _("Paper orientation number."), ""],
            'paperml': [_("=number"),
                        _("Left paper margin"),
                        _("Size in cm")],
            'papermr':
            [_("=number"),
             _("Right paper margin"),
             _("Size in cm")],
            'papermt': [_("=number"),
                        _("Top paper margin"),
                        _("Size in cm")],
            'papermb':
            [_("=number"),
             _("Bottom paper margin"),
             _("Size in cm")],
            'css': [
                _("=css filename"),
                _("CSS filename to use, "
                  "html format only"), ""
            ],
        }

        if noopt:
            return

        self.options_help['of'][2] = os.path.join(USER_HOME, "whatever_name")

        if self.category == CATEGORY_TEXT:
            for plugin in self.__textdoc_plugins:
                self.options_help['off'][2].append(plugin.get_extension() +
                                                   "\t" +
                                                   plugin.get_description())
        elif self.category == CATEGORY_DRAW:
            for plugin in self.__drawdoc_plugins:
                self.options_help['off'][2].append(plugin.get_extension() +
                                                   "\t" +
                                                   plugin.get_description())
        elif self.category == CATEGORY_BOOK:
            for plugin in self.__bookdoc_plugins:
                self.options_help['off'][2].append(plugin.get_extension() +
                                                   "\t" +
                                                   plugin.get_description())
        elif self.category == CATEGORY_GRAPHVIZ:
            for graph_format in graphdoc.FORMATS:
                self.options_help['off'][2].append(graph_format["type"] +
                                                   "\t" +
                                                   graph_format["descr"])
        else:
            self.options_help['off'][2] = "NA"

        self.options_help['papers'][2] = \
            [ paper.get_name() for paper in paper_sizes
                        if paper.get_name() != 'Custom Size' ]

        self.options_help['papero'][2] = [
            "%d\tPortrait" % PAPER_PORTRAIT,
            "%d\tLandscape" % PAPER_LANDSCAPE
        ]

        self.options_help['css'][2] = os.path.join(USER_HOME,
                                                   "whatever_name.css")

        if self.category in (CATEGORY_TEXT, CATEGORY_DRAW):
            default_style = StyleSheet()
            self.option_class.make_default_style(default_style)

            # Read all style sheets available for this item
            style_file = self.option_class.handler.get_stylesheet_savefile()
            self.style_list = StyleSheetList(style_file, default_style)

            self.options_help['style'][2] = self.style_list.get_style_names()

    def init_report_options(self):
        """
        Initialize the options that are defined by each report.
        """

        if self.category == CATEGORY_BOOK:  # a Book Report has no "menu"
            for key in self.option_class.options_dict:
                self.options_dict[key] = self.option_class.options_dict[key]
                self.options_help[key] = \
                    self.option_class.options_help[key][:3]
            # a Book Report can't have HTML output so "css" is meaningless
            self.options_dict.pop('css')

        if not hasattr(self.option_class, "menu"):
            return
        menu = self.option_class.menu
        for name in menu.get_all_option_names():
            option = menu.get_option_by_name(name)
            self.options_dict[name] = option.get_value()

    def init_report_options_help(self):
        """
        Initialize help for the options that are defined by each report.
        (And also any docgen options, if defined by the docgen.)
        """
        if not hasattr(self.option_class, "menu"):
            return
        menu = self.option_class.menu
        for name in menu.get_all_option_names():
            option = menu.get_option_by_name(name)
            self.options_help[name] = ["", option.get_help()]

            if isinstance(option, PersonOption):
                id_list = []
                for person_handle in self.database.get_person_handles(True):
                    person = self.database.get_person_from_handle(
                        person_handle)
                    id_list.append("%s\t%s" % (person.get_gramps_id(),
                                               name_displayer.display(person)))
                self.options_help[name].append(id_list)
            elif isinstance(option, FamilyOption):
                id_list = []
                for family in self.database.iter_families():
                    mname = ""
                    fname = ""
                    mhandle = family.get_mother_handle()
                    if mhandle:
                        mother = self.database.get_person_from_handle(mhandle)
                        if mother:
                            mname = name_displayer.display(mother)
                    fhandle = family.get_father_handle()
                    if fhandle:
                        father = self.database.get_person_from_handle(fhandle)
                        if father:
                            fname = name_displayer.display(father)
                    text = "%s:\t%s, %s" % \
                        (family.get_gramps_id(), fname, mname)
                    id_list.append(text)
                self.options_help[name].append(id_list)
            elif isinstance(option, NoteOption):
                id_list = []
                for nhandle in self.database.get_note_handles():
                    note = self.database.get_note_from_handle(nhandle)
                    id_list.append(note.get_gramps_id())
                self.options_help[name].append(id_list)
            elif isinstance(option, MediaOption):
                id_list = []
                for mhandle in self.database.get_media_object_handles():
                    mobject = self.database.get_object_from_handle(mhandle)
                    id_list.append(mobject.get_gramps_id())
                self.options_help[name].append(id_list)
            elif isinstance(option, PersonListOption):
                self.options_help[name].append("")
            elif isinstance(option, NumberOption):
                self.options_help[name].append("A number")
            elif isinstance(option, BooleanOption):
                self.options_help[name].append(["False", "True"])
            elif isinstance(option, DestinationOption):
                self.options_help[name].append("A file system path")
            elif isinstance(option, StringOption):
                self.options_help[name].append("Any text")
            elif isinstance(option, TextOption):
                self.options_help[name].append(
                    "A list of text values. Each entry in the list "
                    "represents one line of text.")
            elif isinstance(option, EnumeratedListOption):
                ilist = []
                for (value, description) in option.get_items():
                    ilist.append("%s\t%s" % (value, description))
                self.options_help[name].append(ilist)
            elif isinstance(option, Option):
                self.options_help[name].append(option.get_help())
            else:
                print(_("Unknown option: %s") % option, file=sys.stderr)
                print(_("   Valid options are:") +
                      ", ".join(list(self.options_dict.keys())),
                      file=sys.stderr)
                print(_("   Use '%(donottranslate)s' to see description "
                        "and acceptable values") %
                      {'donottranslate': "show=option"},
                      file=sys.stderr)

    def parse_options(self):
        """
        Load the options that the user has entered.
        """
        if not hasattr(self.option_class, "menu"):
            menu = None
        else:
            menu = self.option_class.menu
            menu_opt_names = menu.get_all_option_names()

        _format_str = self.options_str_dict.pop('off', None)
        if _format_str:
            self.options_dict['off'] = _format_str

        self.css_filename = None
        _chosen_format = None

        self.doc_option_class = None
        if self.category in [CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_BOOK]:
            if self.category == CATEGORY_TEXT:
                plugins = self.__textdoc_plugins
                self.css_filename = self.options_dict['css']
            elif self.category == CATEGORY_DRAW:
                plugins = self.__drawdoc_plugins
            elif self.category == CATEGORY_BOOK:
                plugins = self.__bookdoc_plugins
            for plugin in plugins:
                if plugin.get_extension() == self.options_dict['off']:
                    self.format = plugin.get_basedoc()
                    self.doc_option_class = plugin.get_doc_option_class()
            if self.format is None:
                # Pick the first one as the default.
                plugin = plugins[0]
                self.format = plugin.get_basedoc()
                self.doc_option_class = plugin.get_doc_option_class()
                _chosen_format = plugin.get_extension()
        elif self.category == CATEGORY_GRAPHVIZ:
            for graph_format in graphdoc.FORMATS:
                if graph_format['type'] == self.options_dict['off']:
                    if not self.format:  # choose the first one, not the last
                        self.format = graph_format["class"]
            if self.format is None:
                # Pick the first one as the default.
                self.format = graphdoc.FORMATS[0]["class"]
                _chosen_format = graphdoc.FORMATS[0]["type"]
        else:
            self.format = None
        if _chosen_format and _format_str:
            print(_("Ignoring '%(notranslate1)s=%(notranslate2)s' "
                    "and using '%(notranslate1)s=%(notranslate3)s'.") % {
                        'notranslate1': "off",
                        'notranslate2': self.options_dict['off'],
                        'notranslate3': _chosen_format
                    },
                  file=sys.stderr)
            print(_("Use '%(notranslate)s' to see valid values.") %
                  {'notranslate': "show=off"},
                  file=sys.stderr)

        self.do_doc_options()

        for opt in self.options_str_dict:
            if opt in self.options_dict:
                self.options_dict[opt] = \
                    _convert_str_to_match_type(self.options_str_dict[opt],
                                               self.options_dict[opt])

                self.option_class.handler.options_dict[opt] = \
                                                      self.options_dict[opt]

                if menu and opt in menu_opt_names:
                    option = menu.get_option_by_name(opt)
                    option.set_value(self.options_dict[opt])

            else:
                print(_("Ignoring unknown option: %s") % opt, file=sys.stderr)
                print(_("   Valid options are:"),
                      ", ".join(list(self.options_dict.keys())),
                      file=sys.stderr)
                print(_("   Use '%(donottranslate)s' to see description "
                        "and acceptable values") %
                      {'donottranslate': "show=option"},
                      file=sys.stderr)

        self.option_class.handler.output = self.options_dict['of']

        self.paper = paper_sizes[0]  # make sure one exists
        for paper in paper_sizes:
            if paper.get_name() == self.options_dict['papers']:
                self.paper = paper
        self.option_class.handler.set_paper(self.paper)

        self.orien = self.options_dict['papero']

        self.marginl = self.options_dict['paperml']
        self.marginr = self.options_dict['papermr']
        self.margint = self.options_dict['papermt']
        self.marginb = self.options_dict['papermb']

        if self.category in (CATEGORY_TEXT, CATEGORY_DRAW):
            default_style = StyleSheet()
            self.option_class.make_default_style(default_style)

            # Read all style sheets available for this item
            style_file = self.option_class.handler.get_stylesheet_savefile()
            self.style_list = StyleSheetList(style_file, default_style)

            # Get the selected stylesheet
            style_name = self.option_class.handler.get_default_stylesheet_name(
            )
            self.selected_style = self.style_list.get_style_sheet(style_name)

    def do_doc_options(self):
        self.doc_options = None
        if not self.doc_option_class:
            return  # this docgen type has no options
        try:
            if issubclass(self.doc_option_class, object):
                self.doc_options = self.doc_option_class(
                    self.raw_name, self.database)
                doc_options_dict = self.doc_options.options_dict
        except TypeError:
            self.doc_options = self.doc_option_class
        self.doc_options.load_previous_values()
        docgen_menu = self.doc_options.menu
        report_menu = self.option_class.menu  # "help" checks the option type
        for oname in docgen_menu.get_option_names('Document Options'):
            docgen_opt = docgen_menu.get_option('Document Options', oname)
            if oname in self.options_str_dict and oname in doc_options_dict:
                doc_options_dict[oname] = \
                    _convert_str_to_match_type(self.options_str_dict[oname],
                                               doc_options_dict[oname])
                self.options_str_dict.pop(oname)
            if oname in doc_options_dict:
                docgen_opt.set_value(doc_options_dict[oname])
            report_menu.add_option('Document Options', oname, docgen_opt)
        for oname in doc_options_dict:  # enable "help"
            self.options_dict[oname] = doc_options_dict[oname]
            self.options_help[oname] = self.doc_options.options_help[oname][:3]

    def show_options(self):
        """
        Print available options on the CLI.
        """
        if not self.show:
            return
        elif self.show == 'all':
            print(_("   Available options:"))
            for key in sorted(self.options_dict.keys()):
                if key in self.options_help:
                    opt = self.options_help[key]
                    # Make the output nicer to read, assume a tab has 8 spaces
                    tabs = '\t\t' if len(key) < 10 else '\t'
                    optmsg = "      %s%s%s (%s)" % (key, tabs, opt[1], opt[0])
                else:
                    optmsg = "      %s%s%s" % (key, tabs,
                                               _('(no help available)'))
                print(optmsg)
            print(
                _("   Use '%(donottranslate)s' to see description "
                  "and acceptable values") % {'donottranslate': "show=option"})
        elif self.show in self.options_help:
            opt = self.options_help[self.show]
            tabs = '\t\t' if len(self.show) < 10 else '\t'
            print('   %s%s%s (%s)' % (self.show, tabs, opt[1], opt[0]))
            print(_("   Available values are:"))
            vals = opt[2]
            if isinstance(vals, (list, tuple)):
                for val in vals:
                    print("      %s" % val)
            else:
                print("      %s" % opt[2])

        else:
            #there was a show option given, but the option is invalid
            print(_("option '%(optionname)s' not valid. "
                    "Use '%(donottranslate)s' to see all valid options.") % {
                        'optionname': self.show,
                        'donottranslate': "show=all"
                    },
                  file=sys.stderr)
Пример #5
0
    def parse_options(self):
        """
        Load the options that the user has entered.
        """
        if not hasattr(self.option_class, "menu"):
            menu = None
        else:
            menu = self.option_class.menu
            menu_opt_names = menu.get_all_option_names()

        _format_str = self.options_str_dict.pop('off', None)
        if _format_str:
            self.options_dict['off'] = _format_str

        self.css_filename = None
        _chosen_format = None

        self.doc_option_class = None
        if self.category in [CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_BOOK]:
            if self.category == CATEGORY_TEXT:
                plugins = self.__textdoc_plugins
                self.css_filename = self.options_dict['css']
            elif self.category == CATEGORY_DRAW:
                plugins = self.__drawdoc_plugins
            elif self.category == CATEGORY_BOOK:
                plugins = self.__bookdoc_plugins
            for plugin in plugins:
                if plugin.get_extension() == self.options_dict['off']:
                    self.format = plugin.get_basedoc()
                    self.doc_option_class = plugin.get_doc_option_class()
            if self.format is None:
                # Pick the first one as the default.
                plugin = plugins[0]
                self.format = plugin.get_basedoc()
                self.doc_option_class = plugin.get_doc_option_class()
                _chosen_format = plugin.get_extension()
        elif self.category == CATEGORY_GRAPHVIZ:
            for graph_format in graphdoc.FORMATS:
                if graph_format['type'] == self.options_dict['off']:
                    if not self.format: # choose the first one, not the last
                        self.format = graph_format["class"]
            if self.format is None:
                # Pick the first one as the default.
                self.format = graphdoc.FORMATS[0]["class"]
                _chosen_format = graphdoc.FORMATS[0]["type"]
        elif self.category == CATEGORY_TREE:
            for tree_format in treedoc.FORMATS:
                if tree_format['type'] == self.options_dict['off']:
                    if not self.format: # choose the first one, not the last
                        self.format = tree_format["class"]
            if self.format is None:
                # Pick the first one as the default.
                self.format = tree_format.FORMATS[0]["class"]
                _chosen_format = tree_format.FORMATS[0]["type"]
        else:
            self.format = None
        if _chosen_format and _format_str:
            print(_("Ignoring '%(notranslate1)s=%(notranslate2)s' "
                    "and using '%(notranslate1)s=%(notranslate3)s'."
                   ) % {'notranslate1' : "off",
                        'notranslate2' : self.options_dict['off'],
                        'notranslate3' : _chosen_format},
                  file=sys.stderr)
            print(_("Use '%(notranslate)s' to see valid values."
                   ) % {'notranslate' : "show=off"}, file=sys.stderr)

        self.do_doc_options()

        for opt in self.options_str_dict:
            if opt in self.options_dict:
                self.options_dict[opt] = _convert_str_to_match_type(
                    self.options_str_dict[opt], self.options_dict[opt])

                self.option_class.handler.options_dict[
                    opt] = self.options_dict[opt]

                if menu and opt in menu_opt_names:
                    option = menu.get_option_by_name(opt)
                    option.set_value(self.options_dict[opt])

            else:
                print(_("Ignoring unknown option: %s") % opt, file=sys.stderr)
                print(_("   Valid options are:"),
                      _(", ").join(list(self.options_dict.keys())), # Arabic OK
                      file=sys.stderr)
                print(_("   Use '%(donottranslate)s' to see description "
                        "and acceptable values"
                       ) % {'donottranslate' : "show=option"},
                      file=sys.stderr)

        self.option_class.handler.output = self.options_dict['of']

        self.paper = paper_sizes[0] # make sure one exists
        for paper in paper_sizes:
            if paper.get_name() == self.options_dict['papers']:
                self.paper = paper
        self.option_class.handler.set_paper(self.paper)

        self.orien = self.options_dict['papero']

        self.marginl = self.options_dict['paperml']
        self.marginr = self.options_dict['papermr']
        self.margint = self.options_dict['papermt']
        self.marginb = self.options_dict['papermb']

        if self.category in (CATEGORY_TEXT, CATEGORY_DRAW):
            default_style = StyleSheet()
            self.option_class.make_default_style(default_style)

            # Read all style sheets available for this item
            style_file = self.option_class.handler.get_stylesheet_savefile()
            self.style_list = StyleSheetList(style_file, default_style)

            # Get the selected stylesheet
            style_name = self.option_class.handler.get_default_stylesheet_name()
            self.selected_style = self.style_list.get_style_sheet(style_name)
Пример #6
0
    def init_standard_options(self, noopt):
        """
        Initialize the options that are hard-coded into the report system.
        """
        self.options_dict = {
            'of'        : self.option_class.handler.module_name,
            'off'       : self.option_class.handler.get_format_name(),
            'style'     :
                self.option_class.handler.get_default_stylesheet_name(),
            'papers'    : self.option_class.handler.get_paper_name(),
            'papero'    : self.option_class.handler.get_orientation(),
            'paperml'   : self.option_class.handler.get_margins()[0],
            'papermr'   : self.option_class.handler.get_margins()[1],
            'papermt'   : self.option_class.handler.get_margins()[2],
            'papermb'   : self.option_class.handler.get_margins()[3],
            'css'       : self.option_class.handler.get_css_filename(),
            }

        self.options_help = {
            'of'        : [_("=filename"),
                           _("Output file name. MANDATORY"), ""],
            'off'       : [_("=format"), _("Output file format."), []],
            'style'     : [_("=name"), _("Style name."), ""],
            'papers'    : [_("=name"), _("Paper size name."), ""],
            'papero'    : [_("=number"), _("Paper orientation number."), ""],
            'paperml'   : [_("=number"),
                           _("Left paper margin"), _("Size in cm")],
            'papermr'   : [_("=number"),
                           _("Right paper margin"), _("Size in cm")],
            'papermt'   : [_("=number"),
                           _("Top paper margin"), _("Size in cm")],
            'papermb'   : [_("=number"),
                           _("Bottom paper margin"), _("Size in cm")],
            'css'       : [_("=css filename"),
                           _("CSS filename to use, html format only"), ""],
            }

        if noopt:
            return

        self.options_help['of'][2] = os.path.join(USER_HOME,
                                                  "whatever_name")

        if self.category == CATEGORY_TEXT:
            for plugin in self.__textdoc_plugins:
                self.options_help['off'][2].append(
                    plugin.get_extension() + "\t" + plugin.get_description())
        elif self.category == CATEGORY_DRAW:
            for plugin in self.__drawdoc_plugins:
                self.options_help['off'][2].append(
                    plugin.get_extension() + "\t" + plugin.get_description())
        elif self.category == CATEGORY_BOOK:
            for plugin in self.__bookdoc_plugins:
                self.options_help['off'][2].append(
                    plugin.get_extension() + "\t" + plugin.get_description())
        elif self.category == CATEGORY_GRAPHVIZ:
            for graph_format in graphdoc.FORMATS:
                self.options_help['off'][2].append(
                    graph_format["type"] + "\t" + graph_format["descr"])
        elif self.category == CATEGORY_TREE:
            for tree_format in treedoc.FORMATS:
                self.options_help['off'][2].append(
                    tree_format["type"] + "\t" + tree_format["descr"])
        else:
            self.options_help['off'][2] = "NA"

        self.options_help['papers'][2] = [
            paper.get_name() for paper in paper_sizes
            if paper.get_name() != 'Custom Size']

        self.options_help['papero'][2] = ["%d\tPortrait" % PAPER_PORTRAIT,
                                          "%d\tLandscape" % PAPER_LANDSCAPE]

        self.options_help['css'][2] = os.path.join(USER_HOME,
                                                   "whatever_name.css")

        if self.category in (CATEGORY_TEXT, CATEGORY_DRAW):
            default_style = StyleSheet()
            self.option_class.make_default_style(default_style)

            # Read all style sheets available for this item
            style_file = self.option_class.handler.get_stylesheet_savefile()
            self.style_list = StyleSheetList(style_file, default_style)

            self.options_help['style'][2] = self.style_list.get_style_names()
Пример #7
0
class CommandLineReport:
    """
    Provide a way to generate report from the command line.
    """

    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()
        if category == CATEGORY_TREE:
            # Need to include Genealogy Tree options
            self.__toptions = treedoc.TreeOptions()
            menu = self.option_class.menu
            self.__toptions.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()

    def init_standard_options(self, noopt):
        """
        Initialize the options that are hard-coded into the report system.
        """
        self.options_dict = {
            'of'        : self.option_class.handler.module_name,
            'off'       : self.option_class.handler.get_format_name(),
            'style'     :
                self.option_class.handler.get_default_stylesheet_name(),
            'papers'    : self.option_class.handler.get_paper_name(),
            'papero'    : self.option_class.handler.get_orientation(),
            'paperml'   : self.option_class.handler.get_margins()[0],
            'papermr'   : self.option_class.handler.get_margins()[1],
            'papermt'   : self.option_class.handler.get_margins()[2],
            'papermb'   : self.option_class.handler.get_margins()[3],
            'css'       : self.option_class.handler.get_css_filename(),
            }

        self.options_help = {
            'of'        : [_("=filename"),
                           _("Output file name. MANDATORY"), ""],
            'off'       : [_("=format"), _("Output file format."), []],
            'style'     : [_("=name"), _("Style name."), ""],
            'papers'    : [_("=name"), _("Paper size name."), ""],
            'papero'    : [_("=number"), _("Paper orientation number."), ""],
            'paperml'   : [_("=number"),
                           _("Left paper margin"), _("Size in cm")],
            'papermr'   : [_("=number"),
                           _("Right paper margin"), _("Size in cm")],
            'papermt'   : [_("=number"),
                           _("Top paper margin"), _("Size in cm")],
            'papermb'   : [_("=number"),
                           _("Bottom paper margin"), _("Size in cm")],
            'css'       : [_("=css filename"),
                           _("CSS filename to use, html format only"), ""],
            }

        if noopt:
            return

        self.options_help['of'][2] = os.path.join(USER_HOME,
                                                  "whatever_name")

        if self.category == CATEGORY_TEXT:
            for plugin in self.__textdoc_plugins:
                self.options_help['off'][2].append(
                    plugin.get_extension() + "\t" + plugin.get_description())
        elif self.category == CATEGORY_DRAW:
            for plugin in self.__drawdoc_plugins:
                self.options_help['off'][2].append(
                    plugin.get_extension() + "\t" + plugin.get_description())
        elif self.category == CATEGORY_BOOK:
            for plugin in self.__bookdoc_plugins:
                self.options_help['off'][2].append(
                    plugin.get_extension() + "\t" + plugin.get_description())
        elif self.category == CATEGORY_GRAPHVIZ:
            for graph_format in graphdoc.FORMATS:
                self.options_help['off'][2].append(
                    graph_format["type"] + "\t" + graph_format["descr"])
        elif self.category == CATEGORY_TREE:
            for tree_format in treedoc.FORMATS:
                self.options_help['off'][2].append(
                    tree_format["type"] + "\t" + tree_format["descr"])
        else:
            self.options_help['off'][2] = "NA"

        self.options_help['papers'][2] = [
            paper.get_name() for paper in paper_sizes
            if paper.get_name() != 'Custom Size']

        self.options_help['papero'][2] = ["%d\tPortrait" % PAPER_PORTRAIT,
                                          "%d\tLandscape" % PAPER_LANDSCAPE]

        self.options_help['css'][2] = os.path.join(USER_HOME,
                                                   "whatever_name.css")

        if self.category in (CATEGORY_TEXT, CATEGORY_DRAW):
            default_style = StyleSheet()
            self.option_class.make_default_style(default_style)

            # Read all style sheets available for this item
            style_file = self.option_class.handler.get_stylesheet_savefile()
            self.style_list = StyleSheetList(style_file, default_style)

            self.options_help['style'][2] = self.style_list.get_style_names()

    def init_report_options(self):
        """
        Initialize the options that are defined by each report.
        """

        if self.category == CATEGORY_BOOK: # a Book Report has no "menu"
            for key in self.option_class.options_dict:
                self.options_dict[key] = self.option_class.options_dict[key]
                self.options_help[
                    key] = self.option_class.options_help[key][:3]
            # a Book Report can't have HTML output so "css" is meaningless
            self.options_dict.pop('css')

        if not hasattr(self.option_class, "menu"):
            return
        menu = self.option_class.menu
        for name in menu.get_all_option_names():
            option = menu.get_option_by_name(name)
            self.options_dict[name] = option.get_value()

    def init_report_options_help(self):
        """
        Initialize help for the options that are defined by each report.
        (And also any docgen options, if defined by the docgen.)
        """
        if not hasattr(self.option_class, "menu"):
            return
        menu = self.option_class.menu
        for name in menu.get_all_option_names():
            option = menu.get_option_by_name(name)
            self.options_help[name] = ["", option.get_help()]

            if isinstance(option, PersonOption):
                id_list = []
                for person_handle in self.database.get_person_handles(True):
                    person = self.database.get_person_from_handle(person_handle)
                    id_list.append("%s\t%s"
                                   % (person.get_gramps_id(),
                                      name_displayer.display(person)))
                self.options_help[name].append(id_list)
            elif isinstance(option, FamilyOption):
                id_list = []
                for family in self.database.iter_families():
                    mname = ""
                    fname = ""
                    mhandle = family.get_mother_handle()
                    if mhandle:
                        mother = self.database.get_person_from_handle(mhandle)
                        if mother:
                            mname = name_displayer.display(mother)
                    fhandle = family.get_father_handle()
                    if fhandle:
                        father = self.database.get_person_from_handle(fhandle)
                        if father:
                            fname = name_displayer.display(father)
                    # translators: needed for French, Hebrew and Arabic
                    text = _("%(id)s:\t%(father)s, %(mother)s"
                            ) % {'id': family.get_gramps_id(),
                                 'father': fname, 'mother': mname}
                    id_list.append(text)
                self.options_help[name].append(id_list)
            elif isinstance(option, NoteOption):
                id_list = []
                for nhandle in self.database.get_note_handles():
                    note = self.database.get_note_from_handle(nhandle)
                    id_list.append(note.get_gramps_id())
                self.options_help[name].append(id_list)
            elif isinstance(option, MediaOption):
                id_list = []
                for mhandle in self.database.get_media_handles():
                    mobject = self.database.get_media_from_handle(mhandle)
                    id_list.append(mobject.get_gramps_id())
                self.options_help[name].append(id_list)
            elif isinstance(option, PersonListOption):
                self.options_help[name].append("")
            elif isinstance(option, NumberOption):
                self.options_help[name].append("A number")
            elif isinstance(option, BooleanOption):
                self.options_help[name].append(["False", "True"])
            elif isinstance(option, DestinationOption):
                self.options_help[name].append("A file system path")
            elif isinstance(option, StringOption):
                self.options_help[name].append("Any text")
            elif isinstance(option, TextOption):
                self.options_help[name].append(
                    "A list of text values. Each entry in the list "
                    "represents one line of text.")
            elif isinstance(option, EnumeratedListOption):
                ilist = []
                for (value, description) in option.get_items():
                    tabs = '\t'
                    try:
                        tabs = '\t\t' if len(value) < 10 else '\t'
                    except TypeError: #Value is a number, use just one tab.
                        pass
                    val = "%s%s%s" % (value, tabs, description)
                    ilist.append(val)
                self.options_help[name].append(ilist)
            elif isinstance(option, Option):
                self.options_help[name].append(option.get_help())
            else:
                print(_("Unknown option: %s") % option, file=sys.stderr)
                print(_("   Valid options are:") +
                      _(", ").join(list(self.options_dict.keys())), # Arabic OK
                      file=sys.stderr)
                print(_("   Use '%(donottranslate)s' to see description "
                        "and acceptable values"
                       ) % {'donottranslate' : "show=option"},
                      file=sys.stderr)

    def parse_options(self):
        """
        Load the options that the user has entered.
        """
        if not hasattr(self.option_class, "menu"):
            menu = None
        else:
            menu = self.option_class.menu
            menu_opt_names = menu.get_all_option_names()

        _format_str = self.options_str_dict.pop('off', None)
        if _format_str:
            self.options_dict['off'] = _format_str

        self.css_filename = None
        _chosen_format = None

        self.doc_option_class = None
        if self.category in [CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_BOOK]:
            if self.category == CATEGORY_TEXT:
                plugins = self.__textdoc_plugins
                self.css_filename = self.options_dict['css']
            elif self.category == CATEGORY_DRAW:
                plugins = self.__drawdoc_plugins
            elif self.category == CATEGORY_BOOK:
                plugins = self.__bookdoc_plugins
            for plugin in plugins:
                if plugin.get_extension() == self.options_dict['off']:
                    self.format = plugin.get_basedoc()
                    self.doc_option_class = plugin.get_doc_option_class()
            if self.format is None:
                # Pick the first one as the default.
                plugin = plugins[0]
                self.format = plugin.get_basedoc()
                self.doc_option_class = plugin.get_doc_option_class()
                _chosen_format = plugin.get_extension()
        elif self.category == CATEGORY_GRAPHVIZ:
            for graph_format in graphdoc.FORMATS:
                if graph_format['type'] == self.options_dict['off']:
                    if not self.format: # choose the first one, not the last
                        self.format = graph_format["class"]
            if self.format is None:
                # Pick the first one as the default.
                self.format = graphdoc.FORMATS[0]["class"]
                _chosen_format = graphdoc.FORMATS[0]["type"]
        elif self.category == CATEGORY_TREE:
            for tree_format in treedoc.FORMATS:
                if tree_format['type'] == self.options_dict['off']:
                    if not self.format: # choose the first one, not the last
                        self.format = tree_format["class"]
            if self.format is None:
                # Pick the first one as the default.
                self.format = tree_format.FORMATS[0]["class"]
                _chosen_format = tree_format.FORMATS[0]["type"]
        else:
            self.format = None
        if _chosen_format and _format_str:
            print(_("Ignoring '%(notranslate1)s=%(notranslate2)s' "
                    "and using '%(notranslate1)s=%(notranslate3)s'."
                   ) % {'notranslate1' : "off",
                        'notranslate2' : self.options_dict['off'],
                        'notranslate3' : _chosen_format},
                  file=sys.stderr)
            print(_("Use '%(notranslate)s' to see valid values."
                   ) % {'notranslate' : "show=off"}, file=sys.stderr)

        self.do_doc_options()

        for opt in self.options_str_dict:
            if opt in self.options_dict:
                self.options_dict[opt] = _convert_str_to_match_type(
                    self.options_str_dict[opt], self.options_dict[opt])

                self.option_class.handler.options_dict[
                    opt] = self.options_dict[opt]

                if menu and opt in menu_opt_names:
                    option = menu.get_option_by_name(opt)
                    option.set_value(self.options_dict[opt])

            else:
                print(_("Ignoring unknown option: %s") % opt, file=sys.stderr)
                print(_("   Valid options are:"),
                      _(", ").join(list(self.options_dict.keys())), # Arabic OK
                      file=sys.stderr)
                print(_("   Use '%(donottranslate)s' to see description "
                        "and acceptable values"
                       ) % {'donottranslate' : "show=option"},
                      file=sys.stderr)

        self.option_class.handler.output = self.options_dict['of']

        self.paper = paper_sizes[0] # make sure one exists
        for paper in paper_sizes:
            if paper.get_name() == self.options_dict['papers']:
                self.paper = paper
        self.option_class.handler.set_paper(self.paper)

        self.orien = self.options_dict['papero']

        self.marginl = self.options_dict['paperml']
        self.marginr = self.options_dict['papermr']
        self.margint = self.options_dict['papermt']
        self.marginb = self.options_dict['papermb']

        if self.category in (CATEGORY_TEXT, CATEGORY_DRAW):
            default_style = StyleSheet()
            self.option_class.make_default_style(default_style)

            # Read all style sheets available for this item
            style_file = self.option_class.handler.get_stylesheet_savefile()
            self.style_list = StyleSheetList(style_file, default_style)

            # Get the selected stylesheet
            style_name = self.option_class.handler.get_default_stylesheet_name()
            self.selected_style = self.style_list.get_style_sheet(style_name)

    def do_doc_options(self):
        """
        Process docgen options, if any (options for the backend, e.g. AsciiDoc)
        """
        self.doc_options = None
        if not self.doc_option_class:
            return # this docgen type has no options
        try:
            if issubclass(self.doc_option_class, object):
                self.doc_options = self.doc_option_class(self.raw_name,
                                                         self.database)
                doc_options_dict = self.doc_options.options_dict
        except TypeError:
            self.doc_options = self.doc_option_class
        self.doc_options.load_previous_values()
        docgen_menu = self.doc_options.menu
        report_menu = self.option_class.menu # "help" checks the option type
        for oname in docgen_menu.get_option_names(DOCGEN_OPTIONS):
            docgen_opt = docgen_menu.get_option(DOCGEN_OPTIONS, oname)
            if oname in self.options_str_dict and oname in doc_options_dict:
                doc_options_dict[oname] = _convert_str_to_match_type(
                    self.options_str_dict[oname], doc_options_dict[oname])
                self.options_str_dict.pop(oname)
            if oname in doc_options_dict:
                docgen_opt.set_value(doc_options_dict[oname])
            report_menu.add_option(DOCGEN_OPTIONS, oname, docgen_opt)
        for oname in doc_options_dict: # enable "help"
            self.options_dict[oname] = doc_options_dict[oname]
            self.options_help[oname] = self.doc_options.options_help[oname][:3]

    def show_options(self):
        """
        Print available options on the CLI.
        """
        if not self.show:
            return
        elif self.show == 'all':
            print(_("   Available options:"))
            for key in sorted(self.options_dict.keys()):
                if key in self.options_help:
                    opt = self.options_help[key]
                    # Make the output nicer to read, assume a tab has 8 spaces
                    tabs = '\t\t' if len(key) < 10 else '\t'
                    optmsg = "      %s%s%s (%s)" % (key, tabs, opt[1], opt[0])
                else:
                    optmsg = "      %s%s%s" % (key, tabs,
                                               _('(no help available)'))
                print(optmsg)
            print(_("   Use '%(donottranslate)s' to see description "
                    "and acceptable values"
                   ) % {'donottranslate' : "show=option"})
        elif self.show in self.options_help:
            opt = self.options_help[self.show]
            tabs = '\t\t' if len(self.show) < 10 else '\t'
            print(_("   Available values are:"))
            print('      %s%s%s (%s)' % (self.show, tabs, opt[1], opt[0]))
            vals = opt[2]
            if isinstance(vals, (list, tuple)):
                for val in vals:
                    print("      %s" % val)
            else:
                print("      %s" % opt[2])

        else:
            #there was a show option given, but the option is invalid
            print(_("option '%(optionname)s' not valid. "
                    "Use '%(donottranslate)s' to see all valid options."
                   ) % {'optionname'     : self.show,
                        'donottranslate' : "show=all"},
                  file=sys.stderr)