===Класс Options===
* В общем класс Options class should derive from должен наследовать от класса [https://www.gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.report._options.ReportOptions ReportOptions] class. Usually for a common report the Но обычно для большинства отчетов вместо него используется класс <tt>MenuReportOptions</tt> class should be derived from. <tt>MenuReportOptions</tt> will abstract most of the lower-level widget handling below, который абстрагирует большую часть низкоуровневого кода управления виджетами, описанную ниже.
====Использование класса ReportOptions====
ReportOptions.__init__(self,name,person_id)
</pre>
* It should set new options that are specific for this report, by overriding Класс может задать новые параметры для данного отчета переопределив метод the <tt>set_new_options()</tt> method which defines , в котором определяются словари <tt>options_dict</tt> and и <tt>options_help</tt> dictionaries:
<pre>
def set_new_options(self):
# Options specific for this reportНовые параметры данного отчета
self.options_dict = {
'my_first_optionмой_первый_параметр' : 0, 'my_second_optionмой_второй_параметр' : '',
}
self.options_help = {
'my_first_optionмой_первый_параметр' : ("=num","Number of somethingКоличество чего-то", [ "First valueПервое число", "Second valueВторое число" ],
True),
'my_second_optionмой_второй_параметр' : ("=str","Some necessary string for the reportКакая-то необходимая для отчета строка", "Whatever String You WishЛюбая строка по вашему желанию"),
}
</pre>
* It should also enable the Класс может также включить "semi-commonнеобязательные стандартные" options that are used in this reportпараметры, by overriding the которые используются в этом отчете, переопределив метод <tt>enable_options</tt> method which defines , который определяет словарь <tt>enable_dict</tt> dictionary. The semi-commons are the options which "Необязательными стандартными" называются те параметры, о которых ядро Gramps knows aboutзнает, but which are not necessarily present in all reportsно которые не обязательно присутствуют во всех отчетах:
<pre>
def enable_options(self):
# Semi-common options that should be enabled for this reportНеобязательные стандартные параметры, которые должны быть включены в этом отчете
self.enable_dict = {
'filter' : 0,
}
</pre>
All the common options are already taken care of by the core of О всех же стандартных параметрах уже позаботилось ядро Gramps. * For any new options set up in the options classДля любого нового параметра, заданного в классе параметров, необходимо определить виджет пользовательского интерфейса, there must be defined UI widgets to provide means of changing these options through the dialogsпосредством которого можно будет изменять этот параметр в диалоговом режиме. AlsoТак же надо определить метод <tt>parse_user_options</tt>, there must be defined methods to extract values of these options from the widgets and to set them into the class-variable dictionaryкоторый извлечет заданные в виджете значения параметров и сохранит их в переменную класса для значений параметров <tt>options_dict</tt>:
<pre>
def add_user_options(self,dialog):
def parse_user_options(self,dialog):
self.options_dict['my_second_optionмой_первый_параметр'] = unicode(self.the_string_entry.get_text()) self.options_dict['my_first_optionмой_второй_параметр'] = self.the_menu.get_history()</pre>* Finally, the default definitions for the user-adjustable paragraph styles must be defined here, to form a 'default' stylesheet:<pre>def make_default_style(self, default_style): f = docgen.FontStyle() f.set_size(10) f.set_type_face(docgen.FONT_SANS_SERIF) p = docgen.ParagraphStyle() p.set_font(f) p.set_description(_("The style used for the person's name.")) default_style.add_style("ABC-Name",p)
</pre>
====Использование класса MenuReportOptions====
The Класс [https://www.gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.report._options.MenuReportOptions MenuReportOptions] can be used in place of может быть использован вместо [https://www.gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.report._options.ReportOptions ReportOptions] to present the user with a standard interface for running the reportдля предоставления пользователю стандартного интерфейса для запуска отчета. Instead of parsing optionsВместо того, чтобы выполнять разбор введенного значения параметра, Вы создаете меню, используя один или несколько классов, you generate a menu using one or more of the classes available in доступных в [https://www.gramps-project.org/docs/gen/gen_plug.html#module-gramps.gen.plug.menu._menu Menu]. All these are initialized in the Все они инициализируются в методе [https://www.gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug._options.MenuOptions.add_menu_options add_menu_options()] function (which is a required function when you inherit from , который должен быть обязательно переопределен, когда наследование происходит от класса [https://www.gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.report._options.MenuReportOptions MenuReportOptions]). For exampleНапример:
<pre>
</pre>
In this example a В этом примере создается объект <tt>what_types</tt> класса [https://www.gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.menu._booleanlist.BooleanListOption BooleanListOption] object is created that presents the user with a group of check boxes, one is created for each call to который представляет пользователю группу флажков, каждый из которых создан вызовом метода [https://gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.menu._booleanlist.BooleanListOption.add_button what_types.add_button()]. Finally the object is added to the menu with В конце объект добавляется в меню вызовом метода [https://gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.menu._menu.Menu.add_option menu.add_option()]. The category name is used to generate tabs on the report dialogИмя категории используется для создания вкладок в диалоге отчета.
Then to access the selected values once the user runs the reportТеперь, you make a call the menu object from within the report's чтобы получить доступ к выбранным значениям после того как пользователь запустил отчет, Вы обращаетесь к объекту меню из конструктора отчета <tt>__init__</tt> function. For exampleНапример, to access the чтобы узнать "какие_типы" ("what_types" that are selected from the menu above you would add the following code) были выбраны в меню, Вы добавляете следующий код:
<pre>
</pre>
In the example, the option class is retrieved by the В примере объект параметра возвращается методом [https://gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.menu._menu.Menu.get_option_by_name options_class.menu.get_option_by_name()] function. The string must match the name you passed as the second argument to Передаваемая методу строка должна быть в точности такой же, как второй аргумент, переданный методу [https://gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.menu._menu.Menu.add_option menu.add_option()] when you created the menuпри создании меню. Then a list of the selected item titles is retrieved with После этого список названий выбранных флажков извлекается методом [https://gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.menu._booleanlist.BooleanListOption.get_selected menu_option.get_selected()] and stored as a class member и сохраняется в переменную объекта <tt>self.what_types</tt> для последующего использования. ====Определение настраиваемых пользователем стилей==== Если отчет использует настраиваемые пользователем стили абзацев, то значения по умолчанию для этих стилей должны быть определены здесь посредством переопределения метода [https://www.gramps-project.org/docs/gen/gen_plug.html#gramps.gen.plug.report._options.ReportOptions.make_default_style make_default_style()], для формирования таблицы стилей 'по умолчанию': <pre>def make_default_style(self, default_style): f = docgen.FontStyle() f.set_size(10) f.set_type_face(docgen.FONT_SANS_SERIF) p = docgen.ParagraphStyle() p.set_font(f) p.set_description(_("The style used for later usethe person's name.")) default_style.add_style("ABC-Name",p)</pre>
==Реализация==