Esempio n. 1
0
    def __init__(self, report, the_lang, the_title, person_handle, has_add,
                 has_res, has_url):
        """
        @param: report        -- The instance of the main report class
                                 for this report
        @param: the_lang      -- The lang to process
        @param: the_title     -- The title page related to the language
        @param: person_handle -- the url, address and residence to use
                                 for the report
        @param: has_add       -- the address to use for the report
        @param: has_res       -- the residence to use for the report
        @param: has_url       -- the url to use for the report
        """
        person = report.database.get_person_from_handle(person_handle)
        BasePage.__init__(self, report, the_lang, the_title, person.gramps_id)
        self.bibli = Bibliography()

        self.uplink = True

        # set the file name and open file
        output_file, sio = self.report.create_file(person_handle, "addr")
        result = self.write_header(_("Address Book"))
        addressbookpage, dummy_head, dummy_body, outerwrapper = result

        # begin address book page division and section title
        with Html("div", class_="content",
                  id="AddressBookDetail") as addressbookdetail:
            outerwrapper += addressbookdetail

            link = self.new_person_link(person_handle,
                                        uplink=True,
                                        person=person)
            addressbookdetail += Html("h3", link)

            # individual has an address
            if has_add:
                addressbookdetail += self.display_addr_list(has_add, None)

            # individual has a residence
            if has_res:
                addressbookdetail.extend(
                    self.dump_residence(res) for res in has_res)

            # individual has a url
            if has_url:
                addressbookdetail += self.display_url_list(has_url)

        # add fullclear for proper styling
        # and footer section to page
        footer = self.write_footer(None)
        outerwrapper += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.xhtml_writer(addressbookpage, output_file, sio, 0)
Esempio n. 2
0
    def __init__(self, database, options, user):
        """
        Create the DetAncestorReport 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.
        
        gen           - Maximum number of generations to include.
        pagebgg       - Whether to include page breaks between generations.
        pageben       - Whether to include page break before End Notes.
        firstName     - Whether to use first names instead of pronouns.
        fulldate      - Whether to use full dates instead of just year.
        listchildren  - Whether to list children.
        includenotes  - Whether to include notes.
        incattrs      - Whether to include attributes
        blankplace    - Whether to replace missing Places with ___________.
        blankDate     - Whether to replace missing Dates with ___________.
        calcageflag   - Whether to compute age.
        dupperson     - Whether to omit duplicate ancestors
                            (e.g. when distant cousins marry).
        verbose       - Whether to use complete sentences
        childref      - Whether to add descendant references in child list.
        addimages     - Whether to include images.
        pid           - The Gramps ID of the center person for the report.
        name_format   - Preferred format to display names
        incl_private  - Whether to include private data
        """
        Report.__init__(self, database, options, user)

        self.map = {}
        self._user = user

        menu = options.menu
        get_option_by_name = menu.get_option_by_name
        get_value = lambda name: get_option_by_name(name).get_value()

        stdoptions.run_private_data_option(self, menu)
        self.db = self.database

        self.max_generations = get_value('gen')
        self.pgbrk         = get_value('pagebbg')
        self.pgbrkenotes   = get_value('pageben')
        self.fulldate      = get_value('fulldates')
        use_fulldate     = self.fulldate
        self.listchildren  = get_value('listc')
        self.includenotes  = get_value('incnotes')
        use_call           = get_value('usecall')
        blankplace         = get_value('repplace')
        blankdate          = get_value('repdate')
        self.calcageflag   = get_value('computeage')
        self.dupperson     = get_value('omitda')
        self.verbose       = get_value('verbose')
        self.childref      = get_value('desref')
        self.addimages     = get_value('incphotos')
        self.inc_names     = get_value('incnames')
        self.inc_events    = get_value('incevents')
        self.inc_addr      = get_value('incaddresses')
        self.inc_sources   = get_value('incsources')
        self.inc_srcnotes  = get_value('incsrcnotes')
        self.inc_attrs     = get_value('incattrs')
        self.initial_sosa  = get_value('initial_sosa')
        pid                = get_value('pid')
        self.center_person = self.db.get_person_from_gramps_id(pid)
        if (self.center_person == None) :
            raise ReportError(_("Person %s is not in the Database") % pid )

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

        stdoptions.run_name_format_option(self, menu)

        self.gen_handles = {}
        self.prev_gen_handles = {}
        
        if blankdate:
            empty_date = EMPTY_ENTRY
        else:
            empty_date = ""

        if blankplace:
            empty_place = EMPTY_ENTRY
        else:
            empty_place = ""

        self.__narrator = Narrator(self.db, self.verbose, use_call,
                                   use_fulldate, empty_date, empty_place,
                                   nlocale=self._locale,
                                   get_endnote_numbers=self.endnotes)

        self.bibli = Bibliography(Bibliography.MODE_DATE|Bibliography.MODE_PAGE)
Esempio n. 3
0
    def __init__(self, report, the_lang, the_title, step):
        """
        @param: report        -- The instance of the main report class
                                 for this report
        @param: the_lang      -- The lang to process
        @param: the_title     -- The title page related to the language
        @param: step          -- Use to continue the progess bar
        """
        import os
        BasePage.__init__(self, report, the_lang, the_title)
        self.bibli = Bibliography()
        self.uplink = False
        self.report = report
        # set the file name and open file
        output_file, sio = self.report.create_file("statistics")
        result = self.write_header(_("Statistics"))
        addressbookpage, dummy_head, dummy_body, outerwrapper = result
        (males,
         females,
         unknown) = self.get_gender(report.database.iter_person_handles())

        step()
        mobjects = report.database.get_number_of_media()
        npersons = report.database.get_number_of_people()
        nfamilies = report.database.get_number_of_families()
        nsurnames = len(set(report.database.surname_list))
        notfound = []
        total_media = 0
        mbytes = "0"
        chars = 0
        for media in report.database.iter_media():
            total_media += 1
            fullname = media_path_full(report.database, media.get_path())
            try:
                chars += os.path.getsize(fullname)
                length = len(str(chars))
                if chars <= 999999:
                    mbytes = self._("less than 1")
                else:
                    mbytes = str(chars)[:(length-6)]
            except OSError:
                notfound.append(media.get_path())


        with Html("div", class_="content", id='EventDetail') as section:
            section += Html("h3", self._("Database overview"), inline=True)
        outerwrapper += section
        with Html("div", class_="content", id='subsection narrative') as sec11:
            sec11 += Html("h4", self._("Individuals"), inline=True)
        outerwrapper += sec11
        with Html("div", class_="content", id='subsection narrative') as sec1:
            sec1 += Html("br", self._("Number of individuals") + self.colon +
                         "%d" % npersons, inline=True)
            sec1 += Html("br", self._("Males") + self.colon +
                         "%d" % males, inline=True)
            sec1 += Html("br", self._("Females") + self.colon +
                         "%d" % females, inline=True)
            sec1 += Html("br", self._("Individuals with unknown gender") +
                         self.colon + "%d" % unknown, inline=True)
        outerwrapper += sec1
        with Html("div", class_="content", id='subsection narrative') as sec2:
            sec2 += Html("h4", self._("Family Information"), inline=True)
            sec2 += Html("br", self._("Number of families") + self.colon +
                         "%d" % nfamilies, inline=True)
            sec2 += Html("br", self._("Unique surnames") + self.colon +
                         "%d" % nsurnames, inline=True)
        outerwrapper += sec2
        with Html("div", class_="content", id='subsection narrative') as sec3:
            sec3 += Html("h4", self._("Media Objects"), inline=True)
            sec3 += Html("br",
                         self._("Total number of media object references") +
                         self.colon + "%d" % total_media, inline=True)
            sec3 += Html("br", self._("Number of unique media objects") +
                         self.colon + "%d" % mobjects, inline=True)
            sec3 += Html("br", self._("Total size of media objects") +
                         self.colon +
                         "%8s %s" % (mbytes, self._("MB", "Megabyte")),
                         inline=True)
            sec3 += Html("br", self._("Missing Media Objects") +
                         self.colon + "%d" % len(notfound), inline=True)
        outerwrapper += sec3
        with Html("div", class_="content", id='subsection narrative') as sec4:
            sec4 += Html("h4", self._("Miscellaneous"), inline=True)
            sec4 += Html("br", self._("Number of events") + self.colon +
                         "%d" % report.database.get_number_of_events(),
                         inline=True)
            sec4 += Html("br", self._("Number of places") + self.colon +
                         "%d" % report.database.get_number_of_places(),
                         inline=True)
            nsources = report.database.get_number_of_sources()
            sec4 += Html("br", self._("Number of sources") +
                         self.colon + "%d" % nsources,
                         inline=True)
            ncitations = report.database.get_number_of_citations()
            sec4 += Html("br", self._("Number of citations") +
                         self.colon + "%d" % ncitations,
                         inline=True)
            nrepo = report.database.get_number_of_repositories()
            sec4 += Html("br", self._("Number of repositories") +
                         self.colon + "%d" % nrepo,
                         inline=True)
        outerwrapper += sec4

        (males,
         females,
         unknown) = self.get_gender(self.report.bkref_dict[Person].keys())

        origin = " :<br/>" + report.filter.get_name(self.rlocale)
        with Html("div", class_="content", id='EventDetail') as section:
            section += Html("h3",
                            self._("Narrative web content report for") + origin,
                            inline=True)
        outerwrapper += section
        with Html("div", class_="content", id='subsection narrative') as sec5:
            sec5 += Html("h4", self._("Individuals"), inline=True)
            sec5 += Html("br", self._("Number of individuals") + self.colon +
                         "%d" % len(self.report.bkref_dict[Person]),
                         inline=True)
            sec5 += Html("br", self._("Males") + self.colon +
                         "%d" % males, inline=True)
            sec5 += Html("br", self._("Females") + self.colon +
                         "%d" % females, inline=True)
            sec5 += Html("br", self._("Individuals with unknown gender") +
                         self.colon + "%d" % unknown, inline=True)
        outerwrapper += sec5
        with Html("div", class_="content", id='subsection narrative') as sec6:
            sec6 += Html("h4", self._("Family Information"), inline=True)
            sec6 += Html("br", self._("Number of families") + self.colon +
                         "%d" % len(self.report.bkref_dict[Family]),
                         inline=True)
        outerwrapper += sec6
        with Html("div", class_="content", id='subsection narrative') as sec7:
            sec7 += Html("h4", self._("Miscellaneous"), inline=True)
            sec7 += Html("br", self._("Number of events") + self.colon +
                         "%d" % len(self.report.bkref_dict[Event]),
                         inline=True)
            sec7 += Html("br", self._("Number of places") + self.colon +
                         "%d" % len(self.report.bkref_dict[Place]),
                         inline=True)
            sec7 += Html("br", self._("Number of sources") + self.colon +
                         "%d" % len(self.report.bkref_dict[Source]),
                         inline=True)
            sec7 += Html("br", self._("Number of citations") + self.colon +
                         "%d" % len(self.report.bkref_dict[Citation]),
                         inline=True)
            sec7 += Html("br", self._("Number of repositories") + self.colon +
                         "%d" % len(self.report.bkref_dict[Repository]),
                         inline=True)
        outerwrapper += sec7

        # add fullclear for proper styling
        # and footer section to page
        footer = self.write_footer(None)
        outerwrapper += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.xhtml_writer(addressbookpage, output_file, sio, 0)
Esempio n. 4
0
class IndivCompleteReport(Report):

    def __init__(self, database, options, user):
        """
        Create the IndivCompleteReport 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.

        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.
        cites     - Whether or not to include source information.
        sort      - Whether or not to sort events into chronological order.
        images    - Whether or not to include images.
        sections  - Which event groups should be given separate sections.
        name_format   - Preferred format to display names
        incl_private  - Whether to include private data
        """

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

        stdoptions.run_private_data_option(self, menu)
        self._db = self.database

        self.use_pagebreak = menu.get_option_by_name('pageben').get_value()
        self.use_srcs = menu.get_option_by_name('cites').get_value()
        self.use_srcs_notes = menu.get_option_by_name('incsrcnotes').get_value()

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

        self.use_images = menu.get_option_by_name('images').get_value()
        self.use_gramps_id = menu.get_option_by_name('grampsid').get_value()

        filter_option = options.menu.get_option_by_name('filter')
        self.filter = filter_option.get_filter()
        self.bibli = None

        self.section_list = menu.get_option_by_name('sections').get_selected()

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

        stdoptions.run_name_format_option(self, menu)

    def write_fact(self, event_ref, event, show_type=True):
        """
        Writes a single event.
        """
        role = event_ref.get_role()
        description = event.get_description()

        date = self._get_date(event.get_date_object())
        place_name = ''
        place_endnote = ''
        place_handle = event.get_place_handle()
        if place_handle:
            place = self._db.get_place_from_handle(place_handle)
            place_name = place_displayer.display_event(self._db, event)
            place_endnote = self._cite_endnote(place)
        # make sure it's translated, so it can be used below, in "combine"
        ignore1 = _('%(str1)s in %(str2)s. ') % {'str1':'', 'str2':''}
        date_place = self.combine('%(str1)s in %(str2)s. ', '%s. ',
                                  date, place_name)

        if show_type:
            # Groups with more than one type
            column_1 = self._(self._get_type(event.get_type()))
            if role not in (EventRoleType.PRIMARY, EventRoleType.FAMILY):
                column_1 = column_1 + ' (' + self._(role.xml_str()) + ')'
            # translators: needed for Arabic, ignore otherwise
            # make sure it's translated, so it can be used below, in "combine"
            ignore2 = _('%(str1)s, %(str2)s') % {'str1':'', 'str2':''}
            column_2 = self.combine('%(str1)s, %(str2)s', '%s',
                                    description, date_place)
        else:
            # Groups with a single type (remove event type from first column)
            column_1 = date
            # translators: needed for Arabic, ignore otherwise
            # make sure it's translated, so it can be used below, in "combine"
            ignore3 = _('%(str1)s, %(str2)s') % {'str1':'', 'str2':''}
            column_2 = self.combine('%(str1)s, %(str2)s', '%s',
                                    description, place_name)

        endnotes = self._cite_endnote(event, prior=place_endnote)

        self.doc.start_row()
        self.write_cell(column_1)
        self.doc.start_cell('IDS-NormalCell')
        self.doc.start_paragraph('IDS-Normal')
        self.doc.write_text(column_2)
        if endnotes:
            self.doc.start_superscript()
            self.doc.write_text(endnotes)
            self.doc.end_superscript()
        self.doc.end_paragraph()

        self.do_attributes(event.get_attribute_list() +
                           event_ref.get_attribute_list() )

        for notehandle in event.get_note_list():
            note = self._db.get_note_from_handle(notehandle)
            text = note.get_styledtext()
            note_format = note.get_format()
            self.doc.write_styled_note(text, note_format, 'IDS-Normal',
                        contains_html= note.get_type() == NoteType.HTML_CODE)

        self.doc.end_cell()
        self.doc.end_row()

    def write_p_entry(self, label, parent_name, rel_type, pmark=None):
        self.doc.start_row()
        self.write_cell(label)
        if parent_name:
            # for example (a stepfather): John Smith, relationship: Step
            text = self._('%(parent-name)s, relationship: %(rel-type)s') % {
                                      'parent-name' : parent_name,
                                      'rel-type' : self._(rel_type)}
            self.write_cell(text, mark=pmark)
        else:
            self.write_cell('')
        self.doc.end_row()

    def write_note(self):
        notelist = self.person.get_note_list()
        notelist += self.family_notes_list
        if not notelist:
            return
        self.doc.start_table('note','IDS-IndTable')
        self.doc.start_row()
        self.doc.start_cell('IDS-TableHead', 2)
        self.write_paragraph(self._('Notes'), style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()

        for notehandle in notelist:
            note = self._db.get_note_from_handle(notehandle)
            text = note.get_styledtext()
            note_format = note.get_format()
            self.doc.start_row()
            self.doc.start_cell('IDS-NormalCell', 2)
            self.doc.write_styled_note(text, note_format, 'IDS-Normal',
                        contains_html= note.get_type() == NoteType.HTML_CODE)

            self.doc.end_cell()
            self.doc.end_row()

        self.doc.end_table()
        self.doc.start_paragraph("IDS-Normal")
        self.doc.end_paragraph()

    def write_alt_parents(self):

        family_handle_list = self.person.get_parent_family_handle_list()
        if len(family_handle_list) < 2:
            return

        self.doc.start_table("altparents","IDS-IndTable")
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", 2)
        self.write_paragraph(self._('Alternate Parents'),
                             style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()

        for family_handle in family_handle_list:
            if (family_handle ==
                   self.person.get_main_parents_family_handle()):
                continue

            family = self._db.get_family_from_handle(family_handle)

            # Get the mother and father relationships
            frel = ""
            mrel = ""
            child_handle = self.person.get_handle()
            child_ref_list = family.get_child_ref_list()
            for child_ref in child_ref_list:
                if child_ref.ref == child_handle:
                    frel = str(child_ref.get_father_relation())
                    mrel = str(child_ref.get_mother_relation())

            father_handle = family.get_father_handle()
            if father_handle:
                father = self._db.get_person_from_handle(father_handle)
                fname = self._name_display.display(father)
                mark = ReportUtils.get_person_mark(self._db, father)
                self.write_p_entry(self._('Father'), fname, frel, mark)
            else:
                self.write_p_entry(self._('Father'), '', '')

            mother_handle = family.get_mother_handle()
            if mother_handle:
                mother = self._db.get_person_from_handle(mother_handle)
                mname = self._name_display.display(mother)
                mark = ReportUtils.get_person_mark(self._db, mother)
                self.write_p_entry(self._('Mother'), mname, mrel, mark)
            else:
                self.write_p_entry(self._('Mother'), '', '')

        self.doc.end_table()
        self.doc.start_paragraph("IDS-Normal")
        self.doc.end_paragraph()

    def get_name(self, person):
        name = self._name_display.display(person)
        if self.use_gramps_id:
            return '%(name)s [%(gid)s]' % { 'name': name,
                                            'gid': person.get_gramps_id()}
        else:
            return name

    def write_alt_names(self):

        if len(self.person.get_alternate_names()) < 1:
            return

        self.doc.start_table("altnames","IDS-IndTable")
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", 2)
        self.write_paragraph(self._('Alternate Names'),
                             style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()

        for name in self.person.get_alternate_names():
            name_type = self._(self._get_type(name.get_type()))
            self.doc.start_row()
            self.write_cell(name_type)
            text = self._name_display.display_name(name)
            endnotes = self._cite_endnote(name)
            self.write_cell(text, endnotes)
            self.doc.end_row()
        self.doc.end_table()
        self.doc.start_paragraph('IDS-Normal')
        self.doc.end_paragraph()

    def write_addresses(self):

        alist = self.person.get_address_list()

        if len(alist) == 0:
            return

        self.doc.start_table("addresses","IDS-IndTable")
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", 2)
        self.write_paragraph(self._('Addresses'), style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()

        for addr in alist:
            text = ReportUtils.get_address_str(addr)
            date = self._get_date(addr.get_date_object())
            endnotes = self._cite_endnote(addr)
            self.doc.start_row()
            self.write_cell(date)
            self.write_cell(text, endnotes)
            self.doc.end_row()
        self.doc.end_table()
        self.doc.start_paragraph('IDS-Normal')
        self.doc.end_paragraph()

    def write_associations(self):

        if len(self.person.get_person_ref_list()) < 1:
            return

        self.doc.start_table("associations","IDS-IndTable")
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", 2)
        self.write_paragraph(self._('Associations'), style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()
        for person_ref in self.person.get_person_ref_list():
            endnotes = self._cite_endnote(person_ref)
            relationship = person_ref.get_relation()
            associate = self._db.get_person_from_handle(person_ref.ref)
            associate_name = self._name_display.display(associate)
            self.doc.start_row()
            self.write_cell(self._(relationship))
            self.write_cell(associate_name, endnotes)
            self.doc.end_row()
        self.doc.end_table()
        self.doc.start_paragraph('IDS-Normal')
        self.doc.end_paragraph()

    def write_attributes(self):

        attr_list = self.person.get_attribute_list()

        if len(attr_list) == 0:
            return

        self.doc.start_table("attributes","IDS-IndTable")
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", 2)
        self.write_paragraph(self._('Attributes'), style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()

        for attr in attr_list:
            attr_type = attr.get_type().type2base()
            self.doc.start_row()
            self.write_cell(self._(attr_type))
            text = attr.get_value()
            endnotes = self._cite_endnote(attr)
            self.write_cell(text, endnotes)
            self.doc.end_row()
        self.doc.end_table()
        self.doc.start_paragraph('IDS-Normal')
        self.doc.end_paragraph()

    def write_LDS_ordinances(self):

        ord_list = self.person.get_lds_ord_list()

        if len(ord_list) == 0:
            return

        self.doc.start_table("ordinances","IDS-IndTable")
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", 2)
        self.write_paragraph(self._('LDS Ordinance'), style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()
        self.doc.end_table()

        self.doc.start_table("ordinances3","IDS-OrdinanceTable")
        self.doc.start_row()
        self.write_cell(self._('Type'), style='IDS-Section')
        self.write_cell(self._('Date'), style='IDS-Section')
        self.write_cell(self._('Status'), style='IDS-Section')
        self.write_cell(self._('Temple'), style='IDS-Section')
        self.write_cell(self._('Place'), style='IDS-Section')
        self.doc.end_row()

        for lds_ord in ord_list:
            type = self._(lds_ord.type2str())
            date = self._get_date(lds_ord.get_date_object())
            status = self._(lds_ord.status2str())
            temple = TEMPLES.name(lds_ord.get_temple())
            place_name = ''
            place_endnote = ''
            place_handle = lds_ord.get_place_handle()
            if place_handle:
                place = self._db.get_place_from_handle(place_handle)
                place_name = place_displayer.display_event(self._db, lds_ord)
                place_endnote = self._cite_endnote(place)
            endnotes = self._cite_endnote(lds_ord, prior=place_endnote)
            self.doc.start_row()
            self.write_cell(type, endnotes)
            self.write_cell(date)
            self.write_cell(status)
            self.write_cell(temple)
            self.write_cell(place_name)
            self.doc.end_row()
        self.doc.end_table()
        self.doc.start_paragraph('IDS-Normal')
        self.doc.end_paragraph()

    def write_tags(self):

        thlist = self.person.get_tag_list()
        if len(thlist) == 0:
            return
        tags = []

        self.doc.start_table("tags","IDS-IndTable")
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", 2)
        self.write_paragraph(self._('Tags'), style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()
        for tag_handle in thlist:
            tag = self._db.get_tag_from_handle(tag_handle)
            tags.append(tag.get_name())
        for text in sorted(tags):
            self.doc.start_row()
            self.write_cell(text, span=2)
            self.doc.end_row()
        self.doc.end_table()
        self.doc.start_paragraph('IDS-Normal')
        self.doc.end_paragraph()

    def write_images(self):

        media_list = self.person.get_media_list()
        if (not self.use_images) or (not media_list):
            return

        i_total = 0
        for media_ref in media_list:
            media_handle = media_ref.get_reference_handle()
            if media_handle:
                media = self._db.get_media_from_handle(media_handle)
                if media and media.get_mime_type():
                    if media.get_mime_type().startswith("image"):
                        i_total += 1
        if i_total == 0:
            return
        # if there is only one image, and it is the first Gallery item, it
        # will be shown up at the top, so there's no reason to show it here;
        # but if there's only one image and it is not the first Gallery
        # item (maybe the first is a PDF, say), then we need to show it
        if ((i_total == 1) and self.mime0 and self.mime0.startswith("image")):
            return

        self.doc.start_table("images","IDS-GalleryTable")
        cells = 3 # the GalleryTable has 3 cells
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", cells)
        self.write_paragraph(self._('Images'), style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()
        media_count = 0
        image_count = 0
        while ( media_count < len(media_list) ):
            media_ref = media_list[media_count]
            media_handle = media_ref.get_reference_handle()
            media = self._db.get_media_from_handle(media_handle)
            if media is None:
                from gramps.gui.dialog import RunDatabaseRepair
                RunDatabaseRepair(_('Non existing media found in the Gallery'))
                return
            mime_type = media.get_mime_type()
            if not mime_type or not mime_type.startswith("image"):
                media_count += 1
                continue
            description = media.get_description()
            if image_count % cells == 0:
                self.doc.start_row()
            self.doc.start_cell('IDS-NormalCell')
            self.write_paragraph(description, style='IDS-ImageCaptionCenter')
            ReportUtils.insert_image(self._db, self.doc, media_ref, self._user,
                                     align='center', w_cm=5.0, h_cm=5.0)
            self.do_attributes(media.get_attribute_list() +
                               media_ref.get_attribute_list() )
            self.doc.end_cell()
            if image_count % cells == cells - 1:
                self.doc.end_row()
            media_count += 1
            image_count += 1
        if image_count % cells != 0:
            self.doc.end_row()
        self.doc.end_table()
        self.doc.start_paragraph('IDS-Normal')
        self.doc.end_paragraph()

    def write_families(self):

        family_handle_list = self.person.get_family_handle_list()
        if not len(family_handle_list):
            return

        self.doc.start_table("three","IDS-IndTable")
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", 2)
        self.write_paragraph(self._('Marriages/Children'),
                             style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()
        self.doc.end_table()

        for family_handle in family_handle_list:
            self.doc.start_table("three","IDS-IndTable")
            family = self._db.get_family_from_handle(family_handle)
            self.family_notes_list += family.get_note_list()
            if self.person.get_handle() == family.get_father_handle():
                spouse_id = family.get_mother_handle()
            else:
                spouse_id = family.get_father_handle()
            self.doc.start_row()
            self.doc.start_cell("IDS-NormalCell", 2)
            if spouse_id:
                spouse = self._db.get_person_from_handle(spouse_id)
                text = self.get_name(spouse)
                mark = ReportUtils.get_person_mark(self._db, spouse)
            else:
                spouse = None
                text = self._("unknown")
                mark = None
            endnotes = self._cite_endnote(family)
            self.write_paragraph(text, endnotes=endnotes, mark=mark,
                                 style='IDS-Spouse')
            self.doc.end_cell()
            self.doc.end_row()

            event_ref_list = family.get_event_ref_list()
            for event_ref, event in self.get_event_list(event_ref_list):
                self.write_fact(event_ref, event)

            child_ref_list = family.get_child_ref_list()
            if len(child_ref_list):
                self.doc.start_row()
                self.write_cell(self._("Children"))
                self.doc.start_cell("IDS-ListCell")
                for child_ref in child_ref_list:
                    child = self._db.get_person_from_handle(child_ref.ref)
                    name = self.get_name(child)
                    mark = ReportUtils.get_person_mark(self._db, child)
                    endnotes = self._cite_endnote(child_ref)
                    self.write_paragraph(name, endnotes=endnotes, mark=mark)
                self.doc.end_cell()
                self.doc.end_row()

            attr_list = family.get_attribute_list()
            if len(attr_list):
                self.doc.start_row()
                self.write_cell(self._("Attributes"))
                self.doc.start_cell("IDS-ListCell")
                self.do_attributes(attr_list)
                self.doc.end_cell()
                self.doc.end_row()

            self.doc.end_table()

            ord_list = family.get_lds_ord_list()
            if len(ord_list):
                self.doc.start_table("ordinances2","IDS-OrdinanceTable2")
                self.doc.start_row()
                self.write_cell(self._('LDS Ordinance'))
                self.write_cell(self._('Type'), style='IDS-Section')
                self.write_cell(self._('Date'), style='IDS-Section')
                self.write_cell(self._('Status'), style='IDS-Section')
                self.write_cell(self._('Temple'), style='IDS-Section')
                self.write_cell(self._('Place'), style='IDS-Section')
                self.doc.end_row()

                for lds_ord in ord_list:
                    type = self._(lds_ord.type2str())
                    date = self._get_date(lds_ord.get_date_object())
                    status = self._(lds_ord.status2str())
                    temple = TEMPLES.name(lds_ord.get_temple())
                    place_name = ''
                    place_endnote = ''
                    place_handle = lds_ord.get_place_handle()
                    if place_handle:
                        place = self._db.get_place_from_handle(place_handle)
                        place_name = place_displayer.display_event(self._db, lds_ord)
                        place_endnote = self._cite_endnote(place)
                    endnotes = self._cite_endnote(lds_ord, prior=place_endnote)
                    self.doc.start_row()
                    self.write_cell('')
                    self.write_cell(type, endnotes)
                    self.write_cell(date)
                    self.write_cell(status)
                    self.write_cell(temple)
                    self.write_cell(place_name)
                    self.doc.end_row()
                self.doc.end_table()

        self.doc.start_paragraph('IDS-Normal')
        self.doc.end_paragraph()

    def get_event_list(self, event_ref_list):
        """
        Return a list of (EventRef, Event) pairs.  Order by event date
        if the user option is set.
        """
        event_list = []
        for ind, event_ref in enumerate(event_ref_list):
            if event_ref:
                event = self._db.get_event_from_handle(event_ref.ref)
                if event:
                    sort_value = event.get_date_object().get_sort_value()
                    #first sort on date, equal dates, then sort as in GUI.
                    event_list.append((str(sort_value) + "%04i" % ind,
                                       event_ref, event))

        if self.sort:
            event_list.sort()

        return [(item[1], item[2]) for item in event_list]

    def write_section(self, event_ref_list, event_group):
        """
        Writes events in a single event group.
        """
        self.doc.start_table(event_group,"IDS-IndTable")
        self.doc.start_row()
        self.doc.start_cell("IDS-TableHead", 2)
        self.write_paragraph(self._(event_group), style='IDS-TableTitle')
        self.doc.end_cell()
        self.doc.end_row()

        for event_ref, event in self.get_event_list(event_ref_list):
            self.write_fact(event_ref, event)

        self.doc.end_table()
        self.doc.start_paragraph("IDS-Normal")
        self.doc.end_paragraph()

    def write_events(self):
        """
        Write events.  The user can create separate sections for a
        pre-defined set of event groups.  When an event has a type
        contained within a group it is moved from the Individual Facts
        section into its own section.
        """
        event_dict = defaultdict(list)
        event_ref_list = self.person.get_event_ref_list()
        for event_ref in event_ref_list:
            if event_ref:
                event = self._db.get_event_from_handle(event_ref.ref)
                group = TYPE2GROUP[event.get_type().value]
                if _(group) not in self.section_list:
                    group = SECTION_LIST[0]
                event_dict[group].append(event_ref)

        # Write separate event group sections
        for group in SECTION_LIST:
            if group in event_dict:
                self.write_section(event_dict[group], group)

    def write_cell(self, text,
                   endnotes=None, mark=None, style='IDS-Normal', span=1):
        self.doc.start_cell('IDS-NormalCell', span)
        self.write_paragraph(text, endnotes=endnotes, mark=mark, style=style)
        self.doc.end_cell()

    def write_paragraph(self, text,
                        endnotes=None, mark=None, style='IDS-Normal'):
        self.doc.start_paragraph(style)
        self.doc.write_text(text, mark)
        if endnotes:
            self.doc.start_superscript()
            self.doc.write_text(endnotes)
            self.doc.end_superscript()
        self.doc.end_paragraph()

    def write_report(self):
        plist = self._db.get_person_handles(sort_handles=True)
        if self.filter:
            ind_list = self.filter.apply(self._db, plist)
        else:
            ind_list = plist

        for count, person_handle in enumerate(ind_list):
            self.person = self._db.get_person_from_handle(person_handle)
            self.family_notes_list = []
            self.write_person(count)

    def write_person(self, count):
        if count != 0:
            self.doc.page_break()
        self.bibli = Bibliography(Bibliography.MODE_DATE|Bibliography.MODE_PAGE)

        text = self._name_display.display(self.person)
        # feature request 2356: avoid genitive form
        title = self._("Summary of %s") % text
        mark = IndexMark(title, INDEX_TYPE_TOC, 1)
        self.doc.start_paragraph("IDS-Title")
        self.doc.write_text(title, mark)
        self.doc.end_paragraph()

        self.doc.start_paragraph("IDS-Normal")
        self.doc.end_paragraph()

        name = self.person.get_primary_name()
        text = self.get_name(self.person)
        mark = ReportUtils.get_person_mark(self._db, self.person)
        endnotes = self._cite_endnote(self.person)
        endnotes = self._cite_endnote(name, prior=endnotes)

        family_handle = self.person.get_main_parents_family_handle()
        if family_handle:
            family = self._db.get_family_from_handle(family_handle)
            father_inst_id = family.get_father_handle()
            if father_inst_id:
                father_inst = self._db.get_person_from_handle(
                    father_inst_id)
                father = self.get_name(father_inst)
                fmark = ReportUtils.get_person_mark(self._db, father_inst)
            else:
                father = ""
                fmark = None
            mother_inst_id = family.get_mother_handle()
            if mother_inst_id:
                mother_inst = self._db.get_person_from_handle(mother_inst_id)
                mother = self.get_name(mother_inst)
                mmark = ReportUtils.get_person_mark(self._db, mother_inst)
            else:
                mother = ""
                mmark = None
        else:
            father = ""
            fmark = None
            mother = ""
            mmark = None

        media_list = self.person.get_media_list()
        p_style = 'IDS-PersonTable2'
        self.mime0 = None
        if self.use_images and len(media_list) > 0:
            media0 = media_list[0]
            media_handle = media0.get_reference_handle()
            media = self._db.get_media_from_handle(media_handle)
            self.mime0 = media.get_mime_type()
            if self.mime0 and self.mime0.startswith("image"):
                image_filename = media_path_full(self._db, media.get_path())
                if os.path.exists(image_filename):
                    p_style = 'IDS-PersonTable' # this is tested for, also
                else:
                    self._user.warn(_("Could not add photo to page"),
                                    # translators: for French, else ignore
                                    _("%(str1)s: %(str2)s") %
                                         {'str1' : image_filename,
                                          'str2' : _('File does not exist') } )

        self.doc.start_table('person', p_style)
        self.doc.start_row()

        self.doc.start_cell('IDS-NormalCell')
        # translators: needed for French, ignore otherwise
        ignore4 = self._("%s:")
        self.write_paragraph(self._("%s:") % self._("Name"))
        self.write_paragraph(self._("%s:") % self._("Gender"))
        self.write_paragraph(self._("%s:") % self._("Father"))
        self.write_paragraph(self._("%s:") % self._("Mother"))
        self.doc.end_cell()

        self.doc.start_cell('IDS-NormalCell')
        self.write_paragraph(text, endnotes, mark)
        if self.person.get_gender() == Person.MALE:
            self.write_paragraph(self._("Male"))
        elif self.person.get_gender() == Person.FEMALE:
            self.write_paragraph(self._("Female"))
        else:
            self.write_paragraph(self._("Unknown"))
        self.write_paragraph(father, mark=fmark)
        self.write_paragraph(mother, mark=mmark)
        self.doc.end_cell()

        if p_style == 'IDS-PersonTable':
            self.doc.start_cell('IDS-NormalCell')
            self.doc.add_media(image_filename, "right", 4.0, 4.0,
                                      crop=media0.get_rectangle())
            endnotes = self._cite_endnote(media0)
            attr_list = media0.get_attribute_list()
            if len(attr_list) == 0:
                text = _('(image)')
            else:
                for attr in attr_list:
                    attr_type = attr.get_type().type2base()
                    # translators: needed for French, ignore otherwise
                    text = self._("%(str1)s: %(str2)s") % {
                                        'str1' : self._(attr_type),
                                        'str2' : attr.get_value() }
                    endnotes = self._cite_endnote(attr, prior=endnotes)
                    self.write_paragraph("(%s)" % text,
                                         endnotes=endnotes,
                                         style='IDS-ImageNote')
                    endnotes = ''
            if endnotes and len(attr_list) == 0:
                self.write_paragraph(text, endnotes=endnotes,
                                     style='IDS-ImageNote')
            self.doc.end_cell()

        self.doc.end_row()
        self.doc.end_table()

        self.doc.start_paragraph("IDS-Normal")
        self.doc.end_paragraph()

        self.write_alt_names()
        self.write_events()
        self.write_alt_parents()
        self.write_families()
        self.write_addresses()
        self.write_associations()
        self.write_attributes()
        self.write_LDS_ordinances()
        self.write_tags()
        self.write_images()
        self.write_note()
        if self.use_srcs:
            if self.use_pagebreak and self.bibli.get_citation_count():
                self.doc.page_break()
            Endnotes.write_endnotes(self.bibli, self._db, self.doc,
                                    printnotes=self.use_srcs_notes,
                                    elocale=self._locale)

    def combine(self, format_both, format_single, str1, str2):
        """ Combine two strings with a given format. """
        text = ""
        if str1 and str2:
            text = self._(format_both) % {'str1':str1, 'str2':str2}
        elif str1 and not str2:
            text = format_single % str1
        elif str2 and not str1:
            text = format_single % str2
        return text

    def _cite_endnote(self, obj, prior=''):
        if not self.use_srcs:
            return ""
        if not obj:
            return prior

        txt = Endnotes.cite_source(self.bibli, self._db, obj, self._locale)
        if not txt:
            return prior
        if prior:
            # translators: needed for Arabic, ignore otherwise
            txt = self._('%(str1)s, %(str2)s') % {'str1':prior, 'str2':txt}
        return txt

    def do_attributes(self, attr_list):
        for attr in attr_list:
            attr_type = attr.get_type().type2base()
            # translators: needed for French, ignore otherwise
            text = self._("%(type)s: %(value)s") % {
                                'type'  : self._(attr_type),
                                'value' : attr.get_value() }
            endnotes = self._cite_endnote(attr)
            self.write_paragraph(text, endnotes)
Esempio n. 5
0
    def write_person(self, count):
        if count != 0:
            self.doc.page_break()
        self.bibli = Bibliography(Bibliography.MODE_DATE|Bibliography.MODE_PAGE)

        text = self._name_display.display(self.person)
        # feature request 2356: avoid genitive form
        title = self._("Summary of %s") % text
        mark = IndexMark(title, INDEX_TYPE_TOC, 1)
        self.doc.start_paragraph("IDS-Title")
        self.doc.write_text(title, mark)
        self.doc.end_paragraph()

        self.doc.start_paragraph("IDS-Normal")
        self.doc.end_paragraph()

        name = self.person.get_primary_name()
        text = self.get_name(self.person)
        mark = ReportUtils.get_person_mark(self._db, self.person)
        endnotes = self._cite_endnote(self.person)
        endnotes = self._cite_endnote(name, prior=endnotes)

        family_handle = self.person.get_main_parents_family_handle()
        if family_handle:
            family = self._db.get_family_from_handle(family_handle)
            father_inst_id = family.get_father_handle()
            if father_inst_id:
                father_inst = self._db.get_person_from_handle(
                    father_inst_id)
                father = self.get_name(father_inst)
                fmark = ReportUtils.get_person_mark(self._db, father_inst)
            else:
                father = ""
                fmark = None
            mother_inst_id = family.get_mother_handle()
            if mother_inst_id:
                mother_inst = self._db.get_person_from_handle(mother_inst_id)
                mother = self.get_name(mother_inst)
                mmark = ReportUtils.get_person_mark(self._db, mother_inst)
            else:
                mother = ""
                mmark = None
        else:
            father = ""
            fmark = None
            mother = ""
            mmark = None

        media_list = self.person.get_media_list()
        p_style = 'IDS-PersonTable2'
        self.mime0 = None
        if self.use_images and len(media_list) > 0:
            media0 = media_list[0]
            media_handle = media0.get_reference_handle()
            media = self._db.get_media_from_handle(media_handle)
            self.mime0 = media.get_mime_type()
            if self.mime0 and self.mime0.startswith("image"):
                image_filename = media_path_full(self._db, media.get_path())
                if os.path.exists(image_filename):
                    p_style = 'IDS-PersonTable' # this is tested for, also
                else:
                    self._user.warn(_("Could not add photo to page"),
                                    # translators: for French, else ignore
                                    _("%(str1)s: %(str2)s") %
                                         {'str1' : image_filename,
                                          'str2' : _('File does not exist') } )

        self.doc.start_table('person', p_style)
        self.doc.start_row()

        self.doc.start_cell('IDS-NormalCell')
        # translators: needed for French, ignore otherwise
        ignore4 = self._("%s:")
        self.write_paragraph(self._("%s:") % self._("Name"))
        self.write_paragraph(self._("%s:") % self._("Gender"))
        self.write_paragraph(self._("%s:") % self._("Father"))
        self.write_paragraph(self._("%s:") % self._("Mother"))
        self.doc.end_cell()

        self.doc.start_cell('IDS-NormalCell')
        self.write_paragraph(text, endnotes, mark)
        if self.person.get_gender() == Person.MALE:
            self.write_paragraph(self._("Male"))
        elif self.person.get_gender() == Person.FEMALE:
            self.write_paragraph(self._("Female"))
        else:
            self.write_paragraph(self._("Unknown"))
        self.write_paragraph(father, mark=fmark)
        self.write_paragraph(mother, mark=mmark)
        self.doc.end_cell()

        if p_style == 'IDS-PersonTable':
            self.doc.start_cell('IDS-NormalCell')
            self.doc.add_media(image_filename, "right", 4.0, 4.0,
                                      crop=media0.get_rectangle())
            endnotes = self._cite_endnote(media0)
            attr_list = media0.get_attribute_list()
            if len(attr_list) == 0:
                text = _('(image)')
            else:
                for attr in attr_list:
                    attr_type = attr.get_type().type2base()
                    # translators: needed for French, ignore otherwise
                    text = self._("%(str1)s: %(str2)s") % {
                                        'str1' : self._(attr_type),
                                        'str2' : attr.get_value() }
                    endnotes = self._cite_endnote(attr, prior=endnotes)
                    self.write_paragraph("(%s)" % text,
                                         endnotes=endnotes,
                                         style='IDS-ImageNote')
                    endnotes = ''
            if endnotes and len(attr_list) == 0:
                self.write_paragraph(text, endnotes=endnotes,
                                     style='IDS-ImageNote')
            self.doc.end_cell()

        self.doc.end_row()
        self.doc.end_table()

        self.doc.start_paragraph("IDS-Normal")
        self.doc.end_paragraph()

        self.write_alt_names()
        self.write_events()
        self.write_alt_parents()
        self.write_families()
        self.write_addresses()
        self.write_associations()
        self.write_attributes()
        self.write_LDS_ordinances()
        self.write_tags()
        self.write_images()
        self.write_note()
        if self.use_srcs:
            if self.use_pagebreak and self.bibli.get_citation_count():
                self.doc.page_break()
            Endnotes.write_endnotes(self.bibli, self._db, self.doc,
                                    printnotes=self.use_srcs_notes,
                                    elocale=self._locale)
Esempio n. 6
0
    def placepage(self, report, title, place_handle):
        """
        Create a place page

        @param: report            -- The instance of the main report class for
                                     this report
        @param: title             -- Is the title of the web page
        @param: place_handle -- The handle for the place to add
        """
        place = report.database.get_place_from_handle(place_handle)
        if not place:
            return
        BasePage.__init__(self, report, title, place.get_gramps_id())
        self.bibli = Bibliography()
        place_name = self.report.obj_dict[Place][place_handle][1]
        ldatec = place.get_change_time()

        output_file, sio = self.report.create_file(place_handle, "plc")
        self.uplink = True
        self.page_title = place_name
        placepage, head, body, outerwrapper = self.write_header(_("Places"))

        self.placemappages = self.report.options['placemappages']
        self.mapservice = self.report.options['mapservice']
        self.googlemapkey = self.report.options['googlemapkey']

        # begin PlaceDetail Division
        with Html("div", class_="content", id="PlaceDetail") as placedetail:
            outerwrapper += placedetail

            if self.create_media:
                media_list = place.get_media_list()
                thumbnail = self.disp_first_img_as_thumbnail(media_list, place)
                if thumbnail is not None:
                    placedetail += thumbnail

            # add section title
            placedetail += Html("h3", html_escape(place_name), inline=True)

            # begin summaryarea division and places table
            with Html("div", id='summaryarea') as summaryarea:
                placedetail += summaryarea

                with Html("table", class_="infolist place") as table:
                    summaryarea += table

                    # list the place fields
                    self.dump_place(place, table)

            # place gallery
            if self.create_media:
                placegallery = self.disp_add_img_as_gallery(media_list, place)
                if placegallery is not None:
                    placedetail += placegallery

            # place notes
            notelist = self.display_note_list(place.get_note_list())
            if notelist is not None:
                placedetail += notelist

            # place urls
            urllinks = self.display_url_list(place.get_url_list())
            if urllinks is not None:
                placedetail += urllinks

            # add place map here
            # Link to Gramps marker
            fname = "/".join(['images', 'marker.png'])
            marker_path = self.report.build_url_image("marker.png", "images",
                                                      self.uplink)

            if self.placemappages:
                if place and (place.lat and place.long):
                    latitude, longitude = conv_lat_lon(place.get_latitude(),
                                                       place.get_longitude(),
                                                       "D.D8")
                    placetitle = place_name

                    # add narrative-maps CSS...
                    fname = "/".join(["css", "narrative-maps.css"])
                    url = self.report.build_url_fname(fname, None, self.uplink)
                    head += Html("link",
                                 href=url,
                                 type="text/css",
                                 media="screen",
                                 rel="stylesheet")

                    # add MapService specific javascript code
                    src_js = GOOGLE_MAPS + "api/js?sensor=false"
                    if self.mapservice == "Google":
                        if self.googlemapkey:
                            src_js += "&key=" + self.googlemapkey
                        head += Html("script",
                                     type="text/javascript",
                                     src=src_js,
                                     inline=True)
                    else:
                        url = self.secure_mode
                        url += ("maxcdn.bootstrapcdn.com/bootstrap/3.3.7/"
                                "css/bootstrap.min.css")
                        head += Html("link",
                                     href=url,
                                     type="text/javascript",
                                     rel="stylesheet")
                        src_js = self.secure_mode
                        src_js += (
                            "ajax.googleapis.com/ajax/libs/jquery/1.9.1/"
                            "jquery.min.js")
                        head += Html("script",
                                     type="text/javascript",
                                     src=src_js,
                                     inline=True)
                        src_js = self.secure_mode
                        src_js += "openlayers.org/en/latest/build/ol.js"
                        head += Html("script",
                                     type="text/javascript",
                                     src=src_js,
                                     inline=True)
                        url = self.secure_mode
                        url += "openlayers.org/en/latest/css/ol.css"
                        head += Html("link",
                                     href=url,
                                     type="text/javascript",
                                     rel="stylesheet")
                        src_js = self.secure_mode
                        src_js += ("maxcdn.bootstrapcdn.com/bootstrap/3.3.7/"
                                   "js/bootstrap.min.js")
                        head += Html("script",
                                     type="text/javascript",
                                     src=src_js,
                                     inline=True)

                    # section title
                    placedetail += Html("h4", self._("Place Map"), inline=True)

                    # begin map_canvas division
                    with Html("div", id="map_canvas", inline=True) as canvas:
                        placedetail += canvas

                        # Begin inline javascript code because jsc is a
                        # docstring, it does NOT have to be properly indented
                        if self.mapservice == "Google":
                            with Html("script",
                                      type="text/javascript",
                                      indent=False) as jsc:
                                head += jsc

                                # Google adds Latitude/ Longitude to its maps...
                                plce = placetitle.replace("'", "\\'")
                                jsc += MARKER_PATH % marker_path
                                jsc += MARKERS % ([[
                                    plce, latitude, longitude, 1
                                ]], latitude, longitude, 10)

                        else:
                            # OpenStreetMap (OSM) adds Longitude/ Latitude
                            # to its maps, and needs a country code in
                            # lowercase letters...
                            with Html("script", type="text/javascript") as jsc:
                                canvas += jsc
                                #param1 = xml_lang()[3:5].lower()
                                jsc += MARKER_PATH % marker_path
                                jsc += OSM_MARKERS % ([[
                                    float(longitude),
                                    float(latitude), placetitle
                                ]], longitude, latitude, 10)

            # add javascript function call to body element
            body.attr += ' onload = "initialize();" '

            # add div for popups.
            with Html("div", id="popup", inline=True) as popup:
                placedetail += popup

            # source references
            srcrefs = self.display_ind_sources(place)
            if srcrefs is not None:
                placedetail += srcrefs

            # References list
            ref_list = self.display_bkref_list(Place, place_handle)
            if ref_list is not None:
                placedetail += ref_list

        # add clearline for proper styling
        # add footer section
        footer = self.write_footer(ldatec)
        outerwrapper += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.xhtml_writer(placepage, output_file, sio, ldatec)
Esempio n. 7
0
class MediaPages(BasePage):
    """
    This class is responsible for displaying information about the 'Media'
    database objects. It displays this information under the 'Individuals'
    tab. It is told by the 'add_instances' call which 'Media's to display,
    and remembers the list of persons. A single call to 'display_pages'
    displays both the Individual List (Index) page and all the Individual
    pages.

    The base class 'BasePage' is initialised once for each page that is
    displayed.
    """
    def __init__(self, report):
        """
        @param: report -- The instance of the main report class for this report
        """
        BasePage.__init__(self, report, title="")
        self.media_dict = defaultdict(set)
        self.unused_media_handles = []

    def display_pages(self, title):
        """
        Generate and output the pages under the Media tab, namely the media
        index and the individual media pages.

        @param: title -- Is the title of the web page
        """
        LOG.debug("obj_dict[Media]")
        for item in self.report.obj_dict[Media].items():
            LOG.debug("    %s", str(item))
        if self.create_unused_media:
            media_count = len(self.r_db.get_media_handles())
        else:
            media_count = len(self.report.obj_dict[Media])
        message = _("Creating media pages")
        with self.r_user.progress(_("Narrated Web Site Report"), message,
                                  media_count + 1
                                 ) as step:
            # bug 8950 : it seems it's better to sort on desc + gid.
            def sort_by_desc_and_gid(obj):
                """
                Sort by media description and gramps ID
                """
                return (obj.desc.lower(), obj.gramps_id)

            self.unused_media_handles = []
            if self.create_unused_media:
                # add unused media
                media_list = self.r_db.get_media_handles()
                for media_ref in media_list:
                    if media_ref not in self.report.obj_dict[Media]:
                        self.unused_media_handles.append(media_ref)
                self.unused_media_handles = sorted(
                    self.unused_media_handles,
                    key=lambda x: sort_by_desc_and_gid(
                        self.r_db.get_media_from_handle(x)))

            sorted_media_handles = sorted(
                self.report.obj_dict[Media].keys(),
                key=lambda x: sort_by_desc_and_gid(
                    self.r_db.get_media_from_handle(x)))
            prev = None
            total = len(sorted_media_handles)
            index = 1
            for handle in sorted_media_handles:
                gc.collect() # Reduce memory usage when there are many images.
                if index == media_count:
                    next_ = None
                elif index < total:
                    next_ = sorted_media_handles[index]
                elif len(self.unused_media_handles) > 0:
                    next_ = self.unused_media_handles[0]
                else:
                    next_ = None
                self.mediapage(self.report, title,
                               handle, (prev, next_, index, media_count))
                prev = handle
                step()
                index += 1

            total = len(self.unused_media_handles)
            idx = 1
            total_m = len(sorted_media_handles)
            prev = sorted_media_handles[total_m-1] if total_m > 0 else 0
            if total > 0:
                for media_handle in self.unused_media_handles:
                    media = self.r_db.get_media_from_handle(media_handle)
                    gc.collect() # Reduce memory usage when many images.
                    if index == media_count:
                        next_ = None
                    else:
                        next_ = self.unused_media_handles[idx]
                    self.mediapage(self.report, title,
                                   media_handle,
                                   (prev, next_, index, media_count))
                    prev = media_handle
                    step()
                    index += 1
                    idx += 1

        self.medialistpage(self.report, title, sorted_media_handles)

    def medialistpage(self, report, title, sorted_media_handles):
        """
        Generate and output the Media index page.

        @param: report               -- The instance of the main report class
                                        for this report
        @param: title                -- Is the title of the web page
        @param: sorted_media_handles -- A list of the handles of the media to be
                                        displayed sorted by the media title
        """
        BasePage.__init__(self, report, title)

        output_file, sio = self.report.create_file("media")
        # save the media file name in case we create unused media pages
        self.cur_fname = self.report.cur_fname
        medialistpage, head, body = self.write_header(self._('Media'))

        ldatec = 0
        # begin gallery division
        with Html("div", class_="content", id="Gallery") as medialist:
            body += medialist

            msg = self._("This page contains an index of all the media objects "
                         "in the database, sorted by their title. Clicking on "
                         "the title will take you to that "
                         "media object&#8217;s page.  "
                         "If you see media size dimensions "
                         "above an image, click on the "
                         "image to see the full sized version.  ")
            medialist += Html("p", msg, id="description")

            # begin gallery table and table head
            with Html("table",
                      class_="infolist primobjlist gallerylist") as table:
                medialist += table

                # begin table head
                thead = Html("thead")
                table += thead

                trow = Html("tr")
                thead += trow

                trow.extend(
                    Html("th", trans, class_=colclass, inline=True)
                    for trans, colclass in [("&nbsp;", "ColumnRowLabel"),
                                            (self._("Media | Name"),
                                             "ColumnName"),
                                            (self._("Date"), "ColumnDate"),
                                            (self._("Mime Type"), "ColumnMime")]
                )

                # begin table body
                tbody = Html("tbody")
                table += tbody

                index = 1
                if self.create_unused_media:
                    media_count = len(self.r_db.get_media_handles())
                else:
                    media_count = len(self.report.obj_dict[Media])
                message = _("Creating list of media pages")
                with self.r_user.progress(_("Narrated Web Site Report"),
                                          message, media_count + 1
                                 ) as step:
                    for media_handle in sorted_media_handles:
                        media = self.r_db.get_media_from_handle(media_handle)
                        if media:
                            if media.get_change_time() > ldatec:
                                ldatec = media.get_change_time()
                            title = media.get_description() or "[untitled]"

                            trow = Html("tr")
                            tbody += trow

                            media_data_row = [
                                [index, "ColumnRowLabel"],
                                [self.media_ref_link(media_handle,
                                                     title), "ColumnName"],
                                [self.rlocale.get_date(media.get_date_object()),
                                 "ColumnDate"],
                                [media.get_mime_type(), "ColumnMime"]]

                            trow.extend(
                                Html("td", data, class_=colclass)
                                for data, colclass in media_data_row
                            )
                        step()
                        index += 1

                    def sort_by_desc_and_gid(obj):
                        """
                        Sort by media description and gramps ID
                        """
                        return (obj.desc, obj.gramps_id)

                    idx = 1
                    prev = None
                    total = len(self.unused_media_handles)
                    if total > 0:
                        trow += Html("tr")
                        trow.extend(
                            Html("td", Html("h4", " "), inline=True) +
                            Html("td",
                                 Html("h4",
                                      self._("Below unused media objects"),
                                      inline=True),
                                 class_="") +
                            Html("td", Html("h4", " "), inline=True) +
                            Html("td", Html("h4", " "), inline=True)
                        )
                        for media_handle in self.unused_media_handles:
                            media = self.r_db.get_media_from_handle(media_handle)
                            gc.collect() # Reduce memory usage when many images.
                            if idx == total:
                                next_ = None
                            else:
                                self.unused_media_handles[idx]
                            trow += Html("tr")
                            media_data_row = [
                                [index, "ColumnRowLabel"],
                                [self.media_ref_link(media_handle,
                                                     media.get_description()),
                                 "ColumnName"],
                                [self.rlocale.get_date(media.get_date_object()),
                                 "ColumnDate"],
                                [media.get_mime_type(), "ColumnMime"]]
                            trow.extend(
                                Html("td", data, class_=colclass)
                                for data, colclass in media_data_row
                            )
                            prev = media_handle
                            step()
                            index += 1
                            idx += 1

        # add footer section
        # add clearline for proper styling
        footer = self.write_footer(ldatec)
        body += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.report.cur_fname = self.cur_fname
        self.xhtml_writer(medialistpage, output_file, sio, ldatec)

    def media_ref_link(self, handle, name, uplink=False):
        """
        Create a reference link to a media

        @param: handle -- The media handle
        @param: name   -- The name to use for the link
        @param: uplink -- If True, then "../../../" is inserted in front of the
                          result.
        """
        # get media url
        url = self.report.build_url_fname_html(handle, "img", uplink)

        # get name
        name = html_escape(name)

        # begin hyper link
        hyper = Html("a", name, href=url, title=name)

        # return hyperlink to its callers
        return hyper

    def mediapage(self, report, title, media_handle, info):
        """
        Generate and output an individual Media page.

        @param: report       -- The instance of the main report class
                                for this report
        @param: title        -- Is the title of the web page
        @param: media_handle -- The media handle to use
        @param: info         -- A tuple containing the media handle for the
                                next and previous media, the current page
                                number, and the total number of media pages
        """
        media = report.database.get_media_from_handle(media_handle)
        BasePage.__init__(self, report, title, media.gramps_id)
        (prev, next_, page_number, total_pages) = info

        ldatec = media.get_change_time()

        # get media rectangles
        _region_items = self.media_ref_rect_regions(media_handle)

        output_file, sio = self.report.create_file(media_handle, "img")
        self.uplink = True

        self.bibli = Bibliography()

        # get media type to be used primarily with "img" tags
        mime_type = media.get_mime_type()
        #mtype = get_description(mime_type)

        if mime_type:
            #note_only = False
            newpath = self.copy_source_file(media_handle, media)
            target_exists = newpath is not None
        else:
            #note_only = True
            target_exists = False

        self.copy_thumbnail(media_handle, media)
        self.page_title = media.get_description()
        esc_page_title = html_escape(self.page_title)
        (mediapage, head,
         body) = self.write_header("%s - %s" % (self._("Media"),
                                                self.page_title))

        # if there are media rectangle regions, attach behaviour style sheet
        if _region_items:

            fname = "/".join(["css", "behaviour.css"])
            url = self.report.build_url_fname(fname, None, self.uplink)
            head += Html("link", href=url, type="text/css",
                         media="screen", rel="stylesheet")

        # begin MediaDetail division
        with Html("div", class_="content", id="GalleryDetail") as mediadetail:
            body += mediadetail

            # media navigation
            with Html("div", id="GalleryNav", role="navigation") as medianav:
                mediadetail += medianav
                if prev:
                    medianav += self.media_nav_link(prev,
                                                    self._("Previous"), True)
                data = self._('%(strong1_strt)s%(page_number)d%(strong_end)s '
                              'of %(strong2_strt)s%(total_pages)d%(strong_end)s'
                             ) % {'strong1_strt' :
                                  '<strong id="GalleryCurrent">',
                                  'strong2_strt' : '<strong id="GalleryTotal">',
                                  'strong_end' : '</strong>',
                                  'page_number' : page_number,
                                  'total_pages' : total_pages}
                medianav += Html("span", data, id="GalleryPages")
                if next_:
                    medianav += self.media_nav_link(next_, self._("Next"), True)

            # missing media error message
            errormsg = self._("The file has been moved or deleted.")

            # begin summaryarea division
            with Html("div", id="summaryarea") as summaryarea:
                mediadetail += summaryarea
                if mime_type:
                    if mime_type.startswith("image"):
                        if not target_exists:
                            with Html("div", id="MediaDisplay") as mediadisplay:
                                summaryarea += mediadisplay
                                mediadisplay += Html("span", errormsg,
                                                     class_="MissingImage")

                        else:
                            # Check how big the image is relative to the
                            # requested 'initial' image size.
                            # If it's significantly bigger, scale it down to
                            # improve the site's responsiveness. We don't want
                            # the user to have to await a large download
                            # unnecessarily. Either way, set the display image
                            # size as requested.
                            orig_image_path = media_path_full(self.r_db,
                                                              media.get_path())
                            #mtime = os.stat(orig_image_path).st_mtime
                            (width, height) = image_size(orig_image_path)
                            max_width = self.report.options[
                                'maxinitialimagewidth']
                            max_height = self.report.options[
                                'maxinitialimageheight']
                            if width != 0 and height != 0:
                                scale_w = (float(max_width)/width) or 1
                                           # the 'or 1' is so that a max of
                                           # zero is ignored
                                scale_h = (float(max_height)/height) or 1
                            else:
                                scale_w = 1.0
                                scale_h = 1.0
                            scale = min(scale_w, scale_h, 1.0)
                            new_width = int(width*scale)
                            new_height = int(height*scale)

                            # TODO. Convert disk path to URL.
                            url = self.report.build_url_fname(orig_image_path,
                                                              None, self.uplink)
                            with Html("div", id="GalleryDisplay",
                                      style='width: %dpx; height: %dpx' % (
                                          new_width,
                                          new_height)) as mediadisplay:
                                summaryarea += mediadisplay

                                # Feature #2634; display the mouse-selectable
                                # regions. See the large block at the top of
                                # this function where the various regions are
                                # stored in _region_items
                                if _region_items:
                                    ordered = Html("ol", class_="RegionBox")
                                    mediadisplay += ordered
                                    while len(_region_items) > 0:
                                        (name, coord_x, coord_y,
                                         width, height, linkurl
                                        ) = _region_items.pop()
                                        ordered += Html(
                                            "li",
                                            style="left:%d%%; "
                                                  "top:%d%%; "
                                                  "width:%d%%; "
                                                  "height:%d%%;" % (
                                                      coord_x, coord_y,
                                                      width, height)) + (
                                                          Html("a", name,
                                                               href=linkurl)
                                                          )

                                # display the image
                                if orig_image_path != newpath:
                                    url = self.report.build_url_fname(
                                        newpath, None, self.uplink)
                                mediadisplay += Html("a", href=url) + (
                                    Html("img", width=new_width,
                                         height=new_height, src=url,
                                         alt=esc_page_title)
                                )
                    else:
                        dirname = tempfile.mkdtemp()
                        thmb_path = os.path.join(dirname, "document.png")
                        if run_thumbnailer(mime_type,
                                           media_path_full(self.r_db,
                                                           media.get_path()),
                                           thmb_path, 320):
                            try:
                                path = self.report.build_path(
                                    "preview", media.get_handle())
                                npath = os.path.join(path, media.get_handle())
                                npath += ".png"
                                self.report.copy_file(thmb_path, npath)
                                path = npath
                                os.unlink(thmb_path)
                            except EnvironmentError:
                                path = os.path.join("images", "document.png")
                        else:
                            path = os.path.join("images", "document.png")
                        os.rmdir(dirname)

                        with Html("div", id="GalleryDisplay") as mediadisplay:
                            summaryarea += mediadisplay

                            img_url = self.report.build_url_fname(path,
                                                                  None,
                                                                  self.uplink)
                            if target_exists:
                                # TODO. Convert disk path to URL
                                url = self.report.build_url_fname(newpath,
                                                                  None,
                                                                  self.uplink)
                                hyper = Html("a", href=url,
                                             title=esc_page_title) + (
                                                 Html("img", src=img_url,
                                                      alt=esc_page_title)
                                                 )
                                mediadisplay += hyper
                            else:
                                mediadisplay += Html("span", errormsg,
                                                     class_="MissingImage")
                else:
                    with Html("div", id="GalleryDisplay") as mediadisplay:
                        summaryarea += mediadisplay
                        url = self.report.build_url_image("document.png",
                                                          "images", self.uplink)
                        mediadisplay += Html("img", src=url,
                                             alt=esc_page_title,
                                             title=esc_page_title)

                # media title
                title = Html("h3", html_escape(self.page_title.strip()),
                             inline=True)
                summaryarea += title

                # begin media table
                with Html("table", class_="infolist gallery") as table:
                    summaryarea += table

                    # Gramps ID
                    media_gid = media.gramps_id
                    if not self.noid and media_gid:
                        trow = Html("tr") + (
                            Html("td", self._("Gramps ID"),
                                 class_="ColumnAttribute",
                                 inline=True),
                            Html("td", media_gid, class_="ColumnValue",
                                 inline=True)
                            )
                        table += trow

                    # mime type
                    if mime_type:
                        trow = Html("tr") + (
                            Html("td", self._("File Type"),
                                 class_="ColumnAttribute",
                                 inline=True),
                            Html("td", mime_type, class_="ColumnValue",
                                 inline=True)
                            )
                        table += trow

                    # media date
                    date = media.get_date_object()
                    if date and date is not Date.EMPTY:
                        trow = Html("tr") + (
                            Html("td", self._("Date"), class_="ColumnAttribute",
                                 inline=True),
                            Html("td", self.rlocale.get_date(date),
                                 class_="ColumnValue",
                                 inline=True)
                            )
                        table += trow

            # get media notes
            notelist = self.display_note_list(media.get_note_list())
            if notelist is not None:
                mediadetail += notelist

            # get attribute list
            attrlist = media.get_attribute_list()
            if attrlist:
                attrsection, attrtable = self.display_attribute_header()
                self.display_attr_list(attrlist, attrtable)
                mediadetail += attrsection

            # get media sources
            srclist = self.display_media_sources(media)
            if srclist is not None:
                mediadetail += srclist

            # get media references
            reflist = self.display_bkref_list(Media, media_handle)
            if reflist is not None:
                mediadetail += reflist

        # add clearline for proper styling
        # add footer section
        footer = self.write_footer(ldatec)
        body += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.xhtml_writer(mediapage, output_file, sio, ldatec)

    def media_nav_link(self, handle, name, uplink=False):
        """
        Creates the Media Page Navigation hyperlinks for Next and Prev
        """
        url = self.report.build_url_fname_html(handle, "img", uplink)
        name = html_escape(name)
        return Html("a", name, name=name, id=name, href=url,
                    title=name, inline=True)

    def display_media_sources(self, photo):
        """
        Display media sources

        @param: photo  -- The source object (image, pdf, ...)
        """
        list(map(
            lambda i: self.bibli.add_reference(
                self.r_db.get_citation_from_handle(i)),
            photo.get_citation_list()))
        sourcerefs = self.display_source_refs(self.bibli)

        # return source references to its caller
        return sourcerefs

    def copy_source_file(self, handle, photo):
        """
        Copy source file in the web tree.

        @param: handle -- Handle of the source
        @param: photo  -- The source object (image, pdf, ...)
        """
        ext = os.path.splitext(photo.get_path())[1]
        to_dir = self.report.build_path('images', handle)
        newpath = os.path.join(to_dir, handle) + ext

        fullpath = media_path_full(self.r_db, photo.get_path())
        if not os.path.isfile(fullpath):
            _WRONGMEDIAPATH.append([photo.get_gramps_id(), fullpath])
            return None
        try:
            mtime = os.stat(fullpath).st_mtime
            if self.report.archive:
                self.report.archive.add(fullpath, str(newpath))
            else:
                to_dir = os.path.join(self.html_dir, to_dir)
                if not os.path.isdir(to_dir):
                    os.makedirs(to_dir)
                new_file = os.path.join(self.html_dir, newpath)
                shutil.copyfile(fullpath, new_file)
                os.utime(new_file, (mtime, mtime))
            return newpath
        except (IOError, OSError) as msg:
            error = _("Missing media object:"
                     ) + "%s (%s)" % (photo.get_description(),
                                      photo.get_gramps_id())
            self.r_user.warn(error, str(msg))
            return None
Esempio n. 8
0
    def mediapage(self, report, title, media_handle, info):
        """
        Generate and output an individual Media page.

        @param: report       -- The instance of the main report class
                                for this report
        @param: title        -- Is the title of the web page
        @param: media_handle -- The media handle to use
        @param: info         -- A tuple containing the media handle for the
                                next and previous media, the current page
                                number, and the total number of media pages
        """
        media = report.database.get_media_from_handle(media_handle)
        BasePage.__init__(self, report, title, media.gramps_id)
        (prev, next_, page_number, total_pages) = info

        ldatec = media.get_change_time()

        # get media rectangles
        _region_items = self.media_ref_rect_regions(media_handle)

        output_file, sio = self.report.create_file(media_handle, "img")
        self.uplink = True

        self.bibli = Bibliography()

        # get media type to be used primarily with "img" tags
        mime_type = media.get_mime_type()
        #mtype = get_description(mime_type)

        if mime_type:
            #note_only = False
            newpath = self.copy_source_file(media_handle, media)
            target_exists = newpath is not None
        else:
            #note_only = True
            target_exists = False

        self.copy_thumbnail(media_handle, media)
        self.page_title = media.get_description()
        esc_page_title = html_escape(self.page_title)
        (mediapage, head,
         body) = self.write_header("%s - %s" % (self._("Media"),
                                                self.page_title))

        # if there are media rectangle regions, attach behaviour style sheet
        if _region_items:

            fname = "/".join(["css", "behaviour.css"])
            url = self.report.build_url_fname(fname, None, self.uplink)
            head += Html("link", href=url, type="text/css",
                         media="screen", rel="stylesheet")

        # begin MediaDetail division
        with Html("div", class_="content", id="GalleryDetail") as mediadetail:
            body += mediadetail

            # media navigation
            with Html("div", id="GalleryNav", role="navigation") as medianav:
                mediadetail += medianav
                if prev:
                    medianav += self.media_nav_link(prev,
                                                    self._("Previous"), True)
                data = self._('%(strong1_strt)s%(page_number)d%(strong_end)s '
                              'of %(strong2_strt)s%(total_pages)d%(strong_end)s'
                             ) % {'strong1_strt' :
                                  '<strong id="GalleryCurrent">',
                                  'strong2_strt' : '<strong id="GalleryTotal">',
                                  'strong_end' : '</strong>',
                                  'page_number' : page_number,
                                  'total_pages' : total_pages}
                medianav += Html("span", data, id="GalleryPages")
                if next_:
                    medianav += self.media_nav_link(next_, self._("Next"), True)

            # missing media error message
            errormsg = self._("The file has been moved or deleted.")

            # begin summaryarea division
            with Html("div", id="summaryarea") as summaryarea:
                mediadetail += summaryarea
                if mime_type:
                    if mime_type.startswith("image"):
                        if not target_exists:
                            with Html("div", id="MediaDisplay") as mediadisplay:
                                summaryarea += mediadisplay
                                mediadisplay += Html("span", errormsg,
                                                     class_="MissingImage")

                        else:
                            # Check how big the image is relative to the
                            # requested 'initial' image size.
                            # If it's significantly bigger, scale it down to
                            # improve the site's responsiveness. We don't want
                            # the user to have to await a large download
                            # unnecessarily. Either way, set the display image
                            # size as requested.
                            orig_image_path = media_path_full(self.r_db,
                                                              media.get_path())
                            #mtime = os.stat(orig_image_path).st_mtime
                            (width, height) = image_size(orig_image_path)
                            max_width = self.report.options[
                                'maxinitialimagewidth']
                            max_height = self.report.options[
                                'maxinitialimageheight']
                            if width != 0 and height != 0:
                                scale_w = (float(max_width)/width) or 1
                                           # the 'or 1' is so that a max of
                                           # zero is ignored
                                scale_h = (float(max_height)/height) or 1
                            else:
                                scale_w = 1.0
                                scale_h = 1.0
                            scale = min(scale_w, scale_h, 1.0)
                            new_width = int(width*scale)
                            new_height = int(height*scale)

                            # TODO. Convert disk path to URL.
                            url = self.report.build_url_fname(orig_image_path,
                                                              None, self.uplink)
                            with Html("div", id="GalleryDisplay",
                                      style='width: %dpx; height: %dpx' % (
                                          new_width,
                                          new_height)) as mediadisplay:
                                summaryarea += mediadisplay

                                # Feature #2634; display the mouse-selectable
                                # regions. See the large block at the top of
                                # this function where the various regions are
                                # stored in _region_items
                                if _region_items:
                                    ordered = Html("ol", class_="RegionBox")
                                    mediadisplay += ordered
                                    while len(_region_items) > 0:
                                        (name, coord_x, coord_y,
                                         width, height, linkurl
                                        ) = _region_items.pop()
                                        ordered += Html(
                                            "li",
                                            style="left:%d%%; "
                                                  "top:%d%%; "
                                                  "width:%d%%; "
                                                  "height:%d%%;" % (
                                                      coord_x, coord_y,
                                                      width, height)) + (
                                                          Html("a", name,
                                                               href=linkurl)
                                                          )

                                # display the image
                                if orig_image_path != newpath:
                                    url = self.report.build_url_fname(
                                        newpath, None, self.uplink)
                                mediadisplay += Html("a", href=url) + (
                                    Html("img", width=new_width,
                                         height=new_height, src=url,
                                         alt=esc_page_title)
                                )
                    else:
                        dirname = tempfile.mkdtemp()
                        thmb_path = os.path.join(dirname, "document.png")
                        if run_thumbnailer(mime_type,
                                           media_path_full(self.r_db,
                                                           media.get_path()),
                                           thmb_path, 320):
                            try:
                                path = self.report.build_path(
                                    "preview", media.get_handle())
                                npath = os.path.join(path, media.get_handle())
                                npath += ".png"
                                self.report.copy_file(thmb_path, npath)
                                path = npath
                                os.unlink(thmb_path)
                            except EnvironmentError:
                                path = os.path.join("images", "document.png")
                        else:
                            path = os.path.join("images", "document.png")
                        os.rmdir(dirname)

                        with Html("div", id="GalleryDisplay") as mediadisplay:
                            summaryarea += mediadisplay

                            img_url = self.report.build_url_fname(path,
                                                                  None,
                                                                  self.uplink)
                            if target_exists:
                                # TODO. Convert disk path to URL
                                url = self.report.build_url_fname(newpath,
                                                                  None,
                                                                  self.uplink)
                                hyper = Html("a", href=url,
                                             title=esc_page_title) + (
                                                 Html("img", src=img_url,
                                                      alt=esc_page_title)
                                                 )
                                mediadisplay += hyper
                            else:
                                mediadisplay += Html("span", errormsg,
                                                     class_="MissingImage")
                else:
                    with Html("div", id="GalleryDisplay") as mediadisplay:
                        summaryarea += mediadisplay
                        url = self.report.build_url_image("document.png",
                                                          "images", self.uplink)
                        mediadisplay += Html("img", src=url,
                                             alt=esc_page_title,
                                             title=esc_page_title)

                # media title
                title = Html("h3", html_escape(self.page_title.strip()),
                             inline=True)
                summaryarea += title

                # begin media table
                with Html("table", class_="infolist gallery") as table:
                    summaryarea += table

                    # Gramps ID
                    media_gid = media.gramps_id
                    if not self.noid and media_gid:
                        trow = Html("tr") + (
                            Html("td", self._("Gramps ID"),
                                 class_="ColumnAttribute",
                                 inline=True),
                            Html("td", media_gid, class_="ColumnValue",
                                 inline=True)
                            )
                        table += trow

                    # mime type
                    if mime_type:
                        trow = Html("tr") + (
                            Html("td", self._("File Type"),
                                 class_="ColumnAttribute",
                                 inline=True),
                            Html("td", mime_type, class_="ColumnValue",
                                 inline=True)
                            )
                        table += trow

                    # media date
                    date = media.get_date_object()
                    if date and date is not Date.EMPTY:
                        trow = Html("tr") + (
                            Html("td", self._("Date"), class_="ColumnAttribute",
                                 inline=True),
                            Html("td", self.rlocale.get_date(date),
                                 class_="ColumnValue",
                                 inline=True)
                            )
                        table += trow

            # get media notes
            notelist = self.display_note_list(media.get_note_list())
            if notelist is not None:
                mediadetail += notelist

            # get attribute list
            attrlist = media.get_attribute_list()
            if attrlist:
                attrsection, attrtable = self.display_attribute_header()
                self.display_attr_list(attrlist, attrtable)
                mediadetail += attrsection

            # get media sources
            srclist = self.display_media_sources(media)
            if srclist is not None:
                mediadetail += srclist

            # get media references
            reflist = self.display_bkref_list(Media, media_handle)
            if reflist is not None:
                mediadetail += reflist

        # add clearline for proper styling
        # add footer section
        footer = self.write_footer(ldatec)
        body += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.xhtml_writer(mediapage, output_file, sio, ldatec)
Esempio n. 9
0
    def familypage(self, report, title, family_handle):
        """
        Create a family page

        @param: report        -- The instance of the main report class for
                                 this report
        @param: title         -- Is the title of the web page
        @param: family_handle -- The handle for the family to add
        """
        family = report.database.get_family_from_handle(family_handle)
        if not family:
            return
        BasePage.__init__(self, report, title, family.get_gramps_id())
        ldatec = family.get_change_time()

        self.bibli = Bibliography()
        self.uplink = True
        family_name = self.report.get_family_name(family)
        self.page_title = family_name

        self.familymappages = report.options["familymappages"]

        output_file, sio = self.report.create_file(family.get_handle(), "fam")
        result = self.write_header(family_name)
        familydetailpage, dummy_head, dummy_body, outerwrapper = result

        # begin FamilyDetaill division
        with Html("div", class_="content",
                  id="RelationshipDetail") as relationshipdetail:
            outerwrapper += relationshipdetail

            # family media list for initial thumbnail
            if self.create_media:
                media_list = family.get_media_list()
                # If Event pages are not being created, then we need to display
                # the family event media here
                if not self.inc_events:
                    for evt_ref in family.get_event_ref_list():
                        event = self.r_db.get_event_from_handle(evt_ref.ref)
                        media_list += event.get_media_list()

            relationshipdetail += Html(
                "h2", self.page_title, inline=True) + (
                    Html('sup') + (Html('small') +
                                   self.get_citation_links(
                                       family.get_citation_list())))

            # display relationships
            families = self.display_family_relationships(family, None)
            if families is not None:
                relationshipdetail += families

            # display additional images as gallery
            if self.create_media and media_list:
                addgallery = self.disp_add_img_as_gallery(media_list, family)
                if addgallery:
                    relationshipdetail += addgallery

            # Narrative subsection
            notelist = family.get_note_list()
            if notelist:
                relationshipdetail += self.display_note_list(notelist, Family)

            # display family LDS ordinance...
            family_lds_ordinance_list = family.get_lds_ord_list()
            if family_lds_ordinance_list:
                relationshipdetail += self.display_lds_ordinance(family)

            # get attribute list
            attrlist = family.get_attribute_list()
            if attrlist:
                attrsection, attrtable = self.display_attribute_header()
                self.display_attr_list(attrlist, attrtable)
                relationshipdetail += attrsection

            # for use in family map pages...
            if self.report.options["familymappages"]:
                name_format = self.report.options['name_format']
                fhandle = mhandle = father = mother = None
                relationshipdetail += Html("h4", _("Family map"), inline=True)
                mapdetail = Html("br")
                fhandle = family.get_father_handle()
                for handle, dummy_url in self.report.fam_link.items():
                    if fhandle == handle:
                        father = self.r_db.get_person_from_handle(fhandle)
                        break
                if father:
                    primary_name = father.get_primary_name()
                    name = Name(primary_name)
                    name.set_display_as(name_format)
                    fname = html_escape(_nd.display_name(name))
                    mapdetail += self.family_map_link_for_parent(fhandle, fname)
                mapdetail += Html("br")
                mhandle = family.get_mother_handle()
                for handle, dummy_url in self.report.fam_link.items():
                    if mhandle == handle:
                        mother = self.r_db.get_person_from_handle(mhandle)
                        break
                if mother:
                    primary_name = mother.get_primary_name()
                    name = Name(primary_name)
                    name.set_display_as(name_format)
                    mname = html_escape(_nd.display_name(name))
                    mapdetail += self.family_map_link_for_parent(mhandle, mname)
                relationshipdetail += mapdetail

            # source references
            srcrefs = self.display_ind_sources(family)
            if srcrefs:
                relationshipdetail += srcrefs

        # add clearline for proper styling
        # add footer section
        footer = self.write_footer(ldatec)
        outerwrapper += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.xhtml_writer(familydetailpage, output_file, sio, ldatec)
Esempio n. 10
0
    def eventpage(self, report, title, event_handle):
        """
        Creates the individual event page

        @param: report       -- The instance of the main report class for
                                this report
        @param: title        -- Is the title of the web page
        @param: event_handle -- The event handle for the database
        """
        event = report.database.get_event_from_handle(event_handle)
        BasePage.__init__(self, report, title, event.get_gramps_id())
        if not event:
            return None

        ldatec = event.get_change_time()
        event_media_list = event.get_media_list()

        self.uplink = True
        subdirs = True
        evt_type = self._(event.get_type().xml_str())
        self.page_title = "%(eventtype)s" % {'eventtype': evt_type}
        self.bibli = Bibliography()

        output_file, sio = self.report.create_file(event_handle, "evt")
        eventpage, head, body = self.write_header(self._("Events"))

        # start event detail division
        with Html("div", class_="content", id="EventDetail") as eventdetail:
            body += eventdetail

            thumbnail = self.disp_first_img_as_thumbnail(
                event_media_list, event)
            if thumbnail is not None:
                eventdetail += thumbnail

            # display page title
            eventdetail += Html("h3", self.page_title, inline=True)

            # begin eventdetail table
            with Html("table", class_="infolist eventlist") as table:
                eventdetail += table

                tbody = Html("tbody")
                table += tbody

                evt_gid = event.get_gramps_id()
                if not self.noid and evt_gid:
                    trow = Html("tr") + (Html("td",
                                              self._("Gramps ID"),
                                              class_="ColumnAttribute",
                                              inline=True),
                                         Html("td",
                                              evt_gid,
                                              class_="ColumnGRAMPSID",
                                              inline=True))
                    tbody += trow

                # get event data
                #
                # for more information: see get_event_data()
                #
                event_data = self.get_event_data(event, event_handle, subdirs,
                                                 evt_gid)

                for (label, colclass, data) in event_data:
                    if data:
                        trow = Html("tr") + (Html(
                            "td", label, class_="ColumnAttribute", inline=True
                        ), Html('td', data, class_="Column" + colclass))
                        tbody += trow

            # Narrative subsection
            notelist = event.get_note_list()
            notelist = self.display_note_list(notelist)
            if notelist is not None:
                eventdetail += notelist

            # get attribute list
            attrlist = event.get_attribute_list()
            if attrlist:
                attrsection, attrtable = self.display_attribute_header()
                self.display_attr_list(attrlist, attrtable)
                eventdetail += attrsection

            # event source references
            srcrefs = self.display_ind_sources(event)
            if srcrefs is not None:
                eventdetail += srcrefs

            # display additional images as gallery
            if self.create_media:
                addgallery = self.disp_add_img_as_gallery(
                    event_media_list, event)
                if addgallery:
                    eventdetail += addgallery

            # References list
            ref_list = self.display_bkref_list(Event, event_handle)
            if ref_list is not None:
                eventdetail += ref_list

        # add clearline for proper styling
        # add footer section
        footer = self.write_footer(ldatec)
        body += (FULLCLEAR, footer)

        # send page out for processing
        # and close the page
        self.xhtml_writer(eventpage, output_file, sio, ldatec)
Esempio n. 11
0
class MediaPages(BasePage):
    """
    This class is responsible for displaying information about the 'Media'
    database objects. It displays this information under the 'Individuals'
    tab. It is told by the 'add_instances' call which 'Media's to display,
    and remembers the list of persons. A single call to 'display_pages'
    displays both the Individual List (Index) page and all the Individual
    pages.

    The base class 'BasePage' is initialised once for each page that is
    displayed.
    """
    def __init__(self, report):
        """
        @param: report -- The instance of the main report class for this report
        """
        BasePage.__init__(self, report, title="")
        self.media_dict = defaultdict(set)
        self.unused_media_handles = []
        self.cur_fname = None
        self.create_images_index = self.report.options['create_images_index']

    def display_pages(self, title):
        """
        Generate and output the pages under the Media tab, namely the media
        index and the individual media pages.

        @param: title -- Is the title of the web page
        """
        LOG.debug("obj_dict[Media]")
        for item in self.report.obj_dict[Media].items():
            LOG.debug("    %s", str(item))
        if self.create_unused_media:
            media_count = len(self.r_db.get_media_handles())
        else:
            media_count = len(self.report.obj_dict[Media])
        message = _("Creating media pages")
        with self.r_user.progress(_("Narrated Web Site Report"), message,
                                  media_count + 1) as step:
            # bug 8950 : it seems it's better to sort on desc + gid.
            def sort_by_desc_and_gid(obj):
                """
                Sort by media description and gramps ID
                """
                return (obj.desc.lower(), obj.gramps_id)

            self.unused_media_handles = []
            if self.create_unused_media:
                # add unused media
                media_list = self.r_db.get_media_handles()
                for media_ref in media_list:
                    if media_ref not in self.report.obj_dict[Media]:
                        self.unused_media_handles.append(media_ref)
                self.unused_media_handles = sorted(
                    self.unused_media_handles,
                    key=lambda x: sort_by_desc_and_gid(
                        self.r_db.get_media_from_handle(x)))

            sorted_media_handles = sorted(
                self.report.obj_dict[Media].keys(),
                key=lambda x: sort_by_desc_and_gid(
                    self.r_db.get_media_from_handle(x)))
            prev = None
            total = len(sorted_media_handles)
            index = 1
            for handle in sorted_media_handles:
                gc.collect()  # Reduce memory usage when there are many images.
                if index == media_count:
                    next_ = None
                elif index < total:
                    next_ = sorted_media_handles[index]
                elif self.unused_media_handles:
                    next_ = self.unused_media_handles[0]
                else:
                    next_ = None
                self.mediapage(self.report, title, handle,
                               (prev, next_, index, media_count))
                prev = handle
                step()
                index += 1

            total = len(self.unused_media_handles)
            idx = 1
            total_m = len(sorted_media_handles)
            prev = sorted_media_handles[total_m - 1] if total_m > 0 else 0
            if total > 0:
                for media_handle in self.unused_media_handles:
                    gc.collect()  # Reduce memory usage when many images.
                    if index == media_count:
                        next_ = None
                    else:
                        next_ = self.unused_media_handles[idx]
                    self.mediapage(self.report, title, media_handle,
                                   (prev, next_, index, media_count))
                    prev = media_handle
                    step()
                    index += 1
                    idx += 1

        self.medialistpage(self.report, title, sorted_media_handles)

    def medialistpage(self, report, title, sorted_media_handles):
        """
        Generate and output the Media index page.

        @param: report               -- The instance of the main report class
                                        for this report
        @param: title                -- Is the title of the web page
        @param: sorted_media_handles -- A list of the handles of the media to be
                                        displayed sorted by the media title
        """
        BasePage.__init__(self, report, title)

        if self.create_images_index:
            output_file, sio = self.report.create_file("media")
        # save the media file name in case we create unused media pages
        self.cur_fname = self.report.cur_fname
        result = self.write_header(self._('Media'))
        medialistpage, dummy_head, dummy_body, outerwrapper = result

        ldatec = 0
        # begin gallery division
        with Html("div", class_="content", id="Gallery") as medialist:
            outerwrapper += medialist

            msg = self._(
                "This page contains an index of all the media objects "
                "in the database, sorted by their title. Clicking on "
                "the title will take you to that "
                "media object&#8217;s page.  "
                "If you see media size dimensions "
                "above an image, click on the "
                "image to see the full sized version.  ")
            medialist += Html("p", msg, id="description")

            # begin gallery table and table head
            with Html("table",
                      class_="infolist primobjlist gallerylist") as table:
                medialist += table

                # begin table head
                thead = Html("thead")
                table += thead

                trow = Html("tr")
                thead += trow

                trow.extend(
                    Html("th", trans, class_=colclass, inline=True)
                    for trans, colclass in [(
                        "&nbsp;", "ColumnRowLabel"
                    ), (self._("Media | Name"),
                        "ColumnName"), (
                            self._("Date"),
                            "ColumnDate"), (self._("Mime Type"),
                                            "ColumnMime")])

                # begin table body
                tbody = Html("tbody")
                table += tbody

                index = 1
                if self.create_unused_media:
                    media_count = len(self.r_db.get_media_handles())
                else:
                    media_count = len(self.report.obj_dict[Media])
                message = _("Creating list of media pages")
                with self.r_user.progress(_("Narrated Web Site Report"),
                                          message, media_count + 1) as step:
                    for media_handle in sorted_media_handles:
                        media = self.r_db.get_media_from_handle(media_handle)
                        if media:
                            if media.get_change_time() > ldatec:
                                ldatec = media.get_change_time()
                            title = media.get_description() or "[untitled]"

                            trow = Html("tr")
                            tbody += trow

                            media_data_row = [
                                [index, "ColumnRowLabel"],
                                [
                                    self.media_ref_link(media_handle, title),
                                    "ColumnName"
                                ],
                                [
                                    self.rlocale.get_date(
                                        media.get_date_object()), "ColumnDate"
                                ], [media.get_mime_type(), "ColumnMime"]
                            ]

                            trow.extend(
                                Html("td", data, class_=colclass)
                                for data, colclass in media_data_row)
                        step()
                        index += 1

                    idx = 1
                    total = len(self.unused_media_handles)
                    if total > 0:
                        trow += Html("tr")
                        trow.extend(
                            Html("td", Html("h4", " "), inline=True) +
                            Html("td",
                                 Html("h4",
                                      self._("Below unused media objects"),
                                      inline=True),
                                 class_="") +
                            Html("td", Html("h4", " "), inline=True) +
                            Html("td", Html("h4", " "), inline=True))
                        for media_handle in self.unused_media_handles:
                            gmfh = self.r_db.get_media_from_handle
                            media = gmfh(media_handle)
                            gc.collect(
                            )  # Reduce memory usage when many images.
                            if idx != total:
                                self.unused_media_handles[idx]
                            trow += Html("tr")
                            media_data_row = [
                                [index, "ColumnRowLabel"],
                                [
                                    self.media_ref_link(
                                        media_handle, media.get_description()),
                                    "ColumnName"
                                ],
                                [
                                    self.rlocale.get_date(
                                        media.get_date_object()), "ColumnDate"
                                ], [media.get_mime_type(), "ColumnMime"]
                            ]
                            trow.extend(
                                Html("td", data, class_=colclass)
                                for data, colclass in media_data_row)
                            step()
                            index += 1
                            idx += 1

        # add footer section
        # add clearline for proper styling
        footer = self.write_footer(ldatec)
        outerwrapper += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.report.cur_fname = self.cur_fname
        if self.create_images_index:
            self.xhtml_writer(medialistpage, output_file, sio, ldatec)

    def media_ref_link(self, handle, name, uplink=False):
        """
        Create a reference link to a media

        @param: handle -- The media handle
        @param: name   -- The name to use for the link
        @param: uplink -- If True, then "../../../" is inserted in front of the
                          result.
        """
        # get media url
        url = self.report.build_url_fname_html(handle, "img", uplink)

        # get name
        name = html_escape(name)

        # begin hyper link
        hyper = Html("a", name, href=url, title=name)

        # return hyperlink to its callers
        return hyper

    def mediapage(self, report, title, media_handle, info):
        """
        Generate and output an individual Media page.

        @param: report       -- The instance of the main report class
                                for this report
        @param: title        -- Is the title of the web page
        @param: media_handle -- The media handle to use
        @param: info         -- A tuple containing the media handle for the
                                next and previous media, the current page
                                number, and the total number of media pages
        """
        media = report.database.get_media_from_handle(media_handle)
        BasePage.__init__(self, report, title, media.gramps_id)
        (prev, next_, page_number, total_pages) = info

        ldatec = media.get_change_time()

        # get media rectangles
        _region_items = self.media_ref_rect_regions(media_handle)

        output_file, sio = self.report.create_file(media_handle, "img")
        self.uplink = True

        self.bibli = Bibliography()

        # get media type to be used primarily with "img" tags
        mime_type = media.get_mime_type()

        if mime_type:
            newpath = self.copy_source_file(media_handle, media)
            target_exists = newpath is not None
        else:
            target_exists = False

        self.copy_thumbnail(media_handle, media)
        self.page_title = media.get_description()
        esc_page_title = html_escape(self.page_title)
        result = self.write_header("%s - %s" %
                                   (self._("Media"), self.page_title))
        mediapage, head, dummy_body, outerwrapper = result

        # if there are media rectangle regions, attach behaviour style sheet
        if _region_items:

            fname = "/".join(["css", "behaviour.css"])
            url = self.report.build_url_fname(fname, None, self.uplink)
            head += Html("link",
                         href=url,
                         type="text/css",
                         media="screen",
                         rel="stylesheet")

        # begin MediaDetail division
        with Html("div", class_="content", id="GalleryDetail") as mediadetail:
            outerwrapper += mediadetail

            # media navigation
            with Html("div", id="GalleryNav", role="navigation") as medianav:
                mediadetail += medianav
                if prev:
                    medianav += self.media_nav_link(prev, self._("Previous"),
                                                    True)
                data = self._(
                    '%(strong1_strt)s%(page_number)d%(strong_end)s '
                    'of %(strong2_strt)s%(total_pages)d%(strong_end)s') % {
                        'strong1_strt': '<strong id="GalleryCurrent">',
                        'strong2_strt': '<strong id="GalleryTotal">',
                        'strong_end': '</strong>',
                        'page_number': page_number,
                        'total_pages': total_pages
                    }
                medianav += Html("span", data, id="GalleryPages")
                if next_:
                    medianav += self.media_nav_link(next_, self._("Next"),
                                                    True)

            # missing media error message
            errormsg = self._("The file has been moved or deleted.")

            # begin summaryarea division
            with Html("div", id="summaryarea") as summaryarea:
                mediadetail += summaryarea
                if mime_type:
                    if mime_type.startswith("image"):
                        if not target_exists:
                            with Html("div",
                                      id="MediaDisplay") as mediadisplay:
                                summaryarea += mediadisplay
                                mediadisplay += Html("span",
                                                     errormsg,
                                                     class_="MissingImage")

                        else:
                            # Check how big the image is relative to the
                            # requested 'initial' image size.
                            # If it's significantly bigger, scale it down to
                            # improve the site's responsiveness. We don't want
                            # the user to have to await a large download
                            # unnecessarily. Either way, set the display image
                            # size as requested.
                            orig_image_path = media_path_full(
                                self.r_db, media.get_path())
                            (width, height) = image_size(orig_image_path)
                            max_width = self.report.options[
                                'maxinitialimagewidth']

                            # TODO. Convert disk path to URL.
                            url = self.report.build_url_fname(
                                orig_image_path, None, self.uplink)
                            with Html("div",
                                      id="GalleryDisplay",
                                      style='max-width: %dpx; height: auto' %
                                      (max_width)) as mediadisplay:
                                summaryarea += mediadisplay

                                # Feature #2634; display the mouse-selectable
                                # regions. See the large block at the top of
                                # this function where the various regions are
                                # stored in _region_items
                                if _region_items:
                                    ordered = Html("ol", class_="RegionBox")
                                    mediadisplay += ordered
                                    while _region_items:
                                        (name, coord_x, coord_y, width, height,
                                         linkurl) = _region_items.pop()
                                        ordered += Html(
                                            "li",
                                            style="left:%d%%; "
                                            "top:%d%%; "
                                            "width:%d%%; "
                                            "height:%d%%;" %
                                            (coord_x, coord_y, width, height)
                                        ) + (Html("a", name, href=linkurl))

                                # display the image
                                if orig_image_path != newpath:
                                    url = self.report.build_url_fname(
                                        newpath, None, self.uplink)
                                s_width = 'width: %dpx;' % max_width
                                mediadisplay += Html("a", href=url) + (Html(
                                    "img",
                                    src=url,
                                    style=s_width,
                                    alt=esc_page_title))
                    else:
                        dirname = tempfile.mkdtemp()
                        thmb_path = os.path.join(dirname, "document.png")
                        if run_thumbnailer(
                                mime_type,
                                media_path_full(self.r_db, media.get_path()),
                                thmb_path, 320):
                            try:
                                path = self.report.build_path(
                                    "preview", media.get_handle())
                                npath = os.path.join(path, media.get_handle())
                                npath += ".png"
                                self.report.copy_file(thmb_path, npath)
                                path = npath
                                os.unlink(thmb_path)
                            except EnvironmentError:
                                path = os.path.join("images", "document.png")
                        else:
                            path = os.path.join("images", "document.png")
                        os.rmdir(dirname)

                        with Html("div", id="GalleryDisplay") as mediadisplay:
                            summaryarea += mediadisplay

                            img_url = self.report.build_url_fname(
                                path, None, self.uplink)
                            if target_exists:
                                # TODO. Convert disk path to URL
                                url = self.report.build_url_fname(
                                    newpath, None, self.uplink)
                                s_width = 'width: 48px;'
                                hyper = Html(
                                    "a", href=url, title=esc_page_title) + (
                                        Html("img",
                                             src=img_url,
                                             style=s_width,
                                             alt=esc_page_title))
                                mediadisplay += hyper
                            else:
                                mediadisplay += Html("span",
                                                     errormsg,
                                                     class_="MissingImage")
                else:
                    with Html("div", id="GalleryDisplay") as mediadisplay:
                        summaryarea += mediadisplay
                        url = self.report.build_url_image(
                            "document.png", "images", self.uplink)
                        s_width = 'width: 48px;'
                        mediadisplay += Html("img",
                                             src=url,
                                             style=s_width,
                                             alt=esc_page_title,
                                             title=esc_page_title)

                # media title
                title = Html("h3",
                             html_escape(self.page_title.strip()),
                             inline=True)
                summaryarea += title

                # begin media table
                with Html("table", class_="infolist gallery") as table:
                    summaryarea += table

                    # Gramps ID
                    media_gid = media.gramps_id
                    if not self.noid and media_gid:
                        trow = Html("tr") + (Html("td",
                                                  self._("Gramps ID"),
                                                  class_="ColumnAttribute",
                                                  inline=True),
                                             Html("td",
                                                  media_gid,
                                                  class_="ColumnValue",
                                                  inline=True))
                        table += trow

                    # mime type
                    if mime_type:
                        trow = Html("tr") + (Html("td",
                                                  self._("File Type"),
                                                  class_="ColumnAttribute",
                                                  inline=True),
                                             Html("td",
                                                  mime_type,
                                                  class_="ColumnValue",
                                                  inline=True))
                        table += trow

                    # media date
                    date = media.get_date_object()
                    if date and date is not Date.EMPTY:
                        trow = Html("tr") + (Html("td",
                                                  self._("Date"),
                                                  class_="ColumnAttribute",
                                                  inline=True),
                                             Html("td",
                                                  self.rlocale.get_date(date),
                                                  class_="ColumnValue",
                                                  inline=True))
                        table += trow

            # get media notes
            notelist = self.display_note_list(media.get_note_list(), Media)
            if notelist is not None:
                mediadetail += notelist

            # get attribute list
            attrlist = media.get_attribute_list()
            if attrlist:
                attrsection, attrtable = self.display_attribute_header()
                self.display_attr_list(attrlist, attrtable)
                mediadetail += attrsection

            # get media sources
            srclist = self.display_media_sources(media)
            if srclist is not None:
                mediadetail += srclist

            # get media references
            reflist = self.display_bkref_list(Media, media_handle)
            if reflist is not None:
                mediadetail += reflist

        # add clearline for proper styling
        # add footer section
        footer = self.write_footer(ldatec)
        outerwrapper += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.xhtml_writer(mediapage, output_file, sio, ldatec)

    def media_nav_link(self, handle, name, uplink=False):
        """
        Creates the Media Page Navigation hyperlinks for Next and Prev
        """
        url = self.report.build_url_fname_html(handle, "img", uplink)
        name = html_escape(name)
        return Html("a",
                    name,
                    name=name,
                    id=name,
                    href=url,
                    title=name,
                    inline=True)

    def display_media_sources(self, photo):
        """
        Display media sources

        @param: photo  -- The source object (image, pdf, ...)
        """
        list(
            map(
                lambda i: self.bibli.add_reference(
                    self.r_db.get_citation_from_handle(i)),
                photo.get_citation_list()))
        sourcerefs = self.display_source_refs(self.bibli)

        # return source references to its caller
        return sourcerefs

    def copy_source_file(self, handle, photo):
        """
        Copy source file in the web tree.

        @param: handle -- Handle of the source
        @param: photo  -- The source object (image, pdf, ...)
        """
        ext = os.path.splitext(photo.get_path())[1]
        to_dir = self.report.build_path('images', handle)
        newpath = os.path.join(to_dir, handle) + ext

        fullpath = media_path_full(self.r_db, photo.get_path())
        if not os.path.isfile(fullpath):
            _WRONGMEDIAPATH.append([photo.get_gramps_id(), fullpath])
            return None
        try:
            mtime = os.stat(fullpath).st_mtime
            if self.report.archive:
                if str(newpath) not in self.report.archive.getnames():
                    # The current file not already archived.
                    self.report.archive.add(fullpath, str(newpath))
            else:
                to_dir = os.path.join(self.html_dir, to_dir)
                if not os.path.isdir(to_dir):
                    os.makedirs(to_dir)
                new_file = os.path.join(self.html_dir, newpath)
                shutil.copyfile(fullpath, new_file)
                os.utime(new_file, (mtime, mtime))
            return newpath
        except (IOError, OSError) as msg:
            error = _("Missing media object:") + "%s (%s)" % (
                photo.get_description(), photo.get_gramps_id())
            self.r_user.warn(error, str(msg))
            return None
Esempio n. 12
0
    def mediapage(self, report, title, media_handle, info):
        """
        Generate and output an individual Media page.

        @param: report       -- The instance of the main report class
                                for this report
        @param: title        -- Is the title of the web page
        @param: media_handle -- The media handle to use
        @param: info         -- A tuple containing the media handle for the
                                next and previous media, the current page
                                number, and the total number of media pages
        """
        media = report.database.get_media_from_handle(media_handle)
        BasePage.__init__(self, report, title, media.gramps_id)
        (prev, next_, page_number, total_pages) = info

        ldatec = media.get_change_time()

        # get media rectangles
        _region_items = self.media_ref_rect_regions(media_handle)

        output_file, sio = self.report.create_file(media_handle, "img")
        self.uplink = True

        self.bibli = Bibliography()

        # get media type to be used primarily with "img" tags
        mime_type = media.get_mime_type()

        if mime_type:
            newpath = self.copy_source_file(media_handle, media)
            target_exists = newpath is not None
        else:
            target_exists = False

        self.copy_thumbnail(media_handle, media)
        self.page_title = media.get_description()
        esc_page_title = html_escape(self.page_title)
        result = self.write_header("%s - %s" %
                                   (self._("Media"), self.page_title))
        mediapage, head, dummy_body, outerwrapper = result

        # if there are media rectangle regions, attach behaviour style sheet
        if _region_items:

            fname = "/".join(["css", "behaviour.css"])
            url = self.report.build_url_fname(fname, None, self.uplink)
            head += Html("link",
                         href=url,
                         type="text/css",
                         media="screen",
                         rel="stylesheet")

        # begin MediaDetail division
        with Html("div", class_="content", id="GalleryDetail") as mediadetail:
            outerwrapper += mediadetail

            # media navigation
            with Html("div", id="GalleryNav", role="navigation") as medianav:
                mediadetail += medianav
                if prev:
                    medianav += self.media_nav_link(prev, self._("Previous"),
                                                    True)
                data = self._(
                    '%(strong1_strt)s%(page_number)d%(strong_end)s '
                    'of %(strong2_strt)s%(total_pages)d%(strong_end)s') % {
                        'strong1_strt': '<strong id="GalleryCurrent">',
                        'strong2_strt': '<strong id="GalleryTotal">',
                        'strong_end': '</strong>',
                        'page_number': page_number,
                        'total_pages': total_pages
                    }
                medianav += Html("span", data, id="GalleryPages")
                if next_:
                    medianav += self.media_nav_link(next_, self._("Next"),
                                                    True)

            # missing media error message
            errormsg = self._("The file has been moved or deleted.")

            # begin summaryarea division
            with Html("div", id="summaryarea") as summaryarea:
                mediadetail += summaryarea
                if mime_type:
                    if mime_type.startswith("image"):
                        if not target_exists:
                            with Html("div",
                                      id="MediaDisplay") as mediadisplay:
                                summaryarea += mediadisplay
                                mediadisplay += Html("span",
                                                     errormsg,
                                                     class_="MissingImage")

                        else:
                            # Check how big the image is relative to the
                            # requested 'initial' image size.
                            # If it's significantly bigger, scale it down to
                            # improve the site's responsiveness. We don't want
                            # the user to have to await a large download
                            # unnecessarily. Either way, set the display image
                            # size as requested.
                            orig_image_path = media_path_full(
                                self.r_db, media.get_path())
                            (width, height) = image_size(orig_image_path)
                            max_width = self.report.options[
                                'maxinitialimagewidth']

                            # TODO. Convert disk path to URL.
                            url = self.report.build_url_fname(
                                orig_image_path, None, self.uplink)
                            with Html("div",
                                      id="GalleryDisplay",
                                      style='max-width: %dpx; height: auto' %
                                      (max_width)) as mediadisplay:
                                summaryarea += mediadisplay

                                # Feature #2634; display the mouse-selectable
                                # regions. See the large block at the top of
                                # this function where the various regions are
                                # stored in _region_items
                                if _region_items:
                                    ordered = Html("ol", class_="RegionBox")
                                    mediadisplay += ordered
                                    while _region_items:
                                        (name, coord_x, coord_y, width, height,
                                         linkurl) = _region_items.pop()
                                        ordered += Html(
                                            "li",
                                            style="left:%d%%; "
                                            "top:%d%%; "
                                            "width:%d%%; "
                                            "height:%d%%;" %
                                            (coord_x, coord_y, width, height)
                                        ) + (Html("a", name, href=linkurl))

                                # display the image
                                if orig_image_path != newpath:
                                    url = self.report.build_url_fname(
                                        newpath, None, self.uplink)
                                s_width = 'width: %dpx;' % max_width
                                mediadisplay += Html("a", href=url) + (Html(
                                    "img",
                                    src=url,
                                    style=s_width,
                                    alt=esc_page_title))
                    else:
                        dirname = tempfile.mkdtemp()
                        thmb_path = os.path.join(dirname, "document.png")
                        if run_thumbnailer(
                                mime_type,
                                media_path_full(self.r_db, media.get_path()),
                                thmb_path, 320):
                            try:
                                path = self.report.build_path(
                                    "preview", media.get_handle())
                                npath = os.path.join(path, media.get_handle())
                                npath += ".png"
                                self.report.copy_file(thmb_path, npath)
                                path = npath
                                os.unlink(thmb_path)
                            except EnvironmentError:
                                path = os.path.join("images", "document.png")
                        else:
                            path = os.path.join("images", "document.png")
                        os.rmdir(dirname)

                        with Html("div", id="GalleryDisplay") as mediadisplay:
                            summaryarea += mediadisplay

                            img_url = self.report.build_url_fname(
                                path, None, self.uplink)
                            if target_exists:
                                # TODO. Convert disk path to URL
                                url = self.report.build_url_fname(
                                    newpath, None, self.uplink)
                                s_width = 'width: 48px;'
                                hyper = Html(
                                    "a", href=url, title=esc_page_title) + (
                                        Html("img",
                                             src=img_url,
                                             style=s_width,
                                             alt=esc_page_title))
                                mediadisplay += hyper
                            else:
                                mediadisplay += Html("span",
                                                     errormsg,
                                                     class_="MissingImage")
                else:
                    with Html("div", id="GalleryDisplay") as mediadisplay:
                        summaryarea += mediadisplay
                        url = self.report.build_url_image(
                            "document.png", "images", self.uplink)
                        s_width = 'width: 48px;'
                        mediadisplay += Html("img",
                                             src=url,
                                             style=s_width,
                                             alt=esc_page_title,
                                             title=esc_page_title)

                # media title
                title = Html("h3",
                             html_escape(self.page_title.strip()),
                             inline=True)
                summaryarea += title

                # begin media table
                with Html("table", class_="infolist gallery") as table:
                    summaryarea += table

                    # Gramps ID
                    media_gid = media.gramps_id
                    if not self.noid and media_gid:
                        trow = Html("tr") + (Html("td",
                                                  self._("Gramps ID"),
                                                  class_="ColumnAttribute",
                                                  inline=True),
                                             Html("td",
                                                  media_gid,
                                                  class_="ColumnValue",
                                                  inline=True))
                        table += trow

                    # mime type
                    if mime_type:
                        trow = Html("tr") + (Html("td",
                                                  self._("File Type"),
                                                  class_="ColumnAttribute",
                                                  inline=True),
                                             Html("td",
                                                  mime_type,
                                                  class_="ColumnValue",
                                                  inline=True))
                        table += trow

                    # media date
                    date = media.get_date_object()
                    if date and date is not Date.EMPTY:
                        trow = Html("tr") + (Html("td",
                                                  self._("Date"),
                                                  class_="ColumnAttribute",
                                                  inline=True),
                                             Html("td",
                                                  self.rlocale.get_date(date),
                                                  class_="ColumnValue",
                                                  inline=True))
                        table += trow

            # get media notes
            notelist = self.display_note_list(media.get_note_list(), Media)
            if notelist is not None:
                mediadetail += notelist

            # get attribute list
            attrlist = media.get_attribute_list()
            if attrlist:
                attrsection, attrtable = self.display_attribute_header()
                self.display_attr_list(attrlist, attrtable)
                mediadetail += attrsection

            # get media sources
            srclist = self.display_media_sources(media)
            if srclist is not None:
                mediadetail += srclist

            # get media references
            reflist = self.display_bkref_list(Media, media_handle)
            if reflist is not None:
                mediadetail += reflist

        # add clearline for proper styling
        # add footer section
        footer = self.write_footer(ldatec)
        outerwrapper += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        self.xhtml_writer(mediapage, output_file, sio, ldatec)
Esempio n. 13
0
    def __init__(self, database, options, user):
        """
        Create the DetDescendantReport 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.

        gen           - Maximum number of generations to include.
        inc_id        - Whether to include Gramps IDs
        pagebgg       - Whether to include page breaks between generations.
        pageben       - Whether to include page break before End Notes.
        fulldates     - Whether to use full dates instead of just year.
        listc         - Whether to list children.
        list_children_spouses - Whether to list the spouses of the children
        incnotes      - Whether to include notes.
        usecall       - Whether to use the call name as the first name.
        repplace      - Whether to replace missing Places with ___________.
        repdate       - Whether to replace missing Dates with ___________.
        computeage    - Whether to compute age.
        verbose       - Whether to use complete sentences.
        numbering     - The descendancy numbering system to be utilized.
        desref        - Whether to add descendant references in child list.
        incphotos     - Whether to include images.
        incnames      - Whether to include other names.
        incevents     - Whether to include events.
        incaddresses  - Whether to include addresses.
        incsrcnotes   - Whether to include source notes in the Endnotes
                            section. Only works if Include sources is selected.
        incmates      - Whether to include information about spouses
        incattrs      - Whether to include attributes
        incpaths      - Whether to include the path of descendancy
                            from the start-person to each descendant.
        incssign      - Whether to include a sign ('+') before the
                            descendant number in the child-list
                            to indicate a child has succession.
        pid           - The Gramps ID of the center person for the report.
        name_format   - Preferred format to display names
        incmateref    - Whether to print mate information or reference
        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
        structure     - How to structure the report
        """
        Report.__init__(self, database, options, user)

        self.map = {}
        self._user = user

        menu = options.menu
        get_option_by_name = menu.get_option_by_name
        get_value = lambda name: get_option_by_name(name).get_value()

        self.set_locale(get_value('trans'))

        stdoptions.run_date_format_option(self, menu)

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

        self.max_generations = get_value('gen')
        self.pgbrk = get_value('pagebbg')
        self.pgbrkenotes = get_value('pageben')
        self.fulldate = get_value('fulldates')
        use_fulldate = self.fulldate
        self.listchildren = get_value('listc')
        self.list_children_spouses = get_value('listc_spouses')
        self.inc_notes = get_value('incnotes')
        use_call = get_value('usecall')
        blankplace = get_value('repplace')
        blankdate = get_value('repdate')
        self.calcageflag = get_value('computeage')
        self.verbose = get_value('verbose')
        self.numbering = get_value('numbering')
        self.childref = get_value('desref')
        self.addimages = get_value('incphotos')
        self.structure = get_value('structure')
        self.inc_names = get_value('incnames')
        self.inc_events = get_value('incevents')
        self.inc_addr = get_value('incaddresses')
        self.inc_sources = get_value('incsources')
        self.inc_srcnotes = get_value('incsrcnotes')
        self.inc_mates = get_value('incmates')
        self.inc_attrs = get_value('incattrs')
        self.inc_paths = get_value('incpaths')
        self.inc_ssign = get_value('incssign')
        self.inc_materef = get_value('incmateref')
        self.want_ids = get_value('inc_id')

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

        self.gen_handles = {}
        self.prev_gen_handles = {}
        self.gen_keys = []
        self.dnumber = {}
        self.dmates = {}
        self.numbers_printed = list()

        if blankdate:
            empty_date = EMPTY_ENTRY
        else:
            empty_date = ""

        if blankplace:
            empty_place = EMPTY_ENTRY
        else:
            empty_place = ""

        stdoptions.run_name_format_option(self, menu)

        self.__narrator = Narrator(self._db, self.verbose,
                                   use_call, use_fulldate,
                                   empty_date, empty_place,
                                   nlocale=self._locale,
                                   get_endnote_numbers=self.endnotes)

        self.bibli = Bibliography(Bibliography.MODE_DATE|Bibliography.MODE_PAGE)
Esempio n. 14
0
    def placepage(self, report, the_lang, the_title, place_handle, place_name):
        """
        Create a place page

        @param: report       -- The instance of the main report class
                                for this report
        @param: the_lang     -- The lang to process
        @param: the_title    -- The title page related to the language
        @param: place_handle -- The handle for the place to add
        @param: place_name   -- The alternate place name
        """
        place = report.database.get_place_from_handle(place_handle)
        if not place:
            return
        BasePage.__init__(self, report, the_lang, the_title,
                          place.get_gramps_id())
        self.bibli = Bibliography()
        ldatec = place.get_change_time()
        apname = _pd.display(self.r_db, place)

        if place_name == apname: # store only the primary named page
            output_file, sio = self.report.create_file(place_handle, "plc")
        self.uplink = True
        self.page_title = place_name
        (placepage, head, dummy_body,
         outerwrapper) = self.write_header(_("Places"))

        self.placemappages = self.report.options['placemappages']
        self.mapservice = self.report.options['mapservice']
        self.googlemapkey = self.report.options['googlemapkey']
        self.stamenopts = self.report.options['stamenopts']

        # begin PlaceDetail Division
        with Html("div", class_="content", id="PlaceDetail") as placedetail:
            outerwrapper += placedetail

            media_list = place.get_media_list()
            if self.create_media:
                thumbnail = self.disp_first_img_as_thumbnail(media_list,
                                                             place)
                if thumbnail is not None:
                    if media_list[0].ref in self.report.obj_dict[Media]:
                        placedetail += thumbnail

            # add section title
            placedetail += Html("h3",
                                html_escape(place_name),
                                inline=True)

            # begin summaryarea division and places table
            with Html("div", id='summaryarea') as summaryarea:
                placedetail += summaryarea

                with Html("table", class_="infolist place") as table:
                    summaryarea += table

                    # list the place fields
                    self.dump_place(place, table)

            # place gallery
            if self.create_media and not self.report.options['inc_uplaces']:
                # Don't diplay media for unused places. It generates
                # "page not found" if they are not collected in pass 1.
                placegallery = self.disp_add_img_as_gallery(media_list, place)
                if placegallery is not None:
                    placedetail += placegallery

            # place notes
            notelist = self.display_note_list(place.get_note_list(), Place)
            if notelist is not None:
                placedetail += notelist

            # place urls
            urllinks = self.display_url_list(place.get_url_list())
            if urllinks is not None:
                placedetail += urllinks

            # add place map here
            # Link to Gramps marker
            fname = "/".join(['images', 'marker.png'])
            marker_path = self.report.build_url_image("marker.png",
                                                      "images", self.uplink)

            if self.placemappages:
                if place and (place.lat and place.long):
                    placetitle = place_name

                    # add narrative-maps CSS...
                    if the_lang and not self.usecms:
                        fname = "/".join(["..", "css", "narrative-maps.css"])
                    else:
                        fname = "/".join(["css", "narrative-maps.css"])
                    url = self.report.build_url_fname(fname, None, self.uplink)
                    head += Html("link", href=url, type="text/css",
                                 media="screen", rel="stylesheet")

                    # add MapService specific javascript code
                    src_js = GOOGLE_MAPS + "api/js"
                    if self.mapservice == "Google":
                        if self.googlemapkey:
                            src_js += "?key=" + self.googlemapkey
                        head += Html("script", type="text/javascript",
                                     src=src_js, inline=True)
                    else: # OpenStreetMap, Stamen...
                        src_js = self.secure_mode
                        src_js += ("ajax.googleapis.com/ajax/libs/jquery/1.9.1/"
                                   "jquery.min.js")
                        head += Html("script", type="text/javascript",
                                     src=src_js, inline=True)
                        src_js = "https://openlayers.org/en/latest/build/ol.js"
                        head += Html("script", type="text/javascript",
                                     src=src_js, inline=True)
                        url = "https://openlayers.org/en/latest/css/ol.css"
                        head += Html("link", href=url, type="text/css",
                                     rel="stylesheet")

                    # section title
                    placedetail += Html("h4", self._("Place Map"), inline=True)

                    # begin map_canvas division
                    with Html("div", id="map_canvas", inline=True) as canvas:
                        placedetail += canvas

            # add div for popups.
            if self.mapservice == "Google":
                with Html("div", id="popup", inline=True) as popup:
                    placedetail += popup
            else:
                with Html("div", id="popup", class_="ol-popup",
                          inline=True) as popup:
                    placedetail += popup
                    popup += Html("a", href="#", id="popup-closer",
                                  class_="ol-popup-closer")
                    popup += Html("div", id="popup-title",
                                  class_="ol-popup-title")
                    popup += Html("div", id="popup-content")
                with Html("div", id="tooltip", class_="ol-popup",
                          inline=True) as tooltip:
                    placedetail += tooltip
                    tooltip += Html("div", id="tooltip-content")

            # source references
            if not self.report.options['inc_uplaces']:
                # We can't display source reference when we display
                # unused places. These info are not in the collected objects.
                # This is to avoid "page not found" errors.
                srcrefs = self.display_ind_sources(place)
                if srcrefs is not None:
                    placedetail += srcrefs

            # References list
            ref_list = self.display_bkref_list(Place, place_handle)
            if ref_list is not None:
                placedetail += ref_list

            # Begin inline javascript code because jsc is a
            # docstring, it does NOT have to be properly indented
            if self.placemappages:
                if place and (place.lat and place.long):
                    latitude, longitude = conv_lat_lon(place.get_latitude(),
                                                       place.get_longitude(),
                                                       "D.D8")
                    tracelife = " "
                    if self.create_media and media_list:
                        for fmedia in media_list:
                            photo_hdle = fmedia.get_reference_handle()
                            photo = self.r_db.get_media_from_handle(photo_hdle)
                            mime_type = photo.get_mime_type()
                            descr = photo.get_description()

                            if mime_type and is_image_type(mime_type):
                                uplnk = self.uplink
                                (pth,
                                 dummy_) = self.report.prepare_copy_media(photo)
                                srbuf = self.report.build_url_fname
                                newpath = srbuf(pth, image=True, uplink=uplnk)
                                imglnk = self.media_link(photo_hdle, newpath,
                                                         descr, uplink=uplnk,
                                                         usedescr=False)
                                if photo_hdle in self.report.obj_dict[Media]:
                                    tracelife += str(imglnk)
                                break # We show only the first image
                    scripts = Html()
                    if self.mapservice == "Google":
                        with Html("script", type="text/javascript",
                                  indent=False) as jsc:
                            scripts += jsc
                            # Google adds Latitude/ Longitude to its maps...
                            plce = placetitle.replace("'", "\\'")
                            jsc += MARKER_PATH % marker_path
                            jsc += MARKERS % ([[plce,
                                                latitude,
                                                longitude,
                                                1, tracelife]],
                                              latitude, longitude,
                                              10)
                    elif self.mapservice == "OpenStreetMap":
                        with Html("script", type="text/javascript") as jsc:
                            scripts += jsc
                            jsc += MARKER_PATH % marker_path
                            jsc += OSM_MARKERS % ([[float(longitude),
                                                    float(latitude),
                                                    placetitle, tracelife]],
                                                  longitude, latitude, 10)
                            jsc += OPENLAYER
                    else: # STAMEN
                        with Html("script", type="text/javascript") as jsc:
                            scripts += jsc
                            jsc += MARKER_PATH % marker_path
                            jsc += STAMEN_MARKERS % ([[float(longitude),
                                                       float(latitude),
                                                       placetitle, tracelife]],
                                                     self.stamenopts,
                                                     longitude, latitude, 10)
                            jsc += OPENLAYER
                    placedetail += scripts

        # add clearline for proper styling
        # add footer section
        footer = self.write_footer(ldatec)
        outerwrapper += (FULLCLEAR, footer)

        # send page out for processing
        # and close the file
        if place_name == apname: # store only the primary named page
            self.xhtml_writer(placepage, output_file, sio, ldatec)