Report-writing tutorial/he
This tutorial covers the basics of writing a simple report using the Gramps report infrastructure. It covers the process of handling options, building a document and creating the report.
The goals of this report are to create a database summary report. It will include the following information in the report:
- The number of people in the database
- The number of males and females
- The number of unique surnames
- The most common surname
From Gramps version 3.2, there is also A simple access database API available, with accompanying Quick Views, Gramplets and Addons. |
Contents
סקירה כללית
Before going into details, it is useful to note that the report should have two basic parts. This is explained on the Addons development page, that the source code goes into two different files:
- the Gramps Plugin Registration (*.gpr.py) file e.g.:
report.gpr.py
- and the main source code file (*.py) e.g.:
report.py
report.gpr.py
- Registration statement
- This initializes the report by a single call to the register() function. It is trivial, but without it your report will not become available to Gramps, even if it is otherwise perfectly written.
A report can potentially be generated as a standalone report, as a Gramps Book item, and as a command line report. The registration determines which modes are enabled for a given report. The report class does not have to know anything about the mode. The options class is there to provide options interface for all available modes.
report.py
- Report class
- This is the code that takes data from the Gramps database and organizes it into the document structure. This structure can later be printed, viewed, or written into a file in a variety of formats. This class uses the docgen interface to abstract away the output format details.
- Options class
- This is the code that provides means to obtain options necessary for the report using a variety of available mechanisms.
Document interface
The Report Generation article provides an overview of the 'docgen' interfaces that are available for outputting documents.
The Report API article provides more details about the interfaces.
The developer docgen api documentation provides a detailed specification of the interfaces.
Gramps attempts to abstract the output document format away from the report. By coding to the docgen class, the report can generate its output in the format desired by the end user. The document passed to the report (self.doc) could represent an HTML, OpenDocument, PDF or any of the other formats supported by the user. The report does not have to concern itself with the output format details, since all details are handled by the document object.
A document is composed of paragraphs, tables, and graphics objects. Tables and graphics objects will not be covered in this tutorial.
The report defines a set of paragraph and font styles, along with their default implementation. The user can override the definition of each style, allowing the user to customize the report. Each paragraph style must be named uniquely, to prevent collisions when printed in a book format. It is recommended to prefix each paragraph style with a three letter code unique to the report.
Paragraph and font styles are defined in the make_default_style() function of the options class. The paragraphs are grouped into a StyleSheet, which the make_default_style() function defines. For the example report (DbSummary), the paragraph styles are defined as below:
This article's content is incomplete or a placeholder stub. |
compare to gramps\plugins\textreport\summary.py
starting at line 297
def make_default_style(self, default_style): # Define the title paragraph, named 'DBS-Title', which uses a # 18 point, bold Sans Serif font with a paragraph that is centered font = docgen.FontStyle() font.set_size(18) font.set_type_face(docgen.FONT_SANS_SERIF) font.set_bold(True) para = docgen.ParagraphStyle() para.set_header_level(1) para.set_alignment(docgen.PARA_ALIGN_CENTER) para.set_font(font) para.set_description(_('The style used for the title of the page.')) default_style.add_style('DBS-Title',para) # Define the normal paragraph, named 'DBS-Normal', which uses a # 12 point, Serif font. font = docgen.FontStyle() font.set_size(12) font.set_type_face(docgen.FONT_SERIF) para = docgen.ParagraphStyle() para.set_font(font) para.set_description(_('The style used for normal text')) default_style.add_style('DBS-Normal',para)
קביעת המחלקות
מחלקת דוח
The user's report class should inherit from the Report class contained within the Report module. The constructor should take three arguments (besides class instance itself, usually denoted by 'self' name):
- Gramps database instance
- options class instance
- user class instance
The first is the database to work with. The second is the instance of the options class defined in the same report, see next section. The third is an instance of the User class, used for interaction with the user. Here's an example of a report class definition:
from ReportBase import Report, ReportUtils, ReportOptions class ReportClassName(Report): def __init__(self, database, options_class, user): Report.__init__(self, database, options_class, user)
The Report class's constructor will initialize several variables for the user based off the passed values. They are:
- self.doc
- The opened document instance ready for output. This is of the type docgen, and is not a normal file object.
- self.database
- The GrampsDbBase database object.
- self.options_class
- The ReportOptions class passed to the report.
You'll probably need a start-person for which to write the report. This person should be obtained from the options_class object through the PersonOption class which will default to the active person in the database. Anything else the report class needs in order to produce the report should be obtained from the options_class object. For example, you may need to include the additional code in the report class constructor to obtain any options you defined for the report.
Report class must provide a write_report() method. This method should dump the report's contents into the already opened document instance.
def write_report(self): self.doc.start_paragraph("ABC-Title") self.doc.write_text(_("Some text")) self.doc.end_paragraph()
The rest of the report class is pretty much up to the report writer. Depending on the goals and the scope of the report, there can be any amount of code involved. When the user generates the report in any mode, the class constructor will be run, and then the write_report() method will be called. So if you wrote that beautiful method listing something really important, make sure it is eventually called from within the write_report(). Otherwise nobody will see it unless looking at the code.
Options class
- Options class should derive from ReportOptions class. Usually for a common report the MenuReportOptions class should be derived from. MenuReportOptions will abstract most of the lower-level widget handling below.
Using ReportOptions
class OptionsClassName(ReportOptions): def __init__(self,name,person_id=None): ReportOptions.__init__(self,name,person_id)
- It should set new options that are specific for this report, by overriding the set_new_options() method which defines options_dict and options_help dictionaries:
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"), }
- It should also enable the "semi-common" options that are used in this report, by overriding the enable_options method which defines enable_dict dictionary. The semi-commons are the options which Gramps knows about, but which are not necessarily present in all reports:
def enable_options(self): # Semi-common options that should be enabled for this report self.enable_dict = { 'filter' : 0, }
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, there must be defined methods to extract values of these options from the widgets and to set them into the class-variable dictionary:
def add_user_options(self,dialog): option_menu = gtk.OptionMenu() self.the_menu = gtk.Menu() for item_index in range(10): item = _("Item numer %d") % item_index menuitem = gtk.MenuItem(item) menuitem.show() self.the_menu.append(menuitem) option_menu.set_menu(self.the_menu) option_menu.set_history(self.options_dict['my_first_option']) dialog.add_option(_('My first option'),option_menu) self.the_string_entry = gtk.Entry() if self.options_dict['my_second_option']: self.the_string_entry.set_text(self.options_dict['my_second_option']) else: self.the_string_entry.set_text(_("Empty string")) self.the_string_entry.show() dialog.add_option(_('My second option'),self.the_string_entry) 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()
- Finally, the default definitions for the user-adjustable paragraph styles must be defined here, to form a 'default' stylesheet:
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)
Using MenuReportOptions
The MenuReportOptions can be used in place of 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 gen.plug.menu. All these are initialzed in the add_menu_options function (which is a required function when you inherit from MenuReportOptions). For example:
def add_menu_options(self, menu): """ Add options to the menu for this report. """ category_name = _("Report Options") what_types = BooleanListOption(_('Select From:')) what_types.add_button(_('People'), True) what_types.add_button(_('Families'), False) what_types.add_button(_('Places'), False) what_types.add_button(_('Events'), False) menu.add_option(category_name, "what_types", what_types)
In this example a BooleanListOption object is created that presents the user with a group of check boxes, one is created for each call to add_button. Finally the object is added to the menu with 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 __init__ function. For example, to access the "what_types" that are selected from the menu above you would add the following code:
class ExampleReport(Report): def __init__(self, database, options_class): Report.__init__(self, database, options_class) menu_option = options_class.menu.get_option_by_name('what_types') self.what_types = menu_option.get_selected()
In the example, the option class is retrieved by the get_option_by_name() function. The string must match the name you passed as the second argument to menu.add_option() when you created the menu. Then a list of the selected item titles is retrieved with get_selected() and stored as a class member for later use.
יישום
קביעת מחלקת אפשרויות לדוח
In this example, no special options are required. This makes the options class very simple. All that is necessary is to define the default styles.
class DbSummaryOptions(ReportOptions): def __init__(self, name, database): ReportOptions.__init__(self, name, database) def make_default_style(self, default_style): # Define the title paragraph, named 'DBS-Title', which uses a # 18 point, bold Sans Serif font with a paragraph that is centered font = docgen.FontStyle() font.set_size(18) font.set_type_face(docgen.FONT_SANS_SERIF) font.set_bold(True) para = docgen.ParagraphStyle() para.set_header_level(1) para.set_alignment(docgen.PARA_ALIGN_CENTER) para.set_font(font) para.set_description(_('The style used for the title of the page.')) default_style.add_style('DBS-Title',para) # Define the normal paragraph, named 'DBS-Normal', which uses a # 12 point, Serif font. font = docgen.FontStyle() font.set_size(12) font.set_type_face(docgen.FONT_SERIF) para = docgen.ParagraphStyle()-> para.set_font(font) para.set_description(_('The style used for normal text')) default_style.add_style('DBS-Normal',para)
קביעת מחלקות הדוח
The actual implemention of the DbSummary report is rather simple. No additional work needs to be done to initialize the class, so the parent __init__ routine is called.
All the work is done in the write_report() function. This function uses a GrampsCursor to iterate through the map of Person objects and gathers some simple statistics.
The only thing of any complication is the determination of the most common surname. A python dictionary is used to store the number of times each surname is used. Each time a surname is encountered, the value in the dictionary is incremented. The results are then loaded into a list and sorted, allowing us to find the most common name by looking at the last entry in the list.
class DbSummaryReport(Report): def __init__(self, database, options_class): Report.__init__(self, database, options_class) def write_report(self): cursor = self.database.get_person_cursor() data = cursor.first() males = 0 females = 0 total = 0 surname_map = {} while data: person = RelLib.Person() person.unserialize(data[1]) if person.get_gender() == RelLib.Person.MALE: males += 1 if person.get_gender() == RelLib.Person.FEMALE: females += 1 total += 1 surname = person.get_primary_name().get_surname() if surname_map.has_key(surname): surname_map[surname] += 1 else: surname_map[surname] = 1 data = cursor.next() cursor.close() slist = [] for key in surname_map.keys(): slist.append((surname_map[key],key)) slist.sort() self.doc.start_paragraph("DBS-Title") self.doc.write_text(_("Database Summary")) self.doc.end_paragraph() self.doc.start_paragraph('DBS-Normal') self.doc.write_text(_('Number of males : %d') % males) self.doc.end_paragraph() self.doc.start_paragraph('DBS-Normal') self.doc.write_text(_('Number of females : %d') % females) self.doc.end_paragraph() self.doc.start_paragraph('DBS-Normal') self.doc.write_text(_('Total people : %d') % total) self.doc.end_paragraph() self.doc.start_paragraph('DBS-Normal') self.doc.write_text(_('Number of unique surnames : %d') % len(slist)) self.doc.end_paragraph() self.doc.start_paragraph('DBS-Normal') self.doc.write_text(_('Most common surname : %s') % (slist[-1][1])) self.doc.end_paragraph()
רישום הדוח
- Registration is set into a name.gpr.py file
- Registration should define internal name of the report (preferably, single string with non-special ascii characters, usable for report identification from the command line and in the options storage, as well as for forming sane filename for storing its own styles). It should also define the report's...
- category (text/graphics/code)
- translated name (the one to display in menus)
- modes that should be enabled for the report (standalone, book item, command line)
- If the report requires an active person to run, then
require_active
should be set toTrue
. - Finally, both report class and options class should be passed to registration.
Here's the example registration statement:
register(REPORT, id = 'an unique id', name = _("Name of the plugin"), description = _("Produces a ..."), version = '1.0', gramps_target_version = '5.1', status = STABLE, fname = 'filename.py', authors = ["John Doe"], authors_email = ["jdoe@example.com"], category = CATEGORY_TEXT, require_active = False, reportclass = 'DbSummaryReport', optionclass = 'DbSummaryOptions', report_modes = [REPORT_MODE_GUI, REPORT_MODE_CLI], )
There are arguments for the report class and options class. The report_modes argument is set to a list of zero or more of the following modes:
- REPORT_MODE_GUI (available for Gramps running in a window, graphical user interface)
- REPORT_MODE_BKI (available as a book report item)
- REPORT_MODE_CLI (available for the command line interface)
The list should only include those options which are valid for this report.
The rest of the options should be self-explanatory.
דוח ספר
To turn a report into one that will work as a book report, you may need to add the following:
from gen.plug.docgen import IndexMark # Write the title line. # Set in INDEX marker so that this section will be identified # as a major category if this is included in a Book report. title = self._('My Report') mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.start_paragraph('MYREPORT-section') self.doc.write_text(title, mark) ...
See an existing book report for more details.
Manually installing your report
Install in the plugins directory of your Gramps user directory.
Example output
Start Gramps and your tutorial report will be available from the reports menu as ....
Run the report and this is what the output looks like ....
לקריאה נוספת
- Report API
- Report Generation (describing output format options)
- Gramps Data Model
- Discourse forum discussion: Sample Report for new developers