Пример #1
0
class RecordsReport(Report):
    """ Records Report """
    def __init__(self, database, options, user):
        """
        This report needs the following parameters (class variables)
        that come in the options class.

        incl_private    - Whether to include private data
        living_people - How to handle living people
        years_past_death - Consider as living this many years after death
        """

        Report.__init__(self, database, options, user)
        menu = options.menu

        lang = options.menu.get_option_by_name('trans').get_value()
        self._locale = self.set_locale(lang)

        stdoptions.run_private_data_option(self, menu)
        living_opt = stdoptions.run_living_people_option(
            self, menu, self._locale)
        self.database = CacheProxyDb(self.database)

        self._lv = menu.get_option_by_name('living_people').get_value()
        for (value, description) in living_opt.get_items(xml_items=True):
            if value == self._lv:
                living_desc = self._(description)
                break
        self.living_desc = self._("(Living people: %(option_name)s)") % {
            'option_name': living_desc
        }

        filter_option = menu.get_option_by_name('filter')
        self.filter = filter_option.get_filter()

        self.top_size = menu.get_option_by_name('top_size').get_value()
        self.callname = menu.get_option_by_name('callname').get_value()

        self.footer = menu.get_option_by_name('footer').get_value()

        self.include = {}
        for (text, varname, default) in RECORDS:
            self.include[varname] = menu.get_option_by_name(
                varname).get_value()

        self._nf = stdoptions.run_name_format_option(self, menu)

    def write_report(self):
        """
        Build the actual report.
        """

        records = find_records(self.database,
                               self.filter,
                               self.top_size,
                               self.callname,
                               trans_text=self._,
                               name_format=self._nf,
                               living_mode=self._lv)

        self.doc.start_paragraph('REC-Title')
        title = self._("Records")
        mark = IndexMark(title, INDEX_TYPE_TOC, 1)
        self.doc.write_text(title, mark)
        self.doc.end_paragraph()

        self.doc.start_paragraph('REC-Subtitle')
        filter_name = self.filter.get_name(self._locale)
        self.doc.write_text("(%s)" % filter_name)
        self.doc.end_paragraph()
        if self._lv != LivingProxyDb.MODE_INCLUDE_ALL:
            self.doc.start_paragraph('REC-Subtitle')
            self.doc.write_text(self.living_desc)
            self.doc.end_paragraph()

        for (text, varname, top) in records:
            if not self.include[varname]:
                continue

            self.doc.start_paragraph('REC-Heading')
            self.doc.write_text(self._(text))
            self.doc.end_paragraph()

            last_value = None
            rank = 0
            for (number, (sort, value, name, handletype,
                          handle)) in enumerate(top):
                mark = None
                if handletype == 'Person':
                    person = self.database.get_person_from_handle(handle)
                    mark = utils.get_person_mark(self.database, person)
                elif handletype == 'Family':
                    family = self.database.get_family_from_handle(handle)
                    # librecords.py checks that the family has both
                    # a father and a mother and also that each one is
                    # in the filter if any filter was used, so we don't
                    # have to do any similar checking here, it's been done
                    f_handle = family.get_father_handle()
                    dad = self.database.get_person_from_handle(f_handle)
                    f_mark = utils.get_person_mark(self.database, dad)
                    m_handle = family.get_mother_handle()
                    mom = self.database.get_person_from_handle(m_handle)
                    m_mark = utils.get_person_mark(self.database, mom)
                else:
                    raise ReportError(
                        _("Option '%(opt_name)s' is present "
                          "in %(file)s\n  but is not known to "
                          "the module.  Ignoring...") % {
                              'opt_name': handletype,
                              'file': 'libnarrate.py'
                          })
                    # since the error is very unlikely I reused the string
                if value != last_value:
                    last_value = value
                    rank = number
                self.doc.start_paragraph('REC-Normal')
                self.doc.write_text(
                    self._("%(number)s. ") % {'number': rank + 1})
                self.doc.write_markup(str(name), name.get_tags(), mark)
                if handletype == 'Family':
                    self.doc.write_text('', f_mark)
                    self.doc.write_text('', m_mark)
                if isinstance(value, Span):
                    tvalue = value.get_repr(dlocale=self._locale)
                else:
                    tvalue = value
                self.doc.write_text(" (%s)" % tvalue)
                self.doc.end_paragraph()

        self.doc.start_paragraph('REC-Footer')
        self.doc.write_text(self.footer)
        self.doc.end_paragraph()
Пример #2
0
class EndOfLineReport(Report):
    """ EndOfLine Report """
    def __init__(self, database, options, user):
        """
        Create the EndOfLineReport object that produces the report.

        The arguments are:

        database        - the GRAMPS database instance
        options         - instance of the Options class for this report
        user            - a gen.user.User() instance

        This report needs the following parameters (class variables)
        that come in the options class.
        name_format   - Preferred format to display names
        incl_private  - Whether to include private data
        living_people - How to handle living people
        years_past_death - Consider as living this many years after death
        """
        Report.__init__(self, database, options, user)

        menu = options.menu

        lang = menu.get_option_by_name('trans').get_value()
        rlocale = self.set_locale(lang)

        stdoptions.run_private_data_option(self, menu)
        stdoptions.run_living_people_option(self, menu, rlocale)
        self.database = CacheProxyDb(self.database)

        pid = menu.get_option_by_name('pid').get_value()
        self.center_person = self.database.get_person_from_gid(pid)
        if self.center_person is None:
            raise ReportError(_("Person %s is not in the Database") % pid)

        stdoptions.run_name_format_option(self, menu)

        # eol_map is a map whose:
        #   keys are the generations of the people
        #   values are a map whose:
        #      keys are person handles
        #      values are an array whose:
        #         elements are an array of ancestor person handles that link
        #         the eol person handle to the person or interest
        # eol_map[generation][person_handle][pedigree_idx][ancestor_handle_idx]
        #
        # There is an array of pedigrees because one person could show up twice
        # in one generation (descendants marrying). Most people only have one
        # pedigree.
        #
        # eol_map is populated by get_eol() which calls itself recursively.
        self.eol_map = {}
        self.get_eol(self.center_person, 1, [])

    def get_eol(self, person, gen, pedigree):
        """
        Recursively find the end of the line for each person
        """
        person_handle = person.get_handle()
        new_pedigree = list(pedigree) + [person_handle]
        person_is_eol = False
        families = person.get_parent_family_handle_list()

        if person_handle in pedigree:
            # This is a severe error!
            # It indicates a loop in ancestry: A -> B -> A
            person_is_eol = True
        elif not families:
            person_is_eol = True
        else:
            for family_handle in families:
                family = self.database.get_family_from_handle(family_handle)
                father_handle = family.get_father_handle()
                mother_handle = family.get_mother_handle()
                if father_handle:
                    father = self.database.get_person_from_handle(
                        father_handle)
                    self.get_eol(father, gen + 1, new_pedigree)
                if mother_handle:
                    mother = self.database.get_person_from_handle(
                        mother_handle)
                    self.get_eol(mother, gen + 1, new_pedigree)

                if not father_handle or not mother_handle:
                    person_is_eol = True

        if person_is_eol:
            # This person is the end of a line
            if gen not in self.eol_map:
                self.eol_map[gen] = {}
            if person_handle not in self.eol_map[gen]:
                self.eol_map[gen][person_handle] = []
            self.eol_map[gen][person_handle].append(new_pedigree)

    def write_report(self):
        """
        The routine that actually creates the report.
        At this point, the document is opened and ready for writing.
        """
        pname = self._name_display.display(self.center_person)

        self.doc.start_paragraph("EOL-Title")
        # feature request 2356: avoid genitive form
        title = self._("End of Line Report for %s") % pname
        mark = IndexMark(title, INDEX_TYPE_TOC, 1)
        self.doc.write_text(title, mark)
        self.doc.end_paragraph()

        self.doc.start_paragraph("EOL-Subtitle")
        # feature request 2356: avoid genitive form
        title = self._(
            "All the ancestors of %s who are missing a parent") % pname
        self.doc.write_text(title)
        self.doc.end_paragraph()

        self.doc.start_table('EolTable', 'EOL-Table')
        for generation, handles in self.eol_map.items():
            self.write_generation_row(generation)
            for person_handle, pedigrees in handles.items():
                self.write_person_row(person_handle)
                list(map(self.write_pedigree_row, pedigrees))
        self.doc.end_table()

    def write_generation_row(self, generation):
        """
        Write out a row in the table showing the generation.
        """
        self.doc.start_row()
        self.doc.start_cell('EOL_GenerationCell', 2)
        self.doc.start_paragraph('EOL-Generation')
        self.doc.write_text(self._("Generation %d") % generation)
        self.doc.end_paragraph()
        self.doc.end_cell()
        self.doc.end_row()

    def write_person_row(self, person_handle):
        """
        Write a row in the table with information about the given person.
        """
        person = self.database.get_person_from_handle(person_handle)

        name = self._name_display.display(person)
        mark = utils.get_person_mark(self.database, person)
        birth_date = ""
        birth_ref = person.get_birth_ref()
        if birth_ref:
            event = self.database.get_event_from_handle(birth_ref.ref)
            birth_date = self._get_date(event.get_date_object())
        death_date = ""
        death_ref = person.get_death_ref()
        if death_ref:
            event = self.database.get_event_from_handle(death_ref.ref)
            death_date = self._get_date(event.get_date_object())
        dates = ''
        if birth_date or death_date:
            dates = self._(" (%(birth_date)s - %(death_date)s)") % {
                'birth_date': birth_date,
                'death_date': death_date
            }

        self.doc.start_row()
        self.doc.start_cell('EOL-TableCell', 2)
        self.doc.start_paragraph('EOL-Normal')
        self.doc.write_text(name, mark)
        self.doc.write_text(dates)
        self.doc.end_paragraph()
        self.doc.end_cell()
        self.doc.end_row()

    def write_pedigree_row(self, pedigree):
        """
        Write a row in the table with with the person's family line.

        pedigree is an array containing the names of the people in the pedigree
        """
        names = []
        for person_handle in pedigree:
            person = self.database.get_person_from_handle(person_handle)
            names.append(self._name_display.display(person))
        text = " -- ".join(names)
        self.doc.start_row()
        self.doc.start_cell('EOL-TableCell')
        self.doc.end_cell()
        self.doc.start_cell('EOL-TableCell')
        self.doc.start_paragraph('EOL-Pedigree')
        self.doc.write_text(text)
        self.doc.end_paragraph()
        self.doc.end_cell()
        self.doc.end_row()
Пример #3
0
class KinshipReport(Report):
    """ Kinship Report """

    def __init__(self, database, options, user):
        """
        Create the KinshipReport object that produces the report.

        The arguments are:

        database        - the GRAMPS database instance
        options         - instance of the Options class for this report
        user            - a gen.user.User() instance

        This report needs the following parameters (class variables)
        that come in the options class.

        maxdescend    - Maximum generations of descendants to include.
        maxascend     - Maximum generations of ancestors to include.
        incspouses    - Whether to include spouses.
        inccousins    - Whether to include cousins.
        incaunts      - Whether to include aunts/uncles/nephews/nieces.
        pid           - The GID of the center person for the report.
        name_format   - Preferred format to display names
        incl_private  - Whether to include private data
        living_people - How to handle living people
        years_past_death - Consider as living this many years after death
        """
        Report.__init__(self, database, options, user)
        menu = options.menu

        lang = menu.get_option_by_name('trans').get_value()
        rlocale = self.set_locale(lang)

        stdoptions.run_private_data_option(self, menu)
        stdoptions.run_living_people_option(self, menu, rlocale)
        self.database = CacheProxyDb(self.database)
        self.__db = self.database

        self.max_descend = menu.get_option_by_name('maxdescend').get_value()
        self.max_ascend = menu.get_option_by_name('maxascend').get_value()
        self.inc_spouses = menu.get_option_by_name('incspouses').get_value()
        self.inc_cousins = menu.get_option_by_name('inccousins').get_value()
        self.inc_aunts = menu.get_option_by_name('incaunts').get_value()
        pid = menu.get_option_by_name('pid').get_value()
        self.person = self.database.get_person_from_gid(pid)
        if self.person is None:
            raise ReportError(_("Person %s is not in the Database") % pid)

        stdoptions.run_name_format_option(self, menu)

        self.rel_calc = get_relationship_calculator(reinit=True,
                                                    clocale=rlocale)

        self.kinship_map = {}
        self.spouse_map = {}

    def write_report(self):
        """
        The routine the actually creates the report. At this point, the document
        is opened and ready for writing.
        """
        pname = self._name_display.display(self.person)

        self.doc.start_paragraph("KIN-Title")
        # feature request 2356: avoid genitive form
        title = self._("Kinship Report for %s") % pname
        mark = IndexMark(title, INDEX_TYPE_TOC, 1)
        self.doc.write_text(title, mark)
        self.doc.end_paragraph()

        if self.inc_spouses:
            spouse_handles = self.get_spouse_handles(self.person.get_handle())
            if spouse_handles:
                self.write_people(self._("Spouses"), spouse_handles)

        # Collect all descendants of the person
        self.traverse_down(self.person.get_handle(), 0, 1)

        # Collect all ancestors/aunts/uncles/nephews/cousins of the person
        self.traverse_up(self.person.get_handle(), 1, 0)

        # Write Kin
        for Ga, Gbs in self.kinship_map.items():
            for Gb in Gbs:
                # To understand these calculations, see:
                # http://en.wikipedia.org/wiki/Cousin#Mathematical_definitions
                _x_ = min(Ga, Gb)
                _y_ = abs(Ga - Gb)
                # Skip unrequested people
                if _x_ == 1 and _y_ > 0 and not self.inc_aunts:
                    continue
                elif _x_ > 1 and not self.inc_cousins:
                    continue

                get_rel_str = self.rel_calc.get_plural_relationship_string

                title = get_rel_str(Ga, Gb, in_law_b=False)
                self.write_people(self._(title), self.kinship_map[Ga][Gb])

                if (self.inc_spouses and
                        Ga in self.spouse_map and
                        Gb in self.spouse_map[Ga]):
                    title = get_rel_str(Ga, Gb, in_law_b=True)
                    self.write_people(self._(title), self.spouse_map[Ga][Gb])

    def traverse_down(self, person_handle, Ga, Gb, skip_handle=None):
        """
        Populate a map of arrays containing person handles for the descendants
        of the passed person. This function calls itself recursively until it
        reaches max_descend.

        Parameters:
        person_handle: the handle of the person to go to next
        Ga: The number of generations from the main person to the common
           ancestor. This should be incremented when going up generations, and
           left alone when going down generations.
        Gb: The number of generations from this person (person_handle) to the
           common ancestor. This should be incremented when going down
           generations and set back to zero when going up generations.
        skip_handle: an optional handle to skip when going down. This is useful
           to skip the descendant that brought you this generation in the first
           place.
        """
        for child_handle in self.get_children_handles(person_handle):
            if child_handle != skip_handle:
                self.add_kin(child_handle, Ga, Gb)

                if self.inc_spouses:
                    for spouse_handle in self.get_spouse_handles(child_handle):
                        self.add_spouse(spouse_handle, Ga, Gb)

                if Gb < self.max_descend:
                    self.traverse_down(child_handle, Ga, Gb+1)

    def traverse_up(self, person_handle, Ga, Gb):
        """
        Populate a map of arrays containing person handles for the ancestors
        of the passed person. This function calls itself recursively until it
        reaches max_ascend.

        Parameters:
        person_handle: the handle of the person to go to next
        Ga: The number of generations from the main person to the common
           ancestor. This should be incremented when going up generations, and
           left alone when going down generations.
        Gb: The number of generations from this person (person_handle) to the
           common ancestor. This should be incremented when going down
           generations and set back to zero when going up generations.
        """
        parent_handles = self.get_parent_handles(person_handle)
        for parent_handle in parent_handles:
            self.add_kin(parent_handle, Ga, Gb)
            self.traverse_down(parent_handle, Ga, Gb+1, person_handle)
            if Ga < self.max_ascend:
                self.traverse_up(parent_handle, Ga+1, 0)

    def add_kin(self, person_handle, Ga, Gb):
        """
        Add a person handle to the kin map.
        """
        if Ga not in self.kinship_map:
            self.kinship_map[Ga] = {}
        if Gb not in self.kinship_map[Ga]:
            self.kinship_map[Ga][Gb] = []
        if person_handle not in self.kinship_map[Ga][Gb]:
            self.kinship_map[Ga][Gb].append(person_handle)

    def add_spouse(self, spouse_handle, Ga, Gb):
        """
        Add a person handle to the spouse map.
        """
        if Ga not in self.spouse_map:
            self.spouse_map[Ga] = {}
        if Gb not in self.spouse_map[Ga]:
            self.spouse_map[Ga][Gb] = []
        if spouse_handle not in self.spouse_map[Ga][Gb]:
            self.spouse_map[Ga][Gb].append(spouse_handle)

    def get_parent_handles(self, person_handle):
        """
        Return an array of handles for all the parents of the
        given person handle.
        """
        parent_handles = []
        person = self.__db.get_person_from_handle(person_handle)
        family_handle = person.get_main_parents_family_handle()
        if family_handle:
            family = self.__db.get_family_from_handle(family_handle)
            father_handle = family.get_father_handle()
            if father_handle:
                parent_handles.append(father_handle)
            mother_handle = family.get_mother_handle()
            if mother_handle:
                parent_handles.append(mother_handle)
        return parent_handles

    def get_spouse_handles(self, person_handle):
        """
        Return an array of handles for all the spouses of the
        given person handle.
        """
        spouses = []
        person = self.__db.get_person_from_handle(person_handle)
        for family_handle in person.get_family_handle_list():
            family = self.__db.get_family_from_handle(family_handle)
            father_handle = family.get_father_handle()
            mother_handle = family.get_mother_handle()
            spouse_handle = None
            if mother_handle and father_handle == person_handle:
                spouse_handle = mother_handle
            elif father_handle and mother_handle == person_handle:
                spouse_handle = father_handle

            if spouse_handle and spouse_handle not in spouses:
                spouses.append(spouse_handle)
        return spouses

    def get_children_handles(self, person_handle):
        """
        Return an array of handles for all the children of the
        given person handle.
        """
        children = []
        person = self.__db.get_person_from_handle(person_handle)
        for family_handle in person.get_family_handle_list():
            family = self.__db.get_family_from_handle(family_handle)
            for child_ref in family.get_child_ref_list():
                children.append(child_ref.get_reference_handle())
        return children

    def write_people(self, title, people_handles):
        """
        Write information about a group of people - including the title.
        """
        cap_title = title[0].upper() + title[1:]
        subtitle = "%s (%d)" % (cap_title, len(people_handles))
        self.doc.start_paragraph("KIN-Subtitle")
        mark = IndexMark(cap_title, INDEX_TYPE_TOC, 2)
        self.doc.write_text(subtitle, mark)
        self.doc.end_paragraph()
        list(map(self.write_person, people_handles))

    def write_person(self, person_handle):
        """
        Write information about the given person.
        """
        person = self.database.get_person_from_handle(person_handle)

        name = self._name_display.display(person)
        mark = utils.get_person_mark(self.database, person)
        birth_date = ""
        birth = get_birth_or_fallback(self.database, person)
        if birth:
            birth_date = self._get_date(birth.get_date_object())

        death_date = ""
        death = get_death_or_fallback(self.database, person)
        if death:
            death_date = self._get_date(death.get_date_object())
        dates = ''
        if birth_date or death_date:
            dates = self._(" (%(birth_date)s - %(death_date)s)"
                          ) % {'birth_date' : birth_date,
                               'death_date' : death_date}

        self.doc.start_paragraph('KIN-Normal')
        self.doc.write_text(name, mark)
        self.doc.write_text(dates)
        self.doc.end_paragraph()
Пример #4
0
class TagReport(Report):
    """ Tag Report """
    def __init__(self, database, options, user):
        """
        Create the TagReport object that produces the report.

        The arguments are:

        database        - the GRAMPS database instance
        options         - instance of the Options class for this report
        user            - a gen.user.User() instance

        This report needs the following parameters (class variables)
        that come in the options class.

        tag             - The tag each object must match to be included.
        name_format     - Preferred format to display names of people
        incl_private    - Whether to include private data
        living_people - How to handle living people
        years_past_death - Consider as living this many years after death
        """
        Report.__init__(self, database, options, user)
        menu = options.menu

        lang = menu.get_option_by_name('trans').get_value()
        rlocale = self.set_locale(lang)

        stdoptions.run_private_data_option(self, menu)
        living_opt = stdoptions.run_living_people_option(self, menu, rlocale)
        self.database = CacheProxyDb(self.database)

        self._lv = menu.get_option_by_name('living_people').get_value()
        for (value, description) in living_opt.get_items(xml_items=True):
            if value == self._lv:
                living_desc = self._(description)
                break
        self.living_desc = self._("(Living people: %(option_name)s)") % {
            'option_name': living_desc
        }

        self.tag = menu.get_option_by_name('tag').get_value()
        if not self.tag:
            raise ReportError(
                _('Tag Report'),
                _('You must first create a tag before running this report.'))

        stdoptions.run_name_format_option(self, menu)

    def write_report(self):
        self.doc.start_paragraph("TR-Title")
        # feature request 2356: avoid genitive form
        title = self._("Tag Report for %s Items") % self.tag
        mark = IndexMark(title, INDEX_TYPE_TOC, 1)
        self.doc.write_text(title, mark)
        self.doc.end_paragraph()
        if self._lv != LivingProxyDb.MODE_INCLUDE_ALL:
            self.doc.start_paragraph("TR-ReportSubtitle")
            self.doc.write_text(self.living_desc)
            self.doc.end_paragraph()

        self.write_people()
        self.write_families()
        self.write_events()
        self.write_places()
        self.write_notes()
        self.write_media()
        self.write_repositories()
        self.write_sources()
        self.write_citations()

    def write_people(self):
        """ write the people associated with the tag """
        plist = self.database.iter_person_handles()
        filter_class = GenericFilterFactory('Person')
        a_filter = filter_class()
        a_filter.add_rule(rules.person.HasTag([self.tag]))
        ind_list = a_filter.apply(self.database, plist)

        if not ind_list:
            return

        self.doc.start_paragraph("TR-Heading")
        header = self._("People")
        mark = IndexMark(header, INDEX_TYPE_TOC, 2)
        self.doc.write_text(header, mark)
        self.doc.end_paragraph()

        self.doc.start_table('PeopleTable', 'TR-Table')

        self.doc.start_row()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Id"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Name"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Birth"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Death"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.end_row()

        for person_handle in ind_list:
            person = self.database.get_person_from_handle(person_handle)

            self.doc.start_row()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(person.get_gid())
            self.doc.end_paragraph()
            self.doc.end_cell()

            name = self._name_display.display(person)
            mark = utils.get_person_mark(self.database, person)
            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(name, mark)
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            birth_ref = person.get_birth_ref()
            if birth_ref:
                event = self.database.get_event_from_handle(birth_ref.ref)
                self.doc.write_text(self._get_date(event.get_date_object()))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            death_ref = person.get_death_ref()
            if death_ref:
                event = self.database.get_event_from_handle(death_ref.ref)
                self.doc.write_text(self._get_date(event.get_date_object()))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.end_row()

        self.doc.end_table()

    def write_families(self):
        """ write the families associated with the tag """
        flist = self.database.iter_family_handles()
        filter_class = GenericFilterFactory('Family')
        a_filter = filter_class()
        a_filter.add_rule(rules.family.HasTag([self.tag]))
        fam_list = a_filter.apply(self.database, flist)

        if not fam_list:
            return

        self.doc.start_paragraph("TR-Heading")
        header = self._("Families")
        mark = IndexMark(header, INDEX_TYPE_TOC, 2)
        self.doc.write_text(header, mark)
        self.doc.end_paragraph()

        self.doc.start_table('FamilyTable', 'TR-Table')

        self.doc.start_row()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Id"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Father"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Mother"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Relationship"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.end_row()

        for family_handle in fam_list:
            family = self.database.get_family_from_handle(family_handle)

            self.doc.start_row()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(family.get_gid())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            father_handle = family.get_father_handle()
            if father_handle:
                father = self.database.get_person_from_handle(father_handle)
                mark = utils.get_person_mark(self.database, father)
                self.doc.write_text(self._name_display.display(father), mark)
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            mother_handle = family.get_mother_handle()
            if mother_handle:
                mother = self.database.get_person_from_handle(mother_handle)
                mark = utils.get_person_mark(self.database, mother)
                self.doc.write_text(self._name_display.display(mother), mark)
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            relation = family.get_relationship()
            self.doc.write_text(str(relation))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.end_row()

        self.doc.end_table()

    def write_events(self):
        """ write the events associated with the tag """
        elist = self.database.get_event_handles()
        filter_class = GenericFilterFactory('Event')
        a_filter = filter_class()
        a_filter.add_rule(rules.event.HasTag([self.tag]))
        event_list = a_filter.apply(self.database, elist)

        if not event_list:
            return

        self.doc.start_paragraph("TR-Heading")
        header = self._("Events")
        mark = IndexMark(header, INDEX_TYPE_TOC, 2)
        self.doc.write_text(header, mark)
        self.doc.end_paragraph()

        self.doc.start_table('EventTable', 'TR-Table')

        self.doc.start_row()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Id"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Type"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Participants"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Date"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.end_row()

        for event_handle in event_list:
            event = self.database.get_event_from_handle(event_handle)

            self.doc.start_row()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(event.get_gid())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(self._(self._get_type(event.get_type())))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(
                get_participant_from_event(self.database, event_handle))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            date = self._get_date(event.get_date_object())
            if date:
                self.doc.write_text(date)
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.end_row()

        self.doc.end_table()

    def write_places(self):
        """ write the places associated with the tag """
        plist = self.database.get_place_handles()
        filter_class = GenericFilterFactory('Place')
        a_filter = filter_class()
        a_filter.add_rule(rules.place.HasTag([self.tag]))
        place_list = a_filter.apply(self.database, plist)

        if not place_list:
            return

        self.doc.start_paragraph("TR-Heading")
        header = self._("Places")
        mark = IndexMark(header, INDEX_TYPE_TOC, 2)
        self.doc.write_text(header, mark)
        self.doc.end_paragraph()

        self.doc.start_table('PlaceTable', 'TR-Table')

        self.doc.start_row()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Id"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Title"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Name"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Type"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.end_row()

        for place_handle in place_list:
            place = self.database.get_place_from_handle(place_handle)
            place_title = _pd.display(self.database, place)

            self.doc.start_row()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(place.get_gid())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(place_title)
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(place.get_name())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(str(place.get_type()))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.end_row()

        self.doc.end_table()

    def write_notes(self):
        """ write the notes associated with the tag """
        nlist = self.database.get_note_handles()
        filter_class = GenericFilterFactory('Note')
        a_filter = filter_class()
        a_filter.add_rule(rules.note.HasTag([self.tag]))
        note_list = a_filter.apply(self.database, nlist)

        if not note_list:
            return

        self.doc.start_paragraph("TR-Heading")
        header = self._("Notes")
        mark = IndexMark(header, INDEX_TYPE_TOC, 2)
        self.doc.write_text(header, mark)
        self.doc.end_paragraph()

        self.doc.start_table('NoteTable', 'TR-Table')

        self.doc.start_row()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Id"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Type"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell', 2)
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Text"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.end_row()

        for note_handle in note_list:
            note = self.database.get_note_from_handle(note_handle)

            self.doc.start_row()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(note.get_gid())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            note_type = note.get_type()
            self.doc.write_text(str(note_type))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell', 2)
            self.doc.write_styled_note(
                note.get_styledtext(),
                note.get_format(),
                'TR-Note',
                contains_html=((note.get_type() == NoteType.HTML_CODE)))
            self.doc.end_cell()

            self.doc.end_row()

        self.doc.end_table()

    def write_media(self):
        """ write the media associated with the tag """
        mlist = self.database.get_media_handles(sort_handles=True)
        filter_class = GenericFilterFactory('Media')
        a_filter = filter_class()
        a_filter.add_rule(rules.media.HasTag([self.tag]))
        media_list = a_filter.apply(self.database, mlist)

        if not media_list:
            return

        self.doc.start_paragraph("TR-Heading")
        header = self._("Media")
        mark = IndexMark(header, INDEX_TYPE_TOC, 2)
        self.doc.write_text(header, mark)
        self.doc.end_paragraph()

        self.doc.start_table('MediaTable', 'TR-Table')

        self.doc.start_row()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Id"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Title"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Type"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Date"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.end_row()

        for media_handle in media_list:
            media = self.database.get_media_from_handle(media_handle)

            self.doc.start_row()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(media.get_gid())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            title = media.get_description()
            self.doc.write_text(str(title))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            mime_type = media.get_mime_type()
            self.doc.write_text(str(mime_type))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            date = self._get_date(media.get_date_object())
            if date:
                self.doc.write_text(date)
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.end_row()

        self.doc.end_table()

    def write_repositories(self):
        """ write the repositories associated with the tag """
        rlist = self.database.get_repository_handles()
        filter_class = GenericFilterFactory('Repository')
        a_filter = filter_class()
        a_filter.add_rule(rules.repository.HasTag([self.tag]))
        repo_list = a_filter.apply(self.database, rlist)

        if not repo_list:
            return

        self.doc.start_paragraph("TR-Heading")
        header = self._("Repositories")
        mark = IndexMark(header, INDEX_TYPE_TOC, 2)
        self.doc.write_text(header, mark)
        self.doc.end_paragraph()

        self.doc.start_table('ReopTable', 'TR-Table')

        self.doc.start_row()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Id"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Name"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Type"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Email Address"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.end_row()

        for repo_handle in repo_list:
            repo = self.database.get_repository_from_handle(repo_handle)

            self.doc.start_row()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(repo.get_gid())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(repo.get_name())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(str(repo.get_type()))
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            home_page = ''
            for url in repo.get_url_list():
                if url.get_type() == UrlType.EMAIL:
                    home_page = url.get_path()
                    break
            self.doc.write_text(home_page)
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.end_row()

        self.doc.end_table()

    def write_sources(self):
        """ write the sources associated with the tag """
        slist = self.database.get_source_handles(sort_handles=True)
        filter_class = GenericFilterFactory('Source')
        a_filter = filter_class()
        a_filter.add_rule(rules.source.HasTag([self.tag]))
        source_list = a_filter.apply(self.database, slist)

        if not source_list:
            return

        self.doc.start_paragraph("TR-Heading")
        header = self._("Source")
        mark = IndexMark(header, INDEX_TYPE_TOC, 2)
        self.doc.write_text(header, mark)
        self.doc.end_paragraph()

        self.doc.start_table('SourceTable', 'TR-Table')

        self.doc.start_row()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Id"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Title"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Author"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Publication Information"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.end_row()

        for source_handle in source_list:
            source = self.database.get_source_from_handle(source_handle)

            self.doc.start_row()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(source.get_gid())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(source.get_title())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(source.get_author())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(source.get_publication_info())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.end_row()

        self.doc.end_table()

    def write_citations(self):
        """ write the citations associated with the tag """
        clist = self.database.get_citation_handles(sort_handles=True)
        filter_class = GenericFilterFactory('Citation')
        a_filter = filter_class()
        a_filter.add_rule(rules.citation.HasTag([self.tag]))
        citation_list = a_filter.apply(self.database, clist)

        if not citation_list:
            return

        self.doc.start_paragraph("TR-Heading")
        header = self._("Citations")
        mark = IndexMark(header, INDEX_TYPE_TOC, 2)
        self.doc.write_text(header, mark)
        self.doc.end_paragraph()

        self.doc.start_table('CitationTable', 'TR-Table')

        self.doc.start_row()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Id"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Volume/Page"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Date"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.start_cell('TR-TableCell')
        self.doc.start_paragraph('TR-Normal-Bold')
        self.doc.write_text(self._("Source"))
        self.doc.end_paragraph()
        self.doc.end_cell()

        self.doc.end_row()

        for citation_handle in citation_list:
            citation = self.database.get_citation_from_handle(citation_handle)

            self.doc.start_row()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(citation.get_gid())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            self.doc.write_text(citation.get_page())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            date = self._get_date(citation.get_date_object())
            if date:
                self.doc.write_text(date)
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.start_cell('TR-TableCell')
            self.doc.start_paragraph('TR-Normal')
            source_handle = citation.get_reference_handle()
            source = self.database.get_source_from_handle(source_handle)
            self.doc.write_text(source.get_title())
            self.doc.end_paragraph()
            self.doc.end_cell()

            self.doc.end_row()

        self.doc.end_table()
Пример #5
0
class TimeLine(Report):
    """ TimeLine Report """
    def __init__(self, database, options, user):
        """
        Create the Timeline object that produces the report.

        The arguments are:

        database        - the GRAMPS database instance
        options         - instance of the Options class for this report
        user            - instance of gen.user.User()

        This report needs the following parameters (class variables)
        that come in the options class.

        filter    - Filter to be applied to the people of the database.
                    The option class carries its number, and the function
                    returning the list of filters.
        sortby        - Sorting method to be used.
        name_format   - Preferred format to display names
        incl_private  - Whether to include private data
        living_people - How to handle living people
        years_past_death - Consider as living this many years after death
        """
        Report.__init__(self, database, options, user)
        self._user = user
        menu = options.menu

        lang = options.menu.get_option_by_name('trans').get_value()
        rlocale = self.set_locale(lang)

        stdoptions.run_private_data_option(self, menu)
        living_opt = stdoptions.run_living_people_option(self, menu, rlocale)
        self.database = CacheProxyDb(self.database)

        self.filter = menu.get_option_by_name('filter').get_filter()
        self.fil_name = "(%s)" % self.filter.get_name(rlocale)

        living_value = menu.get_option_by_name('living_people').get_value()
        for (value, description) in living_opt.get_items(xml_items=True):
            if value == living_value:
                living_desc = self._(description)
                break
        self.living_desc = self._("(Living people: %(option_name)s)") % {
            'option_name': living_desc
        }

        stdoptions.run_name_format_option(self, menu)

        sort_func_num = menu.get_option_by_name('sortby').get_value()
        sort_functions = _get_sort_functions(Sort(self.database))
        self.sort_name = self._(sort_functions[sort_func_num][0])
        self.sort_func = sort_functions[sort_func_num][1]
        self.calendar = config.get('preferences.calendar-format-report')
        self.plist = []
        self.header = 2.6

    def write_report(self):
        # Apply the filter
        with self._user.progress(_('Timeline'), _('Applying filter...'),
                                 self.database.get_number_of_people()) as step:
            self.plist = self.filter.apply(self.database,
                                           self.database.iter_person_handles(),
                                           step)

        # Find the range of dates to include
        (low, high) = self.find_year_range()

        # Generate the actual timeline
        self.generate_timeline(low, high)

    def generate_timeline(self, low, high):
        """ generate the timeline """
        st_size = self.name_size()
        style_sheet = self.doc.get_style_sheet()
        font = style_sheet.get_paragraph_style('TLG-Name').get_font()
        incr = utils.pt2cm(font.get_size())
        pad = incr * 0.75
        _x1, _x2, _y1, _y2 = (0, 0, 0, 0)
        start = st_size + 0.5
        stop = self.doc.get_usable_width() - 0.5
        size = stop - start
        self.header = 2.6

        # Sort the people as requested
        with self._user.progress(_('Timeline'), _('Sorting dates...'),
                                 0) as step:
            self.plist.sort(key=self.sort_func)

        self.doc.start_page()
        self.build_grid(low, high, start, stop, True)

        index = 1
        current = 1

        length = len(self.plist)

        with self._user.progress(_('Timeline'), _('Calculating timeline...'),
                                 length) as step:

            for p_id in self.plist:
                person = self.database.get_person_from_handle(p_id)
                birth = get_birth_or_fallback(self.database, person)
                if birth:
                    bth = birth.get_date_object()
                    bth = bth.to_calendar(self.calendar).get_year()
                else:
                    bth = None

                death = get_death_or_fallback(self.database, person)
                if death:
                    dth = death.get_date_object()
                    dth = dth.to_calendar(self.calendar).get_year()
                else:
                    dth = None

                dname = self._name_display.display(person)
                mark = utils.get_person_mark(self.database, person)
                self.doc.draw_text('TLG-text', dname, incr + pad,
                                   self.header + (incr + pad) * index, mark)

                _y1 = self.header + (pad + incr) * index
                _y2 = self.header + ((pad + incr) * index) + incr
                _y3 = (_y1 + _y2) / 2.0
                w05 = 0.05

                if bth:
                    start_offset = ((float(bth - low) / float(high - low)) *
                                    size)
                    _x1 = start + start_offset
                    path = [(_x1, _y1), (_x1 + w05, _y3), (_x1, _y2),
                            (_x1 - w05, _y3)]
                    self.doc.draw_path('TLG-line', path)

                if dth:
                    start_offset = ((float(dth - low) / float(high - low)) *
                                    size)
                    _x1 = start + start_offset
                    path = [(_x1, _y1), (_x1 + w05, _y3), (_x1, _y2),
                            (_x1 - w05, _y3)]
                    self.doc.draw_path('TLG-solid', path)

                if bth and dth:
                    start_offset = (
                        (float(bth - low) / float(high - low)) * size) + w05
                    stop_offset = (
                        (float(dth - low) / float(high - low)) * size) - w05

                    _x1 = start + start_offset
                    _x2 = start + stop_offset
                    self.doc.draw_line('open', _x1, _y3, _x2, _y3)

                if (_y2 + incr) >= self.doc.get_usable_height():
                    if current != length:
                        self.doc.end_page()
                        self.doc.start_page()
                        self.build_grid(low, high, start, stop)
                    index = 1
                    _x1, _x2, _y1, _y2 = (0, 0, 0, 0)
                else:
                    index += 1
                current += 1
                step()
            self.doc.end_page()

    def build_grid(self, year_low, year_high, start_pos, stop_pos, toc=False):
        """
        Draws the grid outline for the chart. Sets the document label,
        draws the vertical lines, and adds the year labels. Arguments
        are:

        year_low  - lowest year on the chart
        year_high - highest year on the chart
        start_pos - x position of the lowest leftmost grid line
        stop_pos  - x position of the rightmost grid line
        """
        self.draw_title(toc)
        self.draw_columns(start_pos, stop_pos)
        if year_high is not None and year_low is not None:
            self.draw_year_headings(year_low, year_high, start_pos, stop_pos)
        else:
            self.draw_no_date_heading()

    def draw_columns(self, start_pos, stop_pos):
        """
        Draws the columns out of vertical lines.

        start_pos - x position of the lowest leftmost grid line
        stop_pos  - x position of the rightmost grid line
        """
        top_y = self.header
        bottom_y = self.doc.get_usable_height()
        delta = (stop_pos - start_pos) / 5
        for val in range(0, 6):
            xpos = start_pos + (val * delta)
            self.doc.draw_line('TLG-grid', xpos, top_y, xpos, bottom_y)

    def draw_title(self, toc):
        """
        Draws the title for the page.
        """
        width = self.doc.get_usable_width()
        title = "%(str1)s -- %(str2)s" % {
            'str1': self._("Timeline Chart"),
            # feature request 2356: avoid genitive form
            'str2': self._("Sorted by %s") % self.sort_name
        }
        title3 = self.living_desc
        mark = None
        if toc:
            mark = IndexMark(title, INDEX_TYPE_TOC, 1)
        self.doc.center_text('TLG-title', title, width / 2.0, 0, mark)
        style_sheet = self.doc.get_style_sheet()
        title_font = style_sheet.get_paragraph_style('TLG-Title').get_font()
        title_y = 1.2 - (utils.pt2cm(title_font.get_size()) * 1.2)
        self.doc.center_text('TLG-title', self.fil_name, width / 2.0, title_y)
        title_y = 1.8 - (utils.pt2cm(title_font.get_size()) * 1.2)
        self.doc.center_text('TLG-title', title3, width / 2.0, title_y)

    def draw_year_headings(self, year_low, year_high, start_pos, stop_pos):
        """
        Draws the column headings (years) for the page.
        """
        style_sheet = self.doc.get_style_sheet()
        label_font = style_sheet.get_paragraph_style('TLG-Label').get_font()
        label_y = self.header - (utils.pt2cm(label_font.get_size()) * 1.2)
        incr = (year_high - year_low) / 5
        delta = (stop_pos - start_pos) / 5
        for val in range(0, 6):
            xpos = start_pos + (val * delta)
            year_str = str(int(year_low + (incr * val)))
            self.doc.center_text('TLG-label', year_str, xpos, label_y)

    def draw_no_date_heading(self):
        """
        Draws a single heading that says "No Date Information"
        """
        width = self.doc.get_usable_width()
        style_sheet = self.doc.get_style_sheet()
        label_font = style_sheet.get_paragraph_style('TLG-Label').get_font()
        label_y = self.header - (utils.pt2cm(label_font.get_size()) * 1.2)
        self.doc.center_text('TLG-label', self._("No Date Information"),
                             width / 2.0, label_y)

    def find_year_range(self):
        """
        Finds the range of years that will be displayed on the chart.

        Returns a tuple of low and high years. If no dates are found, the
        function returns (None, None).
        """
        low = None
        high = None

        def min_max_year(low, high, year):
            """ convenience function """
            if year is not None and year != 0:
                if low is not None:
                    low = min(low, year)
                else:
                    low = year
                if high is not None:
                    high = max(high, year)
                else:
                    high = year
            return (low, high)

        with self._user.progress(_('Timeline'), _('Finding date range...'),
                                 len(self.plist)) as step:

            for p_id in self.plist:
                person = self.database.get_person_from_handle(p_id)
                birth = get_birth_or_fallback(self.database, person)
                if birth:
                    bth = birth.get_date_object()
                    bth = bth.to_calendar(self.calendar).get_year()
                    (low, high) = min_max_year(low, high, bth)

                death = get_death_or_fallback(self.database, person)
                if death:
                    dth = death.get_date_object()
                    dth = dth.to_calendar(self.calendar).get_year()
                    (low, high) = min_max_year(low, high, dth)
                step()

            # round the dates to the nearest decade
            if low is not None:
                low = int((low / 10)) * 10
            else:
                low = high

            if high is not None:
                high = int(((high + 9) / 10)) * 10
            else:
                high = low

            # Make sure the difference is a multiple of 50 so
            # all year ranges land on a decade.
            if low is not None and high is not None:
                low -= 50 - ((high - low) % 50)

        return (low, high)

    def name_size(self):
        """ get the length of the name """
        self.plist = self.filter.apply(self.database,
                                       self.database.iter_person_handles())

        style_sheet = self.doc.get_style_sheet()
        gstyle = style_sheet.get_draw_style('TLG-text')
        pname = gstyle.get_paragraph_style()
        pstyle = style_sheet.get_paragraph_style(pname)
        font = pstyle.get_font()

        size = 0
        for p_id in self.plist:
            person = self.database.get_person_from_handle(p_id)
            dname = self._name_display.display(person)
            size = max(self.doc.string_width(font, dname), size)
        return utils.pt2cm(size)
Пример #6
0
class FanChart(Report):
    def __init__(self, database, options, user):
        """
        Create the FanChart object that produces the report.

        The arguments are:

        database     - the GRAMPS database instance
        options      - instance of the Options class for this report
        user         - a gen.user.User instance

        This report needs the following parameters (class variables)
        that come in the options class.

        maxgen       - Maximum number of generations to include.
        circle       - Draw a full circle, half circle, or quarter circle.
        background   - Background color is generation dependent or white.
        radial       - Print radial texts roundabout or as upright as possible.
        draw_empty   - draw background when there is no information
        same_style   - use the same style for all generation
        incl_private - Whether to include private data
        living_people - How to handle living people
        years_past_death - Consider as living this many years after death
        """

        Report.__init__(self, database, options, user)

        menu = options.menu

        lang = options.menu.get_option_by_name('trans').get_value()
        rlocale = self.set_locale(lang)

        stdoptions.run_private_data_option(self, menu)
        stdoptions.run_living_people_option(self, menu, rlocale)
        self.database = CacheProxyDb(self.database)

        self.max_generations = menu.get_option_by_name('maxgen').get_value()
        self.circle = menu.get_option_by_name('circle').get_value()
        self.background = menu.get_option_by_name('background').get_value()
        self.radial = menu.get_option_by_name('radial').get_value()
        pid = menu.get_option_by_name('pid').get_value()
        self.draw_empty = menu.get_option_by_name('draw_empty').get_value()
        self.same_style = menu.get_option_by_name('same_style').get_value()
        self.center_person = self.database.get_person_from_gid(pid)
        if self.center_person is None:
            raise ReportError(_("Person %s is not in the Database") % pid)

        self.graphic_style = []
        self.text_style = []
        for i in range(0, self.max_generations):
            self.graphic_style.append('FC-Graphic' + '%02d' % i)
            self.text_style.append('FC-Text' + '%02d' % i)

        self.calendar = 0

        self.height = 0
        self.map = [None] * 2**self.max_generations
        self.text = {}

    def apply_filter(self, person_handle, index):
        """traverse the ancestors recursively until either the end
        of a line is found, or until we reach the maximum number of
        generations that we want to deal with"""

        if (not person_handle) or (index >= 2**self.max_generations):
            return
        self.map[index - 1] = person_handle
        self.text[index - 1] = self.get_info(person_handle, log2(index))

        person = self.database.get_person_from_handle(person_handle)
        family_handle = person.get_main_parents_family_handle()
        if family_handle:
            family = self.database.get_family_from_handle(family_handle)
            self.apply_filter(family.get_father_handle(), index * 2)
            self.apply_filter(family.get_mother_handle(), (index * 2) + 1)

    def write_report(self):
        self.doc.start_page()

        self.apply_filter(self.center_person.get_handle(), 1)
        p_rn = self.center_person.get_primary_name().get_regular_name()

        if self.circle == FULL_CIRCLE:
            max_angle = 360.0
            start_angle = 90
            max_circular = 5
            _x_ = self.doc.get_usable_width() / 2.0
            _y_ = self.doc.get_usable_height() / 2.0
            min_xy = min(_x_, _y_)

        elif self.circle == HALF_CIRCLE:
            max_angle = 180.0
            start_angle = 180
            max_circular = 3
            _x_ = (self.doc.get_usable_width() / 2.0)
            _y_ = self.doc.get_usable_height()
            min_xy = min(_x_, _y_)

        else:  # quarter circle
            max_angle = 90.0
            start_angle = 270
            max_circular = 2
            _x_ = 0
            _y_ = self.doc.get_usable_height()
            min_xy = min(self.doc.get_usable_width(), _y_)

        # choose  one line or two lines translation according to the width
        title = self._("%(generations)d Generation Fan Chart "
                       "for %(person)s") % {
                           'generations': self.max_generations,
                           'person': p_rn
                       }
        title_nb_lines = 1
        style_sheet = self.doc.get_style_sheet()
        if style_sheet:
            p_style = style_sheet.get_paragraph_style('FC-Title')
            if p_style:
                font = p_style.get_font()
                if font:
                    title_width = utils.pt2cm(
                        self.doc.string_width(font, title))
                    if title_width > self.doc.get_usable_width():
                        title = self._("%(generations)d Generation Fan Chart "
                                       "for\n%(person)s") % {
                                           'generations': self.max_generations,
                                           'person': p_rn
                                       }
                        title_nb_lines = 2

        if self.circle == FULL_CIRCLE or self.circle == QUAR_CIRCLE:
            # adjust only if full circle or 1/4 circle in landscape mode
            if self.doc.get_usable_height() <= self.doc.get_usable_width():
                # Should be in Landscape now
                style_sheet = self.doc.get_style_sheet()
                p_style = style_sheet.get_paragraph_style('FC-Title')
                if p_style:
                    font = p_style.get_font()
                    if font:
                        fontsize = utils.pt2cm(font.get_size())
                        # _y_ is vertical distance to center of circle,
                        # move center down 1 fontsize
                        _y_ += fontsize * title_nb_lines
                        # min_XY is the diameter of the circle,
                        # subtract two fontsize
                        # so we dont draw outside bottom of the paper
                        min_xy = min(min_xy,
                                     _y_ - 2 * fontsize * title_nb_lines)
        if self.max_generations > max_circular:
            block_size = min_xy / (self.max_generations * 2 - max_circular)
        else:
            block_size = min_xy / self.max_generations

        # adaptation of the fonts (title and others)
        optimized_style_sheet = self.get_optimized_style_sheet(
            title,
            max_circular,
            block_size,
            self.same_style,
            not self.same_style,
            # if same_style, use default generated colors
            self.background == BACKGROUND_WHITE)

        if optimized_style_sheet:
            self.doc.set_style_sheet(optimized_style_sheet)

        # title
        mark = IndexMark(title, INDEX_TYPE_TOC, 1)
        self.doc.center_text('FC-Graphic-title', title,
                             self.doc.get_usable_width() / 2, 0, mark)
        # wheel
        for generation in range(0, min(max_circular, self.max_generations)):
            self.draw_circular(_x_, _y_, start_angle, max_angle, block_size,
                               generation)
        for generation in range(max_circular, self.max_generations):
            self.draw_radial(_x_, _y_, start_angle, max_angle, block_size,
                             generation)
        self.doc.end_page()

    def get_info(self, person_handle, generation):
        """ get info about a person """
        person = self.database.get_person_from_handle(person_handle)
        p_pn = person.get_primary_name()
        self.calendar = config.get('preferences.calendar-format-report')

        birth = get_birth_or_fallback(self.database, person)
        bth = ""
        if birth:
            bth = birth.get_date_object()
            bth = str(bth.to_calendar(self.calendar).get_year())
            if bth == 0:
                bth = ""
            elif birth.get_type() != EventType.BIRTH:
                bth += '*'

        death = get_death_or_fallback(self.database, person)
        dth = ""
        if death:
            dth = death.get_date_object()
            dth = str(dth.to_calendar(self.calendar).get_year())
            if dth == 0:
                dth = ""
            elif death.get_type() != EventType.DEATH:
                dth += '*'
        if bth and dth:
            val = "%s - %s" % (str(bth), str(dth))
        elif bth:
            val = "* %s" % (str(bth))
        elif dth:
            val = "+ %s" % (str(dth))
        else:
            val = ""

        if generation > 7:
            if (p_pn.get_first_name() != "") and (p_pn.get_surname() != ""):
                name = p_pn.get_first_name() + " " + p_pn.get_surname()
            else:
                name = p_pn.get_first_name() + p_pn.get_surname()
            if (name != "") and (val != ""):
                string = name + ", " + val
            else:
                string = name + val
            return [string]
        elif generation == 7:
            if (p_pn.get_first_name() != "") and (p_pn.get_surname() != ""):
                name = p_pn.get_first_name() + " " + p_pn.get_surname()
            else:
                name = p_pn.get_first_name() + p_pn.get_surname()

            if self.circle == FULL_CIRCLE:
                return [name, val]
            elif self.circle == HALF_CIRCLE:
                return [name, val]
            else:
                if (name != "") and (val != ""):
                    string = name + ", " + val
                else:
                    string = name + val
                return [string]
        elif generation == 6:
            if self.circle == FULL_CIRCLE:
                return [p_pn.get_first_name(), p_pn.get_surname(), val]
            elif self.circle == HALF_CIRCLE:
                return [p_pn.get_first_name(), p_pn.get_surname(), val]
            else:
                if (p_pn.get_first_name() != "") and (p_pn.get_surname() !=
                                                      ""):
                    name = p_pn.get_first_name() + " " + p_pn.get_surname()
                else:
                    name = p_pn.get_first_name() + p_pn.get_surname()
                return [name, val]
        else:
            return [p_pn.get_first_name(), p_pn.get_surname(), val]

    def get_max_width_for_circles(self, rad1, rad2, max_centering_proportion):
        r"""
        (the "r" in the above line is to keep pylint happy)
           __
          /__\ <- compute the line width which is drawable between 2 circles.
         /  _ \   max_centering_proportion : 0, touching the circle1, 1,
        |  |_| |   touching the circle2, 0.5 : middle between the 2 circles
        |      |
         \    /
          \__/
                 basically, max_centering_proportion is
                 max_centering_proportion/nb_lines
        """
        # radius at the center of the 2 circles
        rmid = rad2 - (rad2 - rad1) * max_centering_proportion
        return sin(acos(rmid / rad2)) * rad2 * 2

    def get_max_width_for_circles_line(self,
                                       rad1,
                                       rad2,
                                       line,
                                       nb_lines,
                                       centering=False):
        r"""
        (the "r" in the above line is to keep pylint happy)
           __
          /__\ <- compute the line width which is drawable between 2 circles.
         /  _ \   instead of a max_centering_proportion, you get a
        |  |_| |  line/nb_lines position.  (we suppose that lines have the
        |      |  same heights.) for example, if you've 2 lines to draw,
         \    /   line 2 max width is at the 2/3 between the 2 circles
          \__/
        """
        if centering:
            return self.get_max_width_for_circles(rad1, rad2, 1.0)
        else:
            return self.get_max_width_for_circles(rad1, rad2,
                                                  line / float(nb_lines + 1))

    def get_optimized_font_size_for_text(self,
                                         rad1,
                                         rad2,
                                         text,
                                         font,
                                         centering=False):
        """
        a text can be several lines
        find the font size equals or lower than font.get_size() which fit
        between rad1 and rad2 to display the text.
        centering is a special case when you've the full circle
        available to draw the text in the middle of it
        """
        min_font_size = font.get_size()
        i = 1
        nb_lines = len(text)
        for line in text:
            font_size = self.get_optimized_font_size(
                line, font,
                self.get_max_width_for_circles_line(rad1, rad2, i, nb_lines,
                                                    centering))
            i += 1
            if min_font_size > font_size:
                min_font_size = font_size
        return min_font_size

    def get_optimized_font_size(self, line, font, max_width):
        """
        for a given width, guess the best font size which is equals
        or smaller than font which make line fit into max_width
        """
        test_font = FontStyle(font)
        width = utils.pt2cm(self.doc.string_width(test_font, line))
        while width > max_width and test_font.get_size() > 1:
            test_font.set_size(test_font.get_size() - 1)
            width = utils.pt2cm(self.doc.string_width(test_font, line))
        return test_font.get_size()

    def get_optimized_style_sheet(self, title, max_circular, block_size,
                                  map_style_from_single,
                                  map_paragraphs_colors_to_graphics,
                                  make_background_white):
        """
        returns an optimized (modified) style sheet which make fanchart
        look nicer
        """
        new_style_sheet = self.doc.get_style_sheet()
        if not new_style_sheet:
            return self.doc.get_style_sheet()

        # update title font size
        pstyle_name = 'FC-Title'
        p_style = new_style_sheet.get_paragraph_style(pstyle_name)
        if p_style:
            title_font = p_style.get_font()
            if title_font:
                title_width = utils.pt2cm(
                    self.doc.string_multiline_width(title_font, title))
                while (title_width > self.doc.get_usable_width()
                       and title_font.get_size() > 1):
                    title_font.set_size(title_font.get_size() - 1)
                    title_width = utils.pt2cm(
                        self.doc.string_multiline_width(title_font, title))
                new_style_sheet.add_paragraph_style(pstyle_name, p_style)

        # biggest font allowed is the one of the fist generation, after,
        # always lower than the previous one
        p_style = new_style_sheet.get_paragraph_style(self.text_style[0])
        font = None
        if p_style:
            font = p_style.get_font()
        if font:
            previous_generation_font_size = font.get_size()

            for generation in range(0, self.max_generations):
                gstyle_name = self.graphic_style[generation]
                pstyle_name = self.text_style[generation]
                g_style = new_style_sheet.get_draw_style(gstyle_name)

                # p_style is a copy of 'FC-Text' - use different style
                # to be able to auto change some fonts for some generations
                if map_style_from_single:
                    p_style = new_style_sheet.get_paragraph_style('FC-Text')
                else:
                    p_style = new_style_sheet.get_paragraph_style(pstyle_name)

                if g_style and p_style:
                    # set graphic colors to paragraph colors,
                    # while it's functionnaly
                    # the same for fanchart or make backgrounds white
                    if make_background_white:
                        g_style.set_fill_color((255, 255, 255))
                        new_style_sheet.add_draw_style(gstyle_name, g_style)
                    elif map_paragraphs_colors_to_graphics:
                        pstyle = new_style_sheet.get_paragraph_style(
                            pstyle_name)
                        if pstyle:
                            g_style.set_fill_color(
                                pstyle.get_background_color())
                            new_style_sheet.add_draw_style(
                                gstyle_name, g_style)

                    # adapt font size if too big
                    segments = 2**generation
                    if generation < min(max_circular, self.max_generations):
                        # adpatation for circular fonts
                        rad1, rad2 = self.get_circular_radius(
                            block_size, generation, self.circle)
                        font = p_style.get_font()
                        if font:
                            min_font_size = font.get_size()
                            # find the smallest font required
                            for index in range(segments - 1, 2 * segments - 1):
                                if self.map[index]:
                                    font_size = \
                                        self.get_optimized_font_size_for_text(
                                            rad1, rad2, self.text[index],
                                            p_style.get_font(),
                                            (self.circle == FULL_CIRCLE and
                                             generation == 0)
                                            )
                                if font_size < min_font_size:
                                    min_font_size = font_size
                            font.set_size(
                                min(previous_generation_font_size,
                                    min_font_size))
                    else:
                        # adaptation for radial fonts

                        # find the largest string for the generation
                        longest_line = ""
                        longest_width = 0
                        for index in range(segments - 1, 2 * segments - 1):
                            if self.map[index]:
                                for line in self.text[index]:
                                    width = utils.pt2cm(
                                        self.doc.string_multiline_width(
                                            p_style.get_font(), line))
                                    if width > longest_width:
                                        longest_line = line
                                        longest_width = width

                        # determine maximum width allowed for this generation
                        rad1, rad2 = self.get_radial_radius(
                            block_size, generation, self.circle)
                        max_width = rad2 - rad1

                        # reduce the font so that longest_width
                        # fit into max_width
                        font = p_style.get_font()
                        if font:
                            font.set_size(
                                min(
                                    previous_generation_font_size,
                                    self.get_optimized_font_size(
                                        longest_line, p_style.get_font(),
                                        max_width)))

                    # redefine the style
                    new_style_sheet.add_paragraph_style(pstyle_name, p_style)
                    font = p_style.get_font()
        if font:
            previous_generation_font_size = font.get_size()

        # finished
        return new_style_sheet

    def draw_circular(self, _x_, _y_, start_angle, max_angle, size,
                      generation):
        segments = 2**generation
        delta = max_angle / segments
        end_angle = start_angle
        text_angle = start_angle - 270 + (delta / 2.0)
        rad1, rad2 = self.get_circular_radius(size, generation, self.circle)
        graphic_style = self.graphic_style[generation]

        for index in range(segments - 1, 2 * segments - 1):
            start_angle = end_angle
            end_angle = start_angle + delta
            (_xc, _yc) = draw_wedge(self.doc, graphic_style, _x_, _y_, rad2,
                                    start_angle, end_angle, self.map[index]
                                    or self.draw_empty, rad1)
            if self.map[index]:
                if (generation == 0) and self.circle == FULL_CIRCLE:
                    _yc = _y_
                person = self.database.get_person_from_handle(self.map[index])
                mark = utils.get_person_mark(self.database, person)
                self.doc.rotate_text(graphic_style, self.text[index], _xc, _yc,
                                     text_angle, mark)
            text_angle += delta

    def get_radial_radius(self, size, generation, circle):
        """ determine the radius """
        if circle == FULL_CIRCLE:
            rad1 = size * ((generation * 2) - 5)
            rad2 = size * ((generation * 2) - 3)
        elif circle == HALF_CIRCLE:
            rad1 = size * ((generation * 2) - 3)
            rad2 = size * ((generation * 2) - 1)
        else:  # quarter circle
            rad1 = size * ((generation * 2) - 2)
            rad2 = size * (generation * 2)
        return rad1, rad2

    def get_circular_radius(self, size, generation, circle):
        """ determine the radius """
        return size * generation, size * (generation + 1)

    def draw_radial(self, _x_, _y_, start_angle, max_angle, size, generation):
        segments = 2**generation
        delta = max_angle / segments
        end_angle = start_angle
        text_angle = start_angle - delta / 2.0
        graphic_style = self.graphic_style[generation]

        rad1, rad2 = self.get_radial_radius(size, generation, self.circle)
        for index in range(segments - 1, 2 * segments - 1):
            start_angle = end_angle
            end_angle = start_angle + delta
            (_xc, _yc) = draw_wedge(self.doc, graphic_style, _x_, _y_, rad2,
                                    start_angle, end_angle, self.map[index]
                                    or self.draw_empty, rad1)
            text_angle += delta
            if self.map[index]:
                person = self.database.get_person_from_handle(self.map[index])
                mark = utils.get_person_mark(self.database, person)
                if (self.radial == RADIAL_UPRIGHT and (start_angle >= 90)
                        and (start_angle < 270)):
                    self.doc.rotate_text(graphic_style, self.text[index], _xc,
                                         _yc, text_angle + 180, mark)
                else:
                    self.doc.rotate_text(graphic_style, self.text[index], _xc,
                                         _yc, text_angle, mark)