From cdee00aca2969d6481e173c1b803ca6b3ce09bda Mon Sep 17 00:00:00 2001 From: Nick Hall Date: Sun, 23 Aug 2015 18:42:07 +0100 Subject: [PATCH] Remove trailing whitespace --- gramps/cli/__init__.py | 2 +- gramps/cli/arghandler.py | 94 +- gramps/cli/argparser.py | 52 +- gramps/cli/clidbman.py | 32 +- gramps/cli/grampscli.py | 66 +- gramps/cli/plug/__init__.py | 78 +- gramps/cli/test/argparser_test.py | 4 +- gramps/cli/test/cli_test.py | 8 +- gramps/cli/test/user_test.py | 10 +- gramps/cli/user.py | 22 +- gramps/gen/__init__.py | 2 +- gramps/gen/config.py | 16 +- gramps/gen/constfunc.py | 6 +- gramps/gen/datehandler/__init__.py | 6 +- gramps/gen/datehandler/_date_ar.py | 46 +- gramps/gen/datehandler/_date_bg.py | 268 +-- gramps/gen/datehandler/_date_ca.py | 132 +- gramps/gen/datehandler/_date_cs.py | 112 +- gramps/gen/datehandler/_date_da.py | 100 +- gramps/gen/datehandler/_date_de.py | 110 +- gramps/gen/datehandler/_date_el.py | 26 +- gramps/gen/datehandler/_date_es.py | 104 +- gramps/gen/datehandler/_date_fi.py | 62 +- gramps/gen/datehandler/_date_hr.py | 12 +- gramps/gen/datehandler/_date_it.py | 122 +- gramps/gen/datehandler/_date_ja.py | 2 +- gramps/gen/datehandler/_date_lt.py | 96 +- gramps/gen/datehandler/_date_nb.py | 100 +- gramps/gen/datehandler/_date_nl.py | 102 +- gramps/gen/datehandler/_date_pl.py | 44 +- gramps/gen/datehandler/_date_pt.py | 34 +- gramps/gen/datehandler/_date_ru.py | 68 +- gramps/gen/datehandler/_date_sk.py | 82 +- gramps/gen/datehandler/_date_sl.py | 22 +- gramps/gen/datehandler/_date_sr.py | 66 +- gramps/gen/datehandler/_date_sv.py | 108 +- gramps/gen/datehandler/_date_zh_CN.py | 18 +- gramps/gen/datehandler/_date_zh_TW.py | 18 +- gramps/gen/datehandler/_datedisplay.py | 84 +- gramps/gen/datehandler/_datehandler.py | 6 +- gramps/gen/datehandler/_dateparser.py | 52 +- gramps/gen/datehandler/_datestrings.py | 218 +-- gramps/gen/datehandler/_dateutils.py | 6 +- gramps/gen/datehandler/_grampslocale.py | 24 +- .../gen/datehandler/test/datedisplay_test.py | 10 +- .../gen/datehandler/test/datehandler_test.py | 26 +- .../gen/datehandler/test/dateparser_test.py | 4 +- .../gen/datehandler/test/datestrings_test.py | 2 +- gramps/gen/db/base.py | 322 +-- gramps/gen/db/dbconst.py | 28 +- gramps/gen/db/exceptions.py | 24 +- gramps/gen/db/txn.py | 40 +- gramps/gen/db/undoredo.py | 10 +- gramps/gen/dbstate.py | 12 +- gramps/gen/display/name.py | 196 +- gramps/gen/errors.py | 2 +- gramps/gen/filters/__init__.py | 4 +- gramps/gen/filters/_filterlist.py | 10 +- gramps/gen/filters/_filterparser.py | 12 +- gramps/gen/filters/_genericfilter.py | 32 +- gramps/gen/filters/_searchfilter.py | 2 +- gramps/gen/filters/rules/__init__.py | 2 +- gramps/gen/filters/rules/_hascitationbase.py | 10 +- gramps/gen/filters/rules/_haseventbase.py | 8 +- gramps/gen/filters/rules/_hasgallerybase.py | 2 +- gramps/gen/filters/rules/_hasldsbase.py | 4 +- gramps/gen/filters/rules/_hassourcebase.py | 4 +- gramps/gen/filters/rules/_hassourceofbase.py | 2 +- .../rules/_hastextmatchingsubstringof.py | 2 +- .../filters/rules/_matcheseventfilterbase.py | 6 +- .../gen/filters/rules/_matchesfilterbase.py | 6 +- .../rules/_matchessourceconfidencebase.py | 2 +- .../filters/rules/_matchessourcefilterbase.py | 2 +- gramps/gen/filters/rules/_regexpidbase.py | 2 +- gramps/gen/filters/rules/_rule.py | 10 +- gramps/gen/filters/rules/citation/__init__.py | 2 +- .../filters/rules/citation/_hascitation.py | 6 +- .../gen/filters/rules/citation/_hassource.py | 6 +- .../citation/_matchesrepositoryfilter.py | 10 +- .../rules/citation/_matchessourcefilter.py | 4 +- gramps/gen/filters/rules/event/__init__.py | 2 +- .../gen/filters/rules/event/_hascitation.py | 4 +- gramps/gen/filters/rules/event/_hasdata.py | 4 +- .../rules/event/_matchespersonfilter.py | 14 +- gramps/gen/filters/rules/family/__init__.py | 2 +- .../gen/filters/rules/family/_hascitation.py | 4 +- gramps/gen/filters/rules/family/_hasevent.py | 6 +- .../gen/filters/rules/family/_isbookmarked.py | 2 +- gramps/gen/filters/rules/media/__init__.py | 2 +- .../gen/filters/rules/media/_hascitation.py | 4 +- gramps/gen/filters/rules/media/_hasmedia.py | 6 +- gramps/gen/filters/rules/note/_hasnote.py | 4 +- gramps/gen/filters/rules/person/__init__.py | 2 +- .../person/_deeprelationshippathbetween.py | 26 +- .../gen/filters/rules/person/_hasaddress.py | 4 +- .../filters/rules/person/_hasassociation.py | 4 +- gramps/gen/filters/rules/person/_hasbirth.py | 4 +- .../gen/filters/rules/person/_hascitation.py | 4 +- .../rules/person/_hascommonancestorwith.py | 6 +- gramps/gen/filters/rules/person/_hasdeath.py | 2 +- gramps/gen/filters/rules/person/_hasevent.py | 8 +- .../rules/person/_hasfamilyattribute.py | 2 +- .../filters/rules/person/_hasfamilyevent.py | 10 +- .../rules/person/_hasnameorigintype.py | 2 +- .../gen/filters/rules/person/_hasnametype.py | 2 +- .../gen/filters/rules/person/_hasnickname.py | 2 +- .../rules/person/_hastextmatchingregexpof.py | 4 +- .../person/_hastextmatchingsubstringof.py | 14 +- .../gen/filters/rules/person/_isancestorof.py | 4 +- .../rules/person/_isancestoroffiltermatch.py | 2 +- .../gen/filters/rules/person/_isbookmarked.py | 2 +- .../rules/person/_isdescendantfamilyof.py | 2 +- .../_isdescendantfamilyoffiltermatch.py | 2 +- .../filters/rules/person/_isdescendantof.py | 2 +- .../person/_isdescendantoffiltermatch.py | 2 +- .../_islessthannthgenerationancestorof.py | 6 +- ...ssthannthgenerationancestorofbookmarked.py | 4 +- ...hannthgenerationancestorofdefaultperson.py | 4 +- .../_ismorethannthgenerationancestorof.py | 6 +- .../_ismorethannthgenerationdescendantof.py | 4 +- .../rules/person/_isparentoffiltermatch.py | 4 +- .../filters/rules/person/_isrelatedwith.py | 10 +- .../rules/person/_isspouseoffiltermatch.py | 4 +- .../rules/person/_matcheseventfilter.py | 2 +- .../filters/rules/person/_missingparent.py | 2 +- .../gen/filters/rules/person/_regexpname.py | 2 +- .../rules/person/_relationshippathbetween.py | 8 +- .../_relationshippathbetweenbookmarks.py | 4 +- .../gen/filters/rules/person/_searchname.py | 2 +- gramps/gen/filters/rules/place/__init__.py | 2 +- .../gen/filters/rules/place/_hascitation.py | 4 +- gramps/gen/filters/rules/place/_hasplace.py | 16 +- .../rules/place/_inlatlonneighborhood.py | 36 +- .../gen/filters/rules/repository/_hasrepo.py | 8 +- .../filters/rules/source/_hasrepository.py | 2 +- .../source/_hasrepositorycallnumberref.py | 4 +- .../rules/source/_matchesrepositoryfilter.py | 10 +- gramps/gen/lib/__init__.py | 2 +- gramps/gen/lib/address.py | 10 +- gramps/gen/lib/addressbase.py | 12 +- gramps/gen/lib/attrbase.py | 8 +- gramps/gen/lib/attribute.py | 44 +- gramps/gen/lib/attrtype.py | 8 +- gramps/gen/lib/childref.py | 10 +- gramps/gen/lib/childreftype.py | 8 +- gramps/gen/lib/citation.py | 32 +- gramps/gen/lib/citationbase.py | 50 +- gramps/gen/lib/date.py | 356 ++-- gramps/gen/lib/datebase.py | 4 +- gramps/gen/lib/event.py | 50 +- gramps/gen/lib/eventref.py | 14 +- gramps/gen/lib/eventtype.py | 20 +- gramps/gen/lib/family.py | 84 +- gramps/gen/lib/gcalendar.py | 86 +- gramps/gen/lib/genderstats.py | 10 +- gramps/gen/lib/grampstype.py | 46 +- gramps/gen/lib/handle.py | 2 +- gramps/gen/lib/ldsord.py | 44 +- gramps/gen/lib/ldsordbase.py | 14 +- gramps/gen/lib/location.py | 22 +- gramps/gen/lib/locationbase.py | 18 +- gramps/gen/lib/mediabase.py | 8 +- gramps/gen/lib/mediaobj.py | 34 +- gramps/gen/lib/mediaref.py | 10 +- gramps/gen/lib/name.py | 126 +- gramps/gen/lib/nameorigintype.py | 2 +- gramps/gen/lib/note.py | 50 +- gramps/gen/lib/notebase.py | 20 +- gramps/gen/lib/notetype.py | 20 +- gramps/gen/lib/person.py | 146 +- gramps/gen/lib/personref.py | 10 +- gramps/gen/lib/place.py | 46 +- gramps/gen/lib/placebase.py | 8 +- gramps/gen/lib/placeref.py | 14 +- gramps/gen/lib/primaryobj.py | 64 +- gramps/gen/lib/privacybase.py | 14 +- gramps/gen/lib/refbase.py | 4 +- gramps/gen/lib/repo.py | 20 +- gramps/gen/lib/reporef.py | 6 +- gramps/gen/lib/researcher.py | 36 +- gramps/gen/lib/secondaryobj.py | 4 +- gramps/gen/lib/src.py | 36 +- gramps/gen/lib/srcattribute.py | 6 +- gramps/gen/lib/srcattrtype.py | 8 +- gramps/gen/lib/styledtext.py | 98 +- gramps/gen/lib/styledtexttag.py | 30 +- gramps/gen/lib/styledtexttagtype.py | 10 +- gramps/gen/lib/surname.py | 34 +- gramps/gen/lib/surnamebase.py | 30 +- gramps/gen/lib/tableobj.py | 24 +- gramps/gen/lib/tag.py | 20 +- gramps/gen/lib/tagbase.py | 16 +- gramps/gen/lib/test/date_test.py | 68 +- gramps/gen/lib/test/grampstype_test.py | 24 +- gramps/gen/lib/test/merge_test.py | 4 +- gramps/gen/lib/test/struct_test.py | 8 +- gramps/gen/lib/url.py | 18 +- gramps/gen/lib/urlbase.py | 12 +- gramps/gen/lib/urltype.py | 2 +- gramps/gen/merge/diff.py | 30 +- gramps/gen/merge/mergecitationquery.py | 6 +- gramps/gen/merge/mergepersonquery.py | 4 +- gramps/gen/merge/test/merge_ref_test.py | 4 +- gramps/gen/mime/_pythonmime.py | 2 +- gramps/gen/mime/_winmime.py | 14 +- gramps/gen/plug/__init__.py | 12 +- gramps/gen/plug/_docgenplugin.py | 30 +- gramps/gen/plug/_export.py | 12 +- gramps/gen/plug/_gramplet.py | 36 +- gramps/gen/plug/_import.py | 10 +- gramps/gen/plug/_manager.py | 102 +- gramps/gen/plug/_options.py | 44 +- gramps/gen/plug/_plugin.py | 18 +- gramps/gen/plug/_pluginreg.py | 238 +-- gramps/gen/plug/docbackend/cairobackend.py | 10 +- gramps/gen/plug/docbackend/docbackend.py | 70 +- gramps/gen/plug/docgen/basedoc.py | 6 +- gramps/gen/plug/docgen/drawdoc.py | 4 +- gramps/gen/plug/docgen/fontscale.py | 2 +- gramps/gen/plug/docgen/fontstyle.py | 4 +- gramps/gen/plug/docgen/graphdoc.py | 200 +- gramps/gen/plug/docgen/graphicstyle.py | 2 +- gramps/gen/plug/docgen/paperstyle.py | 26 +- gramps/gen/plug/docgen/paragraphstyle.py | 4 +- gramps/gen/plug/docgen/stylesheet.py | 32 +- gramps/gen/plug/docgen/tablestyle.py | 4 +- gramps/gen/plug/docgen/textdoc.py | 34 +- gramps/gen/plug/menu/_booleanlist.py | 12 +- gramps/gen/plug/menu/_destination.py | 14 +- gramps/gen/plug/menu/_enumeratedlist.py | 22 +- gramps/gen/plug/menu/_family.py | 2 +- gramps/gen/plug/menu/_filter.py | 14 +- gramps/gen/plug/menu/_media.py | 2 +- gramps/gen/plug/menu/_menu.py | 34 +- gramps/gen/plug/menu/_note.py | 2 +- gramps/gen/plug/menu/_number.py | 14 +- gramps/gen/plug/menu/_option.py | 48 +- gramps/gen/plug/menu/_person.py | 2 +- gramps/gen/plug/menu/_personlist.py | 2 +- gramps/gen/plug/menu/_placelist.py | 2 +- gramps/gen/plug/menu/_style.py | 16 +- gramps/gen/plug/report/_bibliography.py | 38 +- gramps/gen/plug/report/_book.py | 50 +- gramps/gen/plug/report/_options.py | 56 +- gramps/gen/plug/report/endnotes.py | 38 +- gramps/gen/plug/report/utils.py | 44 +- gramps/gen/plug/utils.py | 6 +- gramps/gen/proxy/filter.py | 70 +- gramps/gen/proxy/living.py | 46 +- gramps/gen/proxy/private.py | 178 +- gramps/gen/proxy/proxybase.py | 138 +- gramps/gen/proxy/referencedbyselection.py | 38 +- gramps/gen/recentfiles.py | 14 +- gramps/gen/relationship.py | 578 +++--- gramps/gen/simple/_simpleaccess.py | 162 +- gramps/gen/simple/_simpletable.py | 28 +- gramps/gen/sort.py | 18 +- gramps/gen/soundex.py | 2 +- gramps/gen/test/config_test.py | 40 +- gramps/gen/test/constfunc_test.py | 2 +- gramps/gen/test/user_test.py | 2 +- gramps/gen/user.py | 22 +- gramps/gen/utils/alive.py | 92 +- gramps/gen/utils/callback.py | 52 +- gramps/gen/utils/callman.py | 74 +- gramps/gen/utils/cast.py | 6 +- gramps/gen/utils/config.py | 2 +- gramps/gen/utils/configmanager.py | 70 +- gramps/gen/utils/db.py | 78 +- gramps/gen/utils/debug.py | 6 +- gramps/gen/utils/docgen/odstab.py | 198 +- gramps/gen/utils/docgen/tabbeddoc.py | 2 +- gramps/gen/utils/grampslocale.py | 28 +- gramps/gen/utils/id.py | 4 +- gramps/gen/utils/image.py | 8 +- gramps/gen/utils/keyword.py | 6 +- gramps/gen/utils/lds.py | 10 +- gramps/gen/utils/libformatting.py | 20 +- gramps/gen/utils/location.py | 2 +- gramps/gen/utils/place.py | 78 +- gramps/gen/utils/resourcepath.py | 2 +- gramps/gen/utils/string.py | 28 +- gramps/gen/utils/test/callback_test.py | 34 +- gramps/gen/utils/test/grampslocale_test.py | 6 +- gramps/gen/utils/test/keyword_test.py | 4 +- gramps/gen/utils/test/place_test.py | 6 +- gramps/gen/utils/thumbnails.py | 34 +- gramps/gen/utils/unknown.py | 4 +- gramps/grampsapp.py | 28 +- gramps/gui/__init__.py | 4 +- gramps/gui/aboutdialog.py | 42 +- gramps/gui/actiongroup.py | 2 +- gramps/gui/autocomp.py | 6 +- gramps/gui/clipboard.py | 152 +- gramps/gui/columnorder.py | 14 +- gramps/gui/configure.py | 312 +-- gramps/gui/dbguielement.py | 22 +- gramps/gui/dbloader.py | 108 +- gramps/gui/dbman.py | 88 +- gramps/gui/ddtargets.py | 92 +- gramps/gui/dialog.py | 58 +- gramps/gui/display.py | 2 +- gramps/gui/displaystate.py | 56 +- gramps/gui/editors/__init__.py | 8 +- gramps/gui/editors/addmedia.py | 16 +- gramps/gui/editors/displaytabs/__init__.py | 2 +- .../gui/editors/displaytabs/addrembedlist.py | 20 +- .../gui/editors/displaytabs/addressmodel.py | 12 +- .../gui/editors/displaytabs/attrembedlist.py | 14 +- gramps/gui/editors/displaytabs/attrmodel.py | 4 +- gramps/gui/editors/displaytabs/backreflist.py | 10 +- .../gui/editors/displaytabs/backrefmodel.py | 6 +- gramps/gui/editors/displaytabs/buttontab.py | 26 +- gramps/gui/editors/displaytabs/childmodel.py | 38 +- .../displaytabs/citationbackreflist.py | 2 +- .../editors/displaytabs/citationembedlist.py | 58 +- .../editors/displaytabs/citationrefmodel.py | 2 +- .../gui/editors/displaytabs/embeddedlist.py | 74 +- .../editors/displaytabs/eventbackreflist.py | 2 +- .../gui/editors/displaytabs/eventembedlist.py | 34 +- .../gui/editors/displaytabs/eventrefmodel.py | 20 +- .../displaytabs/familyattrembedlist.py | 4 +- .../editors/displaytabs/familyldsembedlist.py | 6 +- gramps/gui/editors/displaytabs/gallerytab.py | 62 +- gramps/gui/editors/displaytabs/grampstab.py | 16 +- .../editors/displaytabs/groupembeddedlist.py | 38 +- .../gui/editors/displaytabs/ldsembedlist.py | 20 +- gramps/gui/editors/displaytabs/ldsmodel.py | 8 +- .../editors/displaytabs/locationembedlist.py | 26 +- .../gui/editors/displaytabs/locationmodel.py | 2 +- .../editors/displaytabs/mediabackreflist.py | 2 +- .../gui/editors/displaytabs/nameembedlist.py | 26 +- gramps/gui/editors/displaytabs/namemodel.py | 18 +- .../editors/displaytabs/notebackreflist.py | 2 +- gramps/gui/editors/displaytabs/notemodel.py | 6 +- gramps/gui/editors/displaytabs/notetab.py | 40 +- .../editors/displaytabs/personbackreflist.py | 2 +- .../displaytabs/personeventembedlist.py | 6 +- .../editors/displaytabs/personrefembedlist.py | 8 +- .../gui/editors/displaytabs/personrefmodel.py | 2 +- .../editors/displaytabs/placebackreflist.py | 2 +- .../editors/displaytabs/placerefembedlist.py | 20 +- .../gui/editors/displaytabs/placerefmodel.py | 4 +- .../gui/editors/displaytabs/repoembedlist.py | 26 +- .../gui/editors/displaytabs/reporefmodel.py | 2 +- .../editors/displaytabs/sourcebackreflist.py | 2 +- .../editors/displaytabs/srcattrembedlist.py | 16 +- .../gui/editors/displaytabs/surnamemodel.py | 2 +- gramps/gui/editors/displaytabs/surnametab.py | 32 +- .../gui/editors/displaytabs/webembedlist.py | 12 +- gramps/gui/editors/displaytabs/webmodel.py | 2 +- gramps/gui/editors/editaddress.py | 20 +- gramps/gui/editors/editattribute.py | 20 +- gramps/gui/editors/editchildref.py | 20 +- gramps/gui/editors/editcitation.py | 62 +- gramps/gui/editors/editdate.py | 56 +- gramps/gui/editors/editevent.py | 40 +- gramps/gui/editors/editeventref.py | 22 +- gramps/gui/editors/editfamily.py | 144 +- gramps/gui/editors/editldsord.py | 26 +- gramps/gui/editors/editlink.py | 38 +- gramps/gui/editors/editlocation.py | 16 +- gramps/gui/editors/editmedia.py | 58 +- gramps/gui/editors/editmediaref.py | 80 +- gramps/gui/editors/editname.py | 74 +- gramps/gui/editors/editnote.py | 72 +- gramps/gui/editors/editperson.py | 10 +- gramps/gui/editors/editpersonref.py | 20 +- gramps/gui/editors/editplace.py | 50 +- gramps/gui/editors/editplaceref.py | 38 +- gramps/gui/editors/editprimary.py | 54 +- gramps/gui/editors/editreference.py | 8 +- gramps/gui/editors/editreporef.py | 20 +- gramps/gui/editors/editrepository.py | 36 +- gramps/gui/editors/editsecondary.py | 4 +- gramps/gui/editors/editsource.py | 70 +- gramps/gui/editors/edittaglist.py | 6 +- gramps/gui/editors/editurl.py | 20 +- gramps/gui/editors/filtereditor.py | 106 +- gramps/gui/editors/objectentries.py | 46 +- gramps/gui/editors/test/test_editreference.py | 10 +- gramps/gui/filters/_filtercombobox.py | 4 +- gramps/gui/filters/_searchbar.py | 14 +- .../filters/sidebar/_citationsidebarfilter.py | 12 +- .../filters/sidebar/_eventsidebarfilter.py | 10 +- .../filters/sidebar/_familysidebarfilter.py | 14 +- .../filters/sidebar/_mediasidebarfilter.py | 4 +- .../gui/filters/sidebar/_notesidebarfilter.py | 4 +- .../filters/sidebar/_personsidebarfilter.py | 48 +- .../filters/sidebar/_placesidebarfilter.py | 6 +- .../gui/filters/sidebar/_reposidebarfilter.py | 8 +- gramps/gui/filters/sidebar/_sidebarfilter.py | 18 +- .../filters/sidebar/_sourcesidebarfilter.py | 4 +- gramps/gui/glade.py | 58 +- gramps/gui/glade/catalog/grampswidgets.py | 2 +- gramps/gui/grampsgui.py | 14 +- gramps/gui/listmodel.py | 36 +- gramps/gui/logger/__init__.py | 4 +- gramps/gui/logger/_errorreportassistant.py | 36 +- gramps/gui/logger/_errorview.py | 14 +- gramps/gui/logger/_gtkhandler.py | 2 +- gramps/gui/logger/test/rotate_handler_test.py | 20 +- gramps/gui/makefilter.py | 4 +- gramps/gui/managedwindow.py | 62 +- gramps/gui/merge/mergecitation.py | 4 +- gramps/gui/merge/mergeevent.py | 4 +- gramps/gui/merge/mergefamily.py | 4 +- gramps/gui/merge/mergemedia.py | 2 +- gramps/gui/merge/mergenote.py | 2 +- gramps/gui/merge/mergeperson.py | 28 +- gramps/gui/merge/mergeplace.py | 6 +- gramps/gui/merge/mergerepository.py | 2 +- gramps/gui/merge/mergesource.py | 4 +- gramps/gui/navigator.py | 22 +- gramps/gui/plug/_dialogs.py | 38 +- gramps/gui/plug/_guioptions.py | 218 +-- gramps/gui/plug/_windows.py | 150 +- gramps/gui/plug/export/_exportassistant.py | 168 +- gramps/gui/plug/export/_exportoptions.py | 56 +- gramps/gui/plug/quick/__init__.py | 10 +- gramps/gui/plug/quick/_quickreports.py | 52 +- gramps/gui/plug/quick/_quicktable.py | 60 +- gramps/gui/plug/quick/_textbufdoc.py | 20 +- gramps/gui/plug/report/_bookdialog.py | 132 +- gramps/gui/plug/report/_docreportdialog.py | 18 +- gramps/gui/plug/report/_drawreportdialog.py | 6 +- gramps/gui/plug/report/_fileentry.py | 6 +- .../gui/plug/report/_graphvizreportdialog.py | 34 +- gramps/gui/plug/report/_papermenu.py | 46 +- gramps/gui/plug/report/_reportdialog.py | 62 +- gramps/gui/plug/report/_stylecombobox.py | 4 +- gramps/gui/plug/report/_styleeditor.py | 68 +- gramps/gui/plug/report/_textreportdialog.py | 8 +- gramps/gui/plug/report/_webreportdialog.py | 2 +- gramps/gui/plug/tool.py | 20 +- gramps/gui/pluginmanager.py | 32 +- gramps/gui/selectors/baseselector.py | 42 +- gramps/gui/selectors/selectcitation.py | 6 +- gramps/gui/selectors/selectevent.py | 2 +- gramps/gui/selectors/selectfamily.py | 2 +- gramps/gui/selectors/selectnote.py | 4 +- gramps/gui/selectors/selectobject.py | 6 +- gramps/gui/selectors/selectorexceptions.py | 4 +- gramps/gui/selectors/selectperson.py | 4 +- gramps/gui/selectors/selectplace.py | 2 +- gramps/gui/selectors/selectrepository.py | 2 +- gramps/gui/selectors/selectsource.py | 2 +- gramps/gui/spell.py | 12 +- gramps/gui/test/user_test.py | 8 +- gramps/gui/tipofday.py | 22 +- gramps/gui/undohistory.py | 16 +- gramps/gui/user.py | 22 +- gramps/gui/utils.py | 16 +- gramps/gui/utilscairo.py | 2 +- gramps/gui/viewmanager.py | 14 +- gramps/gui/views/__init__.py | 2 +- gramps/gui/views/bookmarks.py | 66 +- gramps/gui/views/listview.py | 164 +- gramps/gui/views/navigationview.py | 76 +- gramps/gui/views/pageview.py | 90 +- gramps/gui/views/tags.py | 26 +- gramps/gui/views/treemodels/basemodel.py | 4 +- .../gui/views/treemodels/citationbasemodel.py | 8 +- .../gui/views/treemodels/citationtreemodel.py | 8 +- gramps/gui/views/treemodels/eventmodel.py | 8 +- gramps/gui/views/treemodels/familymodel.py | 32 +- gramps/gui/views/treemodels/flatbasemodel.py | 144 +- gramps/gui/views/treemodels/lru.py | 2 +- gramps/gui/views/treemodels/mediamodel.py | 6 +- gramps/gui/views/treemodels/notemodel.py | 12 +- gramps/gui/views/treemodels/peoplemodel.py | 32 +- gramps/gui/views/treemodels/placemodel.py | 16 +- gramps/gui/views/treemodels/repomodel.py | 14 +- gramps/gui/views/treemodels/sourcemodel.py | 12 +- gramps/gui/widgets/__init__.py | 2 +- gramps/gui/widgets/basicentry.py | 2 +- gramps/gui/widgets/buttons.py | 4 +- gramps/gui/widgets/dateentry.py | 8 +- gramps/gui/widgets/expandcollapsearrow.py | 4 +- gramps/gui/widgets/fanchart.py | 188 +- gramps/gui/widgets/fanchartdesc.py | 70 +- gramps/gui/widgets/grabbers.py | 16 +- gramps/gui/widgets/grampletbar.py | 28 +- gramps/gui/widgets/grampletpane.py | 190 +- gramps/gui/widgets/interactivesearchbox.py | 4 +- gramps/gui/widgets/labels.py | 10 +- gramps/gui/widgets/linkbox.py | 2 +- gramps/gui/widgets/menuitem.py | 6 +- gramps/gui/widgets/monitoredwidgets.py | 88 +- gramps/gui/widgets/multitreeview.py | 12 +- gramps/gui/widgets/photo.py | 2 +- gramps/gui/widgets/placeentry.py | 6 +- gramps/gui/widgets/progressdialog.py | 190 +- gramps/gui/widgets/reorderfam.py | 14 +- gramps/gui/widgets/selectionwidget.py | 20 +- gramps/gui/widgets/shortlistcomboentry.py | 18 +- gramps/gui/widgets/springseparator.py | 14 +- gramps/gui/widgets/statusbar.py | 4 +- gramps/gui/widgets/styledtextbuffer.py | 140 +- gramps/gui/widgets/styledtexteditor.py | 174 +- gramps/gui/widgets/toolcomboentry.py | 8 +- gramps/gui/widgets/undoablebuffer.py | 28 +- gramps/gui/widgets/undoableentry.py | 18 +- gramps/gui/widgets/undoablestyledbuffer.py | 38 +- gramps/gui/widgets/validatedcomboentry.py | 80 +- gramps/gui/widgets/validatedmaskedentry.py | 168 +- gramps/gui/widgets/valueaction.py | 46 +- gramps/gui/widgets/valuetoolitem.py | 28 +- gramps/guiQML/__init__.py | 2 +- gramps/guiQML/grampsqml.py | 6 +- gramps/guiQML/questiondialog.py | 4 +- gramps/guiQML/viewmanager.py | 4 +- gramps/guiQML/views/__init__.py | 2 +- gramps/guiQML/views/centralview.py | 20 +- gramps/guiQML/views/dbman.py | 14 +- gramps/guiQML/views/personview.py | 34 +- .../database/bsddb_support/bsddbtxn.py | 6 +- .../plugins/database/bsddb_support/cursor.py | 14 +- gramps/plugins/database/bsddb_support/read.py | 390 ++-- .../plugins/database/bsddb_support/summary.py | 4 +- .../bsddb_support/test/cursor_test.py | 38 +- .../bsddb_support/test/grampsdbtestbase.py | 16 +- .../bsddb_support/test/reference_map_test.py | 40 +- .../database/bsddb_support/undoredo.py | 36 +- .../plugins/database/bsddb_support/upgrade.py | 164 +- .../plugins/database/bsddb_support/write.py | 348 ++-- gramps/plugins/database/dictionarydb.py | 130 +- gramps/plugins/docgen/asciidoc.py | 30 +- gramps/plugins/docgen/cairodoc.py | 16 +- gramps/plugins/docgen/docgen.gpr.py | 2 +- gramps/plugins/docgen/gtkprint.py | 134 +- gramps/plugins/docgen/htmldoc.py | 110 +- gramps/plugins/docgen/latexdoc.py | 4 +- gramps/plugins/docgen/odfdoc.py | 210 +- gramps/plugins/docgen/rtfdoc.py | 60 +- gramps/plugins/docgen/svgdrawdoc.py | 24 +- gramps/plugins/drawreport/ancestortree.py | 6 +- gramps/plugins/drawreport/calendarreport.py | 128 +- gramps/plugins/drawreport/descendtree.py | 320 +-- gramps/plugins/drawreport/drawplugins.gpr.py | 2 +- gramps/plugins/drawreport/fanchart.py | 98 +- gramps/plugins/drawreport/statisticschart.py | 96 +- gramps/plugins/drawreport/timeline.py | 64 +- gramps/plugins/export/export.gpr.py | 4 +- gramps/plugins/export/exportcsv.py | 70 +- gramps/plugins/export/exportftree.py | 14 +- gramps/plugins/export/exportgedcom.py | 384 ++-- gramps/plugins/export/exportgeneweb.py | 68 +- gramps/plugins/export/exportpkg.py | 24 +- gramps/plugins/export/exportvcalendar.py | 50 +- gramps/plugins/export/exportvcard.py | 16 +- gramps/plugins/export/exportxml.py | 80 +- .../plugins/export/test/exportvcard_test.py | 24 +- gramps/plugins/gramplet/ageondategramplet.py | 12 +- gramps/plugins/gramplet/agestats.py | 58 +- gramps/plugins/gramplet/ancestor.py | 14 +- gramps/plugins/gramplet/attributes.py | 20 +- gramps/plugins/gramplet/backlinks.py | 26 +- gramps/plugins/gramplet/calendargramplet.py | 6 +- gramps/plugins/gramplet/citations.py | 14 +- gramps/plugins/gramplet/descendant.py | 12 +- gramps/plugins/gramplet/eval.py | 4 +- gramps/plugins/gramplet/events.py | 6 +- .../plugins/gramplet/fanchartdescgramplet.py | 2 +- gramps/plugins/gramplet/fanchartgramplet.py | 2 +- gramps/plugins/gramplet/filter.py | 6 +- gramps/plugins/gramplet/gallery.py | 4 +- gramps/plugins/gramplet/givennamegramplet.py | 12 +- gramps/plugins/gramplet/gramplet.gpr.py | 484 ++--- gramps/plugins/gramplet/leak.py | 8 +- gramps/plugins/gramplet/mediapreview.py | 2 +- gramps/plugins/gramplet/metadataviewer.py | 2 +- gramps/plugins/gramplet/notes.py | 8 +- gramps/plugins/gramplet/pedigreegramplet.py | 8 +- gramps/plugins/gramplet/persondetails.py | 8 +- gramps/plugins/gramplet/personresidence.py | 2 +- gramps/plugins/gramplet/placedetails.py | 4 +- gramps/plugins/gramplet/quickviewgramplet.py | 34 +- gramps/plugins/gramplet/repositorydetails.py | 4 +- gramps/plugins/gramplet/sessionloggramplet.py | 16 +- gramps/plugins/gramplet/statsgramplet.py | 10 +- .../plugins/gramplet/surnamecloudgramplet.py | 8 +- gramps/plugins/gramplet/todo.py | 10 +- gramps/plugins/gramplet/todogramplet.py | 10 +- .../plugins/gramplet/topsurnamesgramplet.py | 2 +- gramps/plugins/gramplet/welcomegramplet.py | 12 +- gramps/plugins/gramplet/whatsnext.py | 2 +- gramps/plugins/graph/graphplugins.gpr.py | 2 +- gramps/plugins/graph/gvfamilylines.py | 48 +- gramps/plugins/graph/gvhourglass.py | 34 +- gramps/plugins/graph/gvrelgraph.py | 66 +- gramps/plugins/importer/import.gpr.py | 2 +- gramps/plugins/importer/importcsv.py | 38 +- gramps/plugins/importer/importgedcom.py | 8 +- gramps/plugins/importer/importgeneweb.py | 58 +- gramps/plugins/importer/importgpkg.py | 14 +- gramps/plugins/importer/importgrdb.py | 10 +- gramps/plugins/importer/importprogen.py | 26 +- gramps/plugins/importer/importvcard.py | 16 +- gramps/plugins/importer/importxml.py | 414 ++-- .../plugins/importer/test/importvcard_test.py | 14 +- gramps/plugins/lib/libcairodoc.py | 426 ++-- gramps/plugins/lib/libgedcom.py | 1430 +++++++------- gramps/plugins/lib/libgrampsxml.py | 2 +- gramps/plugins/lib/libholiday.py | 112 +- gramps/plugins/lib/libhtml.py | 70 +- gramps/plugins/lib/libhtmlbackend.py | 36 +- gramps/plugins/lib/libmapservice.py | 14 +- gramps/plugins/lib/libmetadata.py | 22 +- gramps/plugins/lib/libmixin.py | 132 +- gramps/plugins/lib/libnarrate.py | 1720 ++++++++--------- gramps/plugins/lib/libodfbackend.py | 20 +- gramps/plugins/lib/libpersonview.py | 44 +- gramps/plugins/lib/libplaceimport.py | 4 +- gramps/plugins/lib/libplaceview.py | 38 +- gramps/plugins/lib/libplugins.gpr.py | 2 +- gramps/plugins/lib/librecords.py | 28 +- gramps/plugins/lib/libsubstkeyword.py | 4 +- gramps/plugins/lib/libtreebase.py | 216 +-- gramps/plugins/lib/maps/__init__.py | 2 +- gramps/plugins/lib/maps/cairoprint.py | 24 +- gramps/plugins/lib/maps/geography.py | 22 +- gramps/plugins/lib/maps/markerlayer.py | 2 +- gramps/plugins/lib/maps/osmgps.py | 2 +- gramps/plugins/lib/maps/placeselection.py | 2 +- gramps/plugins/mapservices/eniroswedenmap.py | 28 +- gramps/plugins/mapservices/googlemap.py | 8 +- gramps/plugins/mapservices/mapservice.gpr.py | 8 +- gramps/plugins/mapservices/openstreetmap.py | 10 +- gramps/plugins/quickview/ageondate.py | 6 +- gramps/plugins/quickview/all_events.py | 36 +- gramps/plugins/quickview/all_relations.py | 72 +- gramps/plugins/quickview/filterbyname.py | 64 +- gramps/plugins/quickview/lineage.py | 50 +- gramps/plugins/quickview/linkreferences.py | 2 +- gramps/plugins/quickview/onthisday.py | 24 +- gramps/plugins/quickview/quickview.gpr.py | 52 +- gramps/plugins/quickview/references.py | 2 +- gramps/plugins/quickview/samesurnames.py | 6 +- gramps/plugins/quickview/siblings.py | 8 +- gramps/plugins/rel/rel_ca.py | 6 +- gramps/plugins/rel/rel_cs.py | 12 +- gramps/plugins/rel/rel_da.py | 8 +- gramps/plugins/rel/rel_de.py | 10 +- gramps/plugins/rel/rel_es.py | 52 +- gramps/plugins/rel/rel_fi.py | 8 +- gramps/plugins/rel/rel_fr.py | 6 +- gramps/plugins/rel/rel_hr.py | 22 +- gramps/plugins/rel/rel_hu.py | 22 +- gramps/plugins/rel/rel_it.py | 76 +- gramps/plugins/rel/rel_nl.py | 54 +- gramps/plugins/rel/rel_no.py | 18 +- gramps/plugins/rel/rel_pl.py | 560 +++--- gramps/plugins/rel/rel_ru.py | 418 ++-- gramps/plugins/rel/rel_sk.py | 100 +- gramps/plugins/rel/rel_sl.py | 102 +- gramps/plugins/rel/rel_sv.py | 126 +- gramps/plugins/rel/relplugins.gpr.py | 40 +- gramps/plugins/sidebar/categorysidebar.py | 12 +- gramps/plugins/sidebar/dropdownsidebar.py | 18 +- gramps/plugins/sidebar/expandersidebar.py | 22 +- gramps/plugins/sidebar/sidebar.gpr.py | 8 +- .../plugins/textreport/alphabeticalindex.py | 14 +- gramps/plugins/textreport/ancestorreport.py | 48 +- gramps/plugins/textreport/birthdayreport.py | 100 +- gramps/plugins/textreport/custombooktext.py | 20 +- gramps/plugins/textreport/descendreport.py | 52 +- .../plugins/textreport/detancestralreport.py | 92 +- .../plugins/textreport/detdescendantreport.py | 132 +- gramps/plugins/textreport/endoflinereport.py | 50 +- gramps/plugins/textreport/familygroup.py | 100 +- gramps/plugins/textreport/indivcomplete.py | 104 +- gramps/plugins/textreport/kinshipreport.py | 90 +- gramps/plugins/textreport/notelinkreport.py | 14 +- .../textreport/numberofancestorsreport.py | 28 +- gramps/plugins/textreport/placereport.py | 36 +- gramps/plugins/textreport/recordsreport.py | 6 +- gramps/plugins/textreport/simplebooktitle.py | 24 +- gramps/plugins/textreport/summary.py | 72 +- gramps/plugins/textreport/tableofcontents.py | 14 +- gramps/plugins/textreport/tagreport.py | 146 +- gramps/plugins/textreport/textplugins.gpr.py | 2 +- gramps/plugins/tool/changenames.py | 26 +- gramps/plugins/tool/changetypes.py | 14 +- gramps/plugins/tool/check.py | 198 +- gramps/plugins/tool/dateparserdisplaytest.py | 8 +- gramps/plugins/tool/dumpgenderstats.py | 14 +- gramps/plugins/tool/eventnames.py | 30 +- gramps/plugins/tool/extractcity.py | 532 ++--- gramps/plugins/tool/finddupes.py | 60 +- gramps/plugins/tool/mediamanager.py | 36 +- gramps/plugins/tool/mergecitations.py | 32 +- gramps/plugins/tool/notrelated.py | 14 +- gramps/plugins/tool/ownereditor.py | 10 +- gramps/plugins/tool/patchnames.py | 38 +- gramps/plugins/tool/populatesources.py | 28 +- gramps/plugins/tool/rebuild.py | 10 +- gramps/plugins/tool/rebuildgenderstat.py | 10 +- gramps/plugins/tool/rebuildrefmap.py | 6 +- gramps/plugins/tool/relcalc.py | 22 +- gramps/plugins/tool/removeunused.py | 26 +- gramps/plugins/tool/reorderids.py | 12 +- gramps/plugins/tool/sortevents.py | 8 +- gramps/plugins/tool/testcasegenerator.py | 190 +- gramps/plugins/tool/tools.gpr.py | 40 +- gramps/plugins/tool/toolsdebug.gpr.py | 10 +- gramps/plugins/tool/verify.py | 66 +- gramps/plugins/view/citationlistview.py | 56 +- gramps/plugins/view/citationtreeview.py | 162 +- gramps/plugins/view/dashboardview.py | 14 +- gramps/plugins/view/eventview.py | 18 +- gramps/plugins/view/familyview.py | 32 +- gramps/plugins/view/fanchartdescview.py | 86 +- gramps/plugins/view/fanchartview.py | 96 +- gramps/plugins/view/geoclose.py | 22 +- gramps/plugins/view/geoevents.py | 22 +- gramps/plugins/view/geofamclose.py | 30 +- gramps/plugins/view/geofamily.py | 20 +- gramps/plugins/view/geography.gpr.py | 30 +- gramps/plugins/view/geomoves.py | 26 +- gramps/plugins/view/geoperson.py | 26 +- gramps/plugins/view/geoplaces.py | 18 +- gramps/plugins/view/mediaview.py | 48 +- gramps/plugins/view/noteview.py | 8 +- gramps/plugins/view/pedigreeview.py | 106 +- gramps/plugins/view/persontreeview.py | 16 +- gramps/plugins/view/placetreeview.py | 10 +- gramps/plugins/view/relview.py | 188 +- gramps/plugins/view/repoview.py | 16 +- gramps/plugins/view/sourceview.py | 20 +- gramps/plugins/view/view.gpr.py | 38 +- gramps/plugins/webreport/narrativeweb.py | 770 ++++---- gramps/plugins/webreport/webcal.py | 170 +- gramps/plugins/webreport/webplugins.gpr.py | 2 +- gramps/plugins/webstuff/webstuff.gpr.py | 4 +- gramps/plugins/webstuff/webstuff.py | 10 +- gramps/test/__init__.py | 10 +- gramps/test/regrtest.py | 24 +- gramps/test/test/test_util_test.py | 30 +- gramps/test/test_util.py | 32 +- gramps/webapp/client.py | 2 +- gramps/webapp/connection.py | 4 +- gramps/webapp/default_settings.py | 10 +- gramps/webapp/grampsdb/admin.py | 8 +- gramps/webapp/grampsdb/forms.py | 116 +- gramps/webapp/grampsdb/models.py | 106 +- .../webapp/grampsdb/templatetags/my_tags.py | 6 +- gramps/webapp/grampsdb/view/citation.py | 26 +- gramps/webapp/grampsdb/view/family.py | 34 +- gramps/webapp/grampsdb/view/media.py | 30 +- gramps/webapp/grampsdb/view/person.py | 58 +- gramps/webapp/grampsdb/view/place.py | 10 +- gramps/webapp/grampsdb/view/png.py | 20 +- gramps/webapp/grampsdb/view/repository.py | 26 +- gramps/webapp/grampsdb/view/source.py | 26 +- gramps/webapp/grampsdb/view/tag.py | 12 +- gramps/webapp/libdjango.py | 482 ++--- gramps/webapp/modules_checkpoint.py | 2 +- gramps/webapp/reports.py | 2 +- gramps/webapp/urls.py | 32 +- 760 files changed, 16855 insertions(+), 16855 deletions(-) diff --git a/gramps/cli/__init__.py b/gramps/cli/__init__.py index b9bdf33b9..cf56f3cd0 100644 --- a/gramps/cli/__init__.py +++ b/gramps/cli/__init__.py @@ -21,4 +21,4 @@ Package init for the cli package. """ -# DO NOT IMPORT METHODS/CLASSES FROM src/gui HERE ! Only __all__ +# DO NOT IMPORT METHODS/CLASSES FROM src/gui HERE ! Only __all__ diff --git a/gramps/cli/arghandler.py b/gramps/cli/arghandler.py index 9984b8df4..fa81a0153 100644 --- a/gramps/cli/arghandler.py +++ b/gramps/cli/arghandler.py @@ -62,7 +62,7 @@ from gramps.gen.config import config def _split_options(options_str): """ Split the options for the action. - + Rules: * Entries in the list of options are separated by commas without @@ -74,7 +74,7 @@ def _split_options(options_str): * Text containing double quotes must be contained in single quotes * Text containing single quotes must be contained in double quotes * Text cannot include both single and double quotes - + Examples: Multiple options specified:: @@ -97,9 +97,9 @@ def _split_options(options_str): in_list = False quote_type = "" options_str_dict = {} - + for char in options_str: - if not parsing_value: + if not parsing_value: # Parsing the name of the option if char == "=": #print char, "This value ends the name" @@ -150,11 +150,11 @@ def _split_options(options_str): class ArgHandler(object): """ This class is responsible for the non GUI handling of commands. - The handler is passed a parser object, sanitizes it, and can execute the + The handler is passed a parser object, sanitizes it, and can execute the actions requested working on a :class:`.DbState`. """ - def __init__(self, dbstate, parser, sessionmanager, + def __init__(self, dbstate, parser, sessionmanager, errorfunc=None, gui=False): self.dbstate = dbstate self.sm = sessionmanager @@ -181,7 +181,7 @@ class ArgHandler(object): self.open = self.__handle_open_option(parser.open, parser.create) self.sanitize_args(parser.imports, parser.exports) - + def __error(self, msg1, msg2=None): """ Output an error. Uses errorfunc if given, otherwise a simple print. @@ -249,10 +249,10 @@ class ArgHandler(object): if fname != '-' and not os.path.exists(fullpath): self.__error(_('Error: Import file %s not found.') % fname) sys.exit(0) - + if family_tree_format is None: # Guess the file format based on the file extension. - # This will get the lower case extension without a period, + # This will get the lower case extension without a period, # or an empty string. family_tree_format = os.path.splitext(fname)[-1][1:].lower() @@ -261,16 +261,16 @@ class ArgHandler(object): for plugin in pmgr.get_import_plugins(): if family_tree_format == plugin.get_extension(): plugin_found = True - + if plugin_found: self.imports.append((fname, family_tree_format)) else: self.__error(_('Error: Unrecognized type: "%(format)s" for ' - 'import file: %(filename)s') % - {'format' : family_tree_format, + 'import file: %(filename)s') % + {'format' : family_tree_format, 'filename' : fname}) sys.exit(0) - + def __handle_export_option(self, value, family_tree_format): """ Handle the "-e" or "--export" option. @@ -290,17 +290,17 @@ class ArgHandler(object): message = _("WARNING: Output file already exists!\n" "WARNING: It will be overwritten:\n %s" ) % fullpath - accepted = self.user.prompt(_('OK to overwrite?'), message, + accepted = self.user.prompt(_('OK to overwrite?'), message, _('yes'), _('no')) if accepted: - self.__error(_("Will overwrite the existing file: %s") + self.__error(_("Will overwrite the existing file: %s") % fullpath) else: sys.exit(0) if family_tree_format is None: # Guess the file format based on the file extension. - # This will get the lower case extension without a period, + # This will get the lower case extension without a period, # or an empty string. family_tree_format = os.path.splitext(fname)[-1][1:].lower() @@ -309,18 +309,18 @@ class ArgHandler(object): for plugin in pmgr.get_export_plugins(): if family_tree_format == plugin.get_extension(): plugin_found = True - + if plugin_found: self.exports.append((fullpath, family_tree_format)) else: - self.__error(_("ERROR: Unrecognized format for export file %s") + self.__error(_("ERROR: Unrecognized format for export file %s") % fname) sys.exit(0) - + def __deduce_db_path(self, db_name_or_path): """ Attempt to find a database path for the given parameter. - + :returns: The path to a Gramps DB or None if a database can not be deduced. """ @@ -336,20 +336,20 @@ class ArgHandler(object): name_file_path = os.path.join(fullpath, NAME_FILE) if os.path.isfile(name_file_path): db_path = fullpath - + return db_path #------------------------------------------------------------------------- - # Overall argument handler: + # Overall argument handler: # sorts out the sequence and details of operations #------------------------------------------------------------------------- def handle_args_gui(self): """ Method to handle the arguments that can be given for a GUI session. - :returns: the filename of the family tree that should be opened if + :returns: the filename of the family tree that should be opened if user just passed a famtree or a filename. - + 1. no options: a family tree can be given, if so, this name is tested and returned. If a filename, it is imported in a new db and name of new db returned @@ -380,22 +380,22 @@ class ArgHandler(object): else: sys.exit(0) return db_path - - # if not open_gui, parse any command line args. We can only have one + + # if not open_gui, parse any command line args. We can only have one # open argument, and perhaps some import arguments self.__open_action() self.__import_action() return None - + def handle_args_cli(self, cleanup=True): """ Depending on the given arguments, import or open data, launch session, write files, and/or perform actions. - + :param: climan: the manager of a CLI session :type: :class:`.CLIManager` object """ - # Handle the "-l" List Family Trees option. + # Handle the "-l" List Family Trees option. if self.list: print(_('List of known Family Trees in your database path\n')) @@ -406,7 +406,7 @@ class ArgHandler(object): % {'full_DB_path' : dirname, 'f_t_name' : name}) sys.exit(0) - # Handle the "-L" List Family Trees in detail option. + # Handle the "-L" List Family Trees in detail option. if self.list_more: print(_('Gramps Family Trees:')) summary_list = self.dbman.family_tree_summary() @@ -420,8 +420,8 @@ class ArgHandler(object): 'item' : item, 'summary' : summary[item] } ) sys.exit(0) - - # Handle the "-t" List Family Trees, tab delimited option. + + # Handle the "-t" List Family Trees, tab delimited option. if self.list_table: print(_('Gramps Family Trees:')) summary_list = self.dbman.family_tree_summary() @@ -446,7 +446,7 @@ class ArgHandler(object): self.__open_action() self.__import_action() - + for (action, op_string) in self.actions: print(_("Performing action: %s.") % action, file=sys.stderr) if op_string: @@ -475,7 +475,7 @@ class ArgHandler(object): def __import_action(self): """ Take action for all given import files. - + .. note:: Family trees are not supported. If a family tree is open, the import happens on top of it. If not @@ -496,7 +496,7 @@ class ArgHandler(object): dbid = config.get('behavior.database-backend') newdb = self.dbstate.make_database(dbid) newdb.write_version(self.imp_db_path) - + try: self.sm.open_activate(self.imp_db_path) msg = _("Created empty Family Tree successfully") @@ -514,11 +514,11 @@ class ArgHandler(object): def __open_action(self): """ - Take action on a family tree dir to open. It will be opened in the + Take action on a family tree dir to open. It will be opened in the session manager """ if self.open: - # Family Tree to open was given. Open it + # Family Tree to open was given. Open it # Then go on and process the rest of the command line arguments. self.cl = bool(self.exports or self.actions) @@ -570,7 +570,7 @@ class ArgHandler(object): #------------------------------------------------------------------------- def cl_export(self, filename, family_tree_format): """ - Command-line export routine. + Command-line export routine. Try to write into filename using the family_tree_format. """ pmgr = BasePluginManager.get_instance() @@ -605,15 +605,15 @@ class ArgHandler(object): mod = pmgr.load_plugin(pdata) if not mod: #import of plugin failed - return + return category = pdata.category report_class = eval('mod.' + pdata.reportclass) options_class = eval('mod.' + pdata.optionclass) if category in (CATEGORY_BOOK, CATEGORY_CODE): - options_class(self.dbstate.db, name, category, + options_class(self.dbstate.db, name, category, options_str_dict) else: - cl_report(self.dbstate.db, name, category, + cl_report(self.dbstate.db, name, category, report_class, options_class, options_str_dict) return @@ -653,16 +653,16 @@ class ArgHandler(object): mod = pmgr.load_plugin(pdata) if not mod: #import of plugin failed - return + return category = pdata.category tool_class = eval('mod.' + pdata.toolclass) options_class = eval('mod.' + pdata.optionclass) tool.cli_tool( - dbstate=self.dbstate, - name=name, - category=category, + dbstate=self.dbstate, + name=name, + category=category, tool_class=tool_class, - options_class=options_class, + options_class=options_class, options_str_dict=options_str_dict, user=self.user) return @@ -696,7 +696,7 @@ class ArgHandler(object): book_list = BookList('books.xml', self.dbstate.db) if name: if name in book_list.get_book_names(): - cl_book(self.dbstate.db, name, book_list.get_book(name), + cl_book(self.dbstate.db, name, book_list.get_book(name), options_str_dict) return msg = _("Unknown book name.") diff --git a/gramps/cli/argparser.py b/gramps/cli/argparser.py index 8e0233df3..e503c70df 100644 --- a/gramps/cli/argparser.py +++ b/gramps/cli/argparser.py @@ -83,10 +83,10 @@ Example of usage of Gramps command line interface 1. To import four databases (whose formats can be determined from their names) and then check the resulting database for errors, one may type: -gramps -i file1.ged -i file2.gpkg -i ~/db3.gramps -i file4.wft -a tool -p name=check. +gramps -i file1.ged -i file2.gpkg -i ~/db3.gramps -i file4.wft -a tool -p name=check. 2. To explicitly specify the formats in the above example, append filenames with appropriate -f options: -gramps -i file1.ged -f gedcom -i file2.gpkg -f gramps-pkg -i ~/db3.gramps -f gramps-xml -i file4.wft -f wft -a tool -p name=check. +gramps -i file1.ged -f gedcom -i file2.gpkg -f gramps-pkg -i ~/db3.gramps -f gramps-xml -i file4.wft -f wft -a tool -p name=check. 3. To record the database resulting from all imports, supply -e flag (use -f if the filename does not allow Gramps to guess the format): @@ -154,32 +154,32 @@ class ArgParser(object): -h, --help Display the help --usage Display usage information - If the filename (no options) is specified, the interactive session is - launched using data from filename. In this mode (filename, no options), the + If the filename (no options) is specified, the interactive session is + launched using data from filename. In this mode (filename, no options), the rest of the arguments are ignored. This is a mode suitable by default for GUI launchers, mime type handlers, and the like. - + If no filename or -i option is given, a new interactive session (empty database) is launched, since no data is given anyway. - + If -O or -i option is given, but no -e or -a options are given, an - interactive session is launched with the ``FILENAME`` (specified with -i). - + interactive session is launched with the ``FILENAME`` (specified with -i). + If both input (-O or -i) and processing (-e or -a) options are given, interactive session will not be launched. - + When using import ot export options (-i or -e), the -f option may be specified to indicate the family tree format. - + Possible values for ``ACTION`` are: 'report', 'book' and 'tool'. - + Configuration ``SETTINGS`` may be specified using the -c option. The settings are of the form config.setting[:value]. If used without a value, - the setting is shown. - - If the -y option is given, the user's acceptance of any CLI prompt is + the setting is shown. + + If the -y option is given, the user's acceptance of any CLI prompt is assumed. (see :meth:`.cli.user.User.prompt`) - + If the -q option is given, extra noise on sys.stderr, such as progress indicators, is suppressed. """ @@ -240,9 +240,9 @@ class ArgParser(object): cliargs += "]" # Must first do str() of the msg object. msg = str(msg) - self.errors += [(_('Error parsing the arguments'), + self.errors += [(_('Error parsing the arguments'), msg + '\n' + - _("Error parsing the arguments: %s \n" + _("Error parsing the arguments: %s \n" "Type gramps --help for an overview of commands, or " "read the manual pages.") % cliargs)] return @@ -273,13 +273,13 @@ class ArgParser(object): elif option in ['-i', '--import']: family_tree_format = None if opt_ix < len(options) - 1 \ - and options[opt_ix + 1][0] in ( '-f', '--format'): + and options[opt_ix + 1][0] in ( '-f', '--format'): family_tree_format = options[opt_ix + 1][1] self.imports.append((value, family_tree_format)) elif option in ['-e', '--export']: family_tree_format = None if opt_ix < len(options) - 1 \ - and options[opt_ix + 1][0] in ( '-f', '--format'): + and options[opt_ix + 1][0] in ( '-f', '--format'): family_tree_format = options[opt_ix + 1][1] self.exports.append((value, family_tree_format)) elif option in ['-a', '--action']: @@ -290,7 +290,7 @@ class ArgParser(object): continue options_str = "" if opt_ix < len(options)-1 \ - and options[opt_ix+1][0] in ( '-p', '--options' ): + and options[opt_ix+1][0] in ( '-p', '--options' ): options_str = options[opt_ix+1][1] self.actions.append((action, options_str)) elif option in ['-d', '--debug']: @@ -362,12 +362,12 @@ class ArgParser(object): self.auto_accept = True elif option in ['-q', '--quiet']: self.quiet = True - + #clean options list cleandbg.reverse() for ind in cleandbg: del options[ind] - + if len(options) > 0 and self.open is None and self.imports == [] \ and not (self.list or self.list_more or self.list_table or self.help or self.runqml): @@ -394,10 +394,10 @@ class ArgParser(object): """ Determine whether we need a GUI session for the given tasks. """ - if self.errors: + if self.errors: #errors in argument parsing ==> give cli error, no gui needed return False - + if self.list or self.list_more or self.list_table or self.help: return False @@ -419,10 +419,10 @@ class ArgParser(object): else: # data given, but no action/export => GUI return True - + # No data, can only do GUI here return True - + def print_help(self): """ If the user gives the --help or -h option, print the output to terminal. diff --git a/gramps/cli/clidbman.py b/gramps/cli/clidbman.py index 176ed9ee3..9f0a29c7e 100644 --- a/gramps/cli/clidbman.py +++ b/gramps/cli/clidbman.py @@ -98,29 +98,29 @@ class CLIDbManager(object): IND_TVAL = 4 IND_USE_ICON_BOOL = 5 IND_STOCK_ID =6 - + ICON_NONE = 0 ICON_RECOVERY = 1 ICON_LOCK = 2 ICON_OPEN = 3 - + ICON_MAP = { ICON_NONE : None, ICON_RECOVERY : None, ICON_LOCK : None, ICON_OPEN : None, } - + ERROR = _errordialog def __init__(self, dbstate): self.dbstate = dbstate self.msg = None - + if dbstate: self.active = dbstate.db.get_save_path() else: self.active = None - + self.current_names = [] if dbstate: self._populate_cli() @@ -180,7 +180,7 @@ class CLIDbManager(object): # make the default directory if it does not exist summary_list = [] for item in self.current_names: - (name, dirpath, path_name, last, + (name, dirpath, path_name, last, tval, enable, stock_id) = item retval = self.get_dbdir_summary(dirpath, name) summary_list.append( retval ) @@ -205,7 +205,7 @@ class CLIDbManager(object): file.close() (tval, last) = time_val(dirpath) - (enable, stock_id) = self.icon_values(dirpath, self.active, + (enable, stock_id) = self.icon_values(dirpath, self.active, self.dbstate.db.is_open()) if (stock_id == 'gramps-lock'): @@ -271,7 +271,7 @@ class CLIDbManager(object): newdb.write_version(new_path) (tval, last) = time_val(new_path) - + self.current_names.append((title, new_path, path_name, last, tval, False, "")) return new_path, title @@ -285,7 +285,7 @@ class CLIDbManager(object): def import_new_db(self, filename, user): """ Attempt to import the provided file into a new database. - A new database will only be created if an appropriate importer was + A new database will only be created if an appropriate importer was found. :param filename: a fully-qualified path, filename, and @@ -293,7 +293,7 @@ class CLIDbManager(object): :param user: a :class:`.cli.user.User` or :class:`.gui.user.User` instance for managing user interaction. - + :returns: A tuple of (new_path, name) for the new database or (None, None) if no import was performed. """ @@ -330,21 +330,21 @@ class CLIDbManager(object): if format == plugin.get_extension(): new_path, name = self._create_new_db(name) - + # Create a new database self.__start_cursor(_("Importing data...")) dbid = config.get('behavior.database-backend') dbase = self.dbstate.make_database(dbid) dbase.load(new_path, user.callback) - + import_function = plugin.get_import_function() import_function(dbase, filename, user) - + # finish up self.__end_cursor() dbase.close() - + return new_path, name return None, None @@ -390,7 +390,7 @@ class CLIDbManager(object): """ if os.path.exists(os.path.join(dbpath, "lock")): os.unlink(os.path.join(dbpath, "lock")) - + def icon_values(self, dirpath, active, is_open): """ If the directory path is the active path, then return values @@ -448,7 +448,7 @@ def find_next_db_dir(): def time_val(dirpath): """ Return the last modified time of the database. We do this by looking - at the modification time of the meta db file. If this file does not + at the modification time of the meta db file. If this file does not exist, we indicate that database as never modified. """ meta = os.path.join(dirpath, META_NAME) diff --git a/gramps/cli/grampscli.py b/gramps/cli/grampscli.py index d7b9afea6..a1073e312 100644 --- a/gramps/cli/grampscli.py +++ b/gramps/cli/grampscli.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -50,9 +50,9 @@ from gramps.gen.const import PLUGINS_DIR, USER_PLUGINS from gramps.gen.db.dbconst import DBBACKEND from gramps.gen.errors import DbError from gramps.gen.dbstate import DbState -from gramps.gen.db.exceptions import (DbUpgradeRequiredError, - BsddbDowngradeError, - DbVersionError, +from gramps.gen.db.exceptions import (DbUpgradeRequiredError, + BsddbDowngradeError, + DbVersionError, DbEnvironmentError, BsddbUpgradeRequiredError, BsddbDowngradeRequiredError, @@ -74,13 +74,13 @@ class CLIDbLoader(object): """ def __init__(self, dbstate): self.dbstate = dbstate - + def _warn(self, title, warnmessage): """ Issue a warning message. Inherit for GUI action """ print(_('WARNING: %s') % warnmessage, file=sys.stderr) - + def _errordialog(self, title, errormessage): """ Show the error. A title for the error and an errormessage @@ -88,30 +88,30 @@ class CLIDbLoader(object): """ print(_('ERROR: %s') % errormessage, file=sys.stderr) sys.exit(1) - + def _dberrordialog(self, msg): """ - Show a database error. + Show a database error. :param msg: an error message :type msg : string .. note:: Inherit for GUI action """ - self._errordialog( '', _("Low level database corruption detected") + self._errordialog( '', _("Low level database corruption detected") + '\n' + _("Gramps has detected a problem in the underlying " "Berkeley database. This can be repaired from " "the Family Tree Manager. Select the database and " 'click on the Repair button') + '\n\n' + str(msg)) - + def _begin_progress(self): """ Convenience method to allow to show a progress bar if wanted on load actions. Inherit if needed """ pass - + def _pulse_progress(self, value): """ Convenience method to allow to show a progress bar if wanted on load @@ -129,9 +129,9 @@ class CLIDbLoader(object): def read_file(self, filename): """ This method takes care of changing database, and loading the data. - In 3.0 we only allow reading of real databases of filetype + In 3.0 we only allow reading of real databases of filetype 'x-directory/normal' - + This method should only return on success. Returning on failure makes no sense, because we cannot recover, since database has already been changed. @@ -144,7 +144,7 @@ class CLIDbLoader(object): if os.path.exists(filename): if not os.access(filename, os.W_OK): mode = "r" - self._warn(_('Read only database'), + self._warn(_('Read only database'), _('You do not have write access ' 'to the selected file.')) else: @@ -160,12 +160,12 @@ class CLIDbLoader(object): dbid = "bsddb" db = self.dbstate.make_database(dbid) - + self.dbstate.change_database(db) self.dbstate.db.disable_signals() self._begin_progress() - + try: self.dbstate.db.load(filename, self._pulse_progress, mode) self.dbstate.db.set_save_path(filename) @@ -213,8 +213,8 @@ class CLIDbLoader(object): class CLIManager(object): """ - Sessionmanager for Gramps. This is in effect a reduced :class:`.ViewManager` - instance (see gui/viewmanager), suitable for CLI actions. + Sessionmanager for Gramps. This is in effect a reduced :class:`.ViewManager` + instance (see gui/viewmanager), suitable for CLI actions. Aim is to manage a dbstate on which to work (load, unload), and interact with the plugin session """ @@ -233,14 +233,14 @@ class CLIManager(object): Open and make a family tree active """ self._read_recent_file(path) - + def _errordialog(self, title, errormessage): """ Show the error. A title for the error and an errormessage """ print(_('ERROR: %s') % errormessage, file=sys.stderr) sys.exit(1) - + def _read_recent_file(self, filename): """ Called when a file needs to be loaded @@ -250,7 +250,7 @@ class CLIManager(object): # also updated the recent file menu info in displaystate.py if not os.path.isdir(filename): self._errordialog( - _("Could not load a recent Family Tree."), + _("Could not load a recent Family Tree."), _("Family Tree does not exist, as it has been deleted.")) return @@ -272,21 +272,21 @@ class CLIManager(object): title = filename self._post_load_newdb(filename, 'x-directory/normal', title) - + def _post_load_newdb(self, filename, filetype, title=None): """ - The method called after load of a new database. + The method called after load of a new database. Here only CLI stuff is done, inherit this method to add extra stuff """ self._post_load_newdb_nongui(filename, title) - + def _post_load_newdb_nongui(self, filename, title=None): """ Called after a new database is loaded. """ if not filename: return - + if filename[-1] == os.path.sep: filename = filename[:-1] name = os.path.basename(filename) @@ -298,7 +298,7 @@ class CLIManager(object): # Window title, recent files, etc related to new file. self.dbstate.db.set_save_path(filename) - + # apply preferred researcher if loaded file has none res = self.dbstate.db.get_researcher() owner = get_researcher() @@ -307,7 +307,7 @@ class CLIManager(object): # database is empty, then copy default researcher to DB owner if res.is_empty() and not owner.is_empty() and self.dbstate.db.is_empty(): self.dbstate.db.set_researcher(owner) - + name_displayer.set_name_format(self.dbstate.db.name_formats) fmt_default = config.get('preferences.name-format') name_displayer.set_default_format(fmt_default) @@ -319,7 +319,7 @@ class CLIManager(object): recent_files(filename, name) self.file_loaded = True - + def do_reg_plugins(self, dbstate, uistate): """ Register the plugins at initialization time. @@ -341,15 +341,15 @@ def startcli(errors, argparser): errmsg = _(' Details: %s') % errors[0][1] print(errmsg, file=sys.stderr) sys.exit(1) - - if argparser.errors: + + if argparser.errors: errmsg = _('Error encountered in argument parsing: %s') \ % argparser.errors[0][0] print(errmsg, file=sys.stderr) errmsg = _(' Details: %s') % argparser.errors[0][1] print(errmsg, file=sys.stderr) sys.exit(1) - + #we need to keep track of the db state dbstate = DbState() @@ -365,7 +365,7 @@ def startcli(errors, argparser): from .arghandler import ArgHandler handler = ArgHandler(dbstate, argparser, climanager) # create a manager to manage the database - + handler.handle_args_cli() - + sys.exit(0) diff --git a/gramps/cli/plug/__init__.py b/gramps/cli/plug/__init__.py index 97c389103..e2ecdead9 100644 --- a/gramps/cli/plug/__init__.py +++ b/gramps/cli/plug/__init__.py @@ -47,14 +47,14 @@ log = logging.getLogger(".") from gramps.gen.plug import BasePluginManager from gramps.gen.plug.docgen import (StyleSheet, StyleSheetList, PaperStyle, PAPER_PORTRAIT, PAPER_LANDSCAPE, graphdoc) -from gramps.gen.plug.menu import (FamilyOption, PersonOption, NoteOption, - MediaOption, PersonListOption, NumberOption, - BooleanOption, DestinationOption, StringOption, +from gramps.gen.plug.menu import (FamilyOption, PersonOption, NoteOption, + MediaOption, PersonListOption, NumberOption, + BooleanOption, DestinationOption, StringOption, TextOption, EnumeratedListOption, Option) from gramps.gen.display.name import displayer as name_displayer from gramps.gen.errors import ReportError, FilterError from gramps.gen.plug.report import (CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_BOOK, - CATEGORY_GRAPHVIZ, CATEGORY_CODE, + CATEGORY_GRAPHVIZ, CATEGORY_CODE, ReportOptions, append_styles) from gramps.gen.plug.report._paper import paper_sizes from gramps.gen.const import USER_HOME @@ -75,7 +75,7 @@ def _convert_str_to_match_type(str_val, type_val): """ str_val = str_val.strip() ret_type = type(type_val) - + if isinstance(type_val, str): if ( str_val.startswith("'") and str_val.endswith("'") ) or \ ( str_val.startswith('"') and str_val.endswith('"') ): @@ -83,21 +83,21 @@ def _convert_str_to_match_type(str_val, type_val): return str(str_val[1:-1]) else: return str(str_val) - + elif ret_type == int: if str_val.isdigit(): return int(str_val) else: print("'%s' is not an integer number" % str_val) return 0 - + elif ret_type == float: try: return float(str_val) except ValueError: print("'%s' is not a decimal number" % str_val) return 0.0 - + elif ret_type == bool: if str_val == str(True): return True @@ -106,16 +106,16 @@ def _convert_str_to_match_type(str_val, type_val): else: print("'%s' is not a boolean-- try 'True' or 'False'" % str_val) return False - + elif ret_type == list: ret_val = [] if not ( str_val.startswith("[") and str_val.endswith("]") ): print("'%s' is not a list-- try: [%s]" % (str_val, str_val)) return ret_val - + entry = "" quote_type = None - + # Search through characters between the brackets for char in str_val[1:-1]: if (char == "'" or char == '"') and quote_type == None: @@ -135,21 +135,21 @@ def _convert_str_to_match_type(str_val, type_val): if entry != "": # Add the last entry ret_val.append(entry.strip()) - + return ret_val def _validate_options(options, dbase): """ Validate all options by making sure that their values are consistent with the database. - + menu: The Menu class dbase: the database the options will be applied to """ if not hasattr(options, "menu"): return menu = options.menu - + for name in menu.get_all_option_names(): option = menu.get_option_by_name(name) @@ -169,7 +169,7 @@ def _validate_options(options, dbase): file=sys.stderr) if person: option.set_value(person.get_gramps_id()) - + elif isinstance(option, FamilyOption): fid = option.get_value() family = dbase.get_family_from_gramps_id(fid) @@ -204,7 +204,7 @@ class CommandLineReport(object): def __init__(self, database, name, category, option_class, options_str_dict, noopt=False): - + pmgr = BasePluginManager.get_instance() self.__textdoc_plugins = [] self.__drawdoc_plugins = [] @@ -218,7 +218,7 @@ class CommandLineReport(object): plugin.get_draw_support() and \ plugin.get_extension(): self.__bookdoc_plugins.append(plugin) - + self.database = database self.category = category self.format = None @@ -282,20 +282,20 @@ class CommandLineReport(object): if noopt: return - self.options_help['of'][2] = os.path.join(USER_HOME, + self.options_help['of'][2] = os.path.join(USER_HOME, "whatever_name") if self.category == CATEGORY_TEXT: for plugin in self.__textdoc_plugins: - self.options_help['off'][2].append( + self.options_help['off'][2].append( plugin.get_extension() + "\t" + plugin.get_description() ) elif self.category == CATEGORY_DRAW: for plugin in self.__drawdoc_plugins: - self.options_help['off'][2].append( + self.options_help['off'][2].append( plugin.get_extension() + "\t" + plugin.get_description() ) elif self.category == CATEGORY_BOOK: for plugin in self.__bookdoc_plugins: - self.options_help['off'][2].append( + self.options_help['off'][2].append( plugin.get_extension() + "\t" + plugin.get_description() ) elif self.category == CATEGORY_GRAPHVIZ: for graph_format in graphdoc.FORMATS: @@ -305,7 +305,7 @@ class CommandLineReport(object): self.options_help['off'][2] = "NA" self.options_help['papers'][2] = \ - [ paper.get_name() for paper in paper_sizes + [ paper.get_name() for paper in paper_sizes if paper.get_name() != 'Custom Size' ] self.options_help['papero'][2] = [ @@ -322,9 +322,9 @@ class CommandLineReport(object): # Read all style sheets available for this item style_file = self.option_class.handler.get_stylesheet_savefile() self.style_list = StyleSheetList(style_file, default_style) - + self.options_help['style'][2] = self.style_list.get_style_names() - + def init_report_options(self): """ Initialize the options that are defined by each report. @@ -344,7 +344,7 @@ class CommandLineReport(object): for name in menu.get_all_option_names(): option = menu.get_option_by_name(name) self.options_dict[name] = option.get_value() - + def init_report_options_help(self): """ Initialize help for the options that are defined by each report. @@ -356,7 +356,7 @@ class CommandLineReport(object): for name in menu.get_all_option_names(): option = menu.get_option_by_name(name) self.options_help[name] = [ "", option.get_help() ] - + if isinstance(option, PersonOption): id_list = [] for person_handle in self.database.get_person_handles(True): @@ -426,7 +426,7 @@ class CommandLineReport(object): "and acceptable values") % {'donottranslate' : "show=option"}, file=sys.stderr) - + def parse_options(self): """ Load the options that the user has entered. @@ -440,7 +440,7 @@ class CommandLineReport(object): _format_str = self.options_str_dict.pop('off', None) if _format_str: self.options_dict['off'] = _format_str - + self.css_filename = None _chosen_format = None @@ -489,7 +489,7 @@ class CommandLineReport(object): for opt in self.options_str_dict: if opt in self.options_dict: self.options_dict[opt] = \ - _convert_str_to_match_type(self.options_str_dict[opt], + _convert_str_to_match_type(self.options_str_dict[opt], self.options_dict[opt]) self.option_class.handler.options_dict[opt] = \ @@ -498,7 +498,7 @@ class CommandLineReport(object): if menu and opt in menu_opt_names: option = menu.get_option_by_name(opt) option.set_value(self.options_dict[opt]) - + else: print(_("Ignoring unknown option: %s") % opt, file=sys.stderr) print(_(" Valid options are:"), @@ -507,7 +507,7 @@ class CommandLineReport(object): print(_(" Use '%(donottranslate)s' to see description " "and acceptable values") % {'donottranslate' : "show=option"}, file=sys.stderr) - + self.option_class.handler.output = self.options_dict['of'] self.paper = paper_sizes[0] # make sure one exists @@ -517,7 +517,7 @@ class CommandLineReport(object): self.option_class.handler.set_paper(self.paper) self.orien = self.options_dict['papero'] - + self.marginl = self.options_dict['paperml'] self.marginr = self.options_dict['papermr'] self.margint = self.options_dict['papermt'] @@ -609,11 +609,11 @@ class CommandLineReport(object): # Command-line report generic task # #------------------------------------------------------------------------ -def cl_report(database, name, category, report_class, options_class, +def cl_report(database, name, category, report_class, options_class, options_str_dict): - + err_msg = _("Failed to write report. ") - clr = CommandLineReport(database, name, category, options_class, + clr = CommandLineReport(database, name, category, options_class, options_str_dict) # Exit here if show option was given @@ -676,7 +676,7 @@ def run_report(db, name, **options_str_dict): options_str_dict is the same kind of options given at the command line. For example: - + >>> run_report(db, "ancestor_report", off="txt", of="ancestor-007.txt", pid="I37") @@ -703,10 +703,10 @@ def run_report(db, name, **options_str_dict): report_class = getattr(mod, pdata.reportclass) options_class = getattr(mod, pdata.optionclass) if category in (CATEGORY_BOOK, CATEGORY_CODE): - options_class(db, name, category, + options_class(db, name, category, options_str_dict) else: - clr = cl_report(db, name, category, + clr = cl_report(db, name, category, report_class, options_class, options_str_dict) return clr @@ -725,7 +725,7 @@ def cl_book(database, name, book, options_str_dict): # Exit here if show option was given if clr.show: return - + # write report doc = clr.format(None, PaperStyle(clr.paper, clr.orien, clr.marginl, diff --git a/gramps/cli/test/argparser_test.py b/gramps/cli/test/argparser_test.py index 3f3006803..734fc3b51 100644 --- a/gramps/cli/test/argparser_test.py +++ b/gramps/cli/test/argparser_test.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -32,7 +32,7 @@ try: from unittest.mock import Mock MOCKING = True - + except: MOCKING = False print ("Mocking disabled", sys.exc_info()[0:2]) diff --git a/gramps/cli/test/cli_test.py b/gramps/cli/test/cli_test.py index 252f0eb61..cc9f08497 100644 --- a/gramps/cli/test/cli_test.py +++ b/gramps/cli/test/cli_test.py @@ -67,9 +67,9 @@ class Test(unittest.TestCase): def test1_setup_works(self): self.assertTrue(os.path.exists(ddir), "data dir %r exists" % ddir) self.assertTrue(os.path.exists(min1r), "data file %r exists" % min1r) - self.assertFalse(os.path.exists(out_ged), + self.assertFalse(os.path.exists(out_ged), "NO out file %r yet" % out_ged) - + # This tests the fix for bug #1331-1334 # read trivial gedcom input, write gedcom output def test2_exec_CLI(self): @@ -91,7 +91,7 @@ class Test(unittest.TestCase): g = re.search("INDI", content) self.assertTrue(g, "found 'INDI' in output file") - # this verifies that files in the temporary "import dir" + # this verifies that files in the temporary "import dir" # get cleaned before (and after) running a CLI # (eg cleanout stale files from prior crash-runs) def test3_files_in_import_dir(self): @@ -104,7 +104,7 @@ class Test(unittest.TestCase): for fn in bogofiles: with io.open(fn, "w") as f: f.write("garbage") - + # ~same as test 2 pyexec = sys.executable ifile = min1r diff --git a/gramps/cli/test/user_test.py b/gramps/cli/test/user_test.py index a2bb2a6c8..e1da67426 100644 --- a/gramps/cli/test/user_test.py +++ b/gramps/cli/test/user_test.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -33,7 +33,7 @@ try: from unittest.mock import Mock, patch MOCKING = True - + except: MOCKING = False print ("Mocking disabled", sys.exc_info()[0:2]) @@ -69,7 +69,7 @@ class TestUser_prompt(unittest.TestCase): self.user._input.assert_called_once_with() def assert_prompt_contains_text(self, text, - title=TestUser.TITLE, msg=TestUser.MSG, + title=TestUser.TITLE, msg=TestUser.MSG, accept=TestUser.ACCEPT, reject=TestUser.REJECT): self.user._input.configure_mock(return_value = TestUser.REJECT) self.user.prompt(title, msg, accept, reject) @@ -160,7 +160,7 @@ class TestUser_progress(unittest.TestCase): self.expected_output = list(self.user._fileout.method_calls) self.user._fileout.reset_mock() self.assertTrue( - len(self.user._fileout.method_calls) == 0, + len(self.user._fileout.method_calls) == 0, list(self.user._fileout.method_calls)) with self.user.progress("Foo", "Bar", 0) as step: @@ -168,7 +168,7 @@ class TestUser_progress(unittest.TestCase): step() # Output using `with' differs from one with `progress_...' - self.assertEqual(self.expected_output, + self.assertEqual(self.expected_output, list(self.user._fileout.method_calls)) def test_ends_progress_upon_exception_in_with(self): diff --git a/gramps/cli/user.py b/gramps/cli/user.py index cc66c396b..8e0f8715a 100644 --- a/gramps/cli/user.py +++ b/gramps/cli/user.py @@ -60,7 +60,7 @@ class User(user.User): self.current_step = 0; self._input = input - def yes(*args): + def yes(*args): return True if auto_accept: @@ -68,11 +68,11 @@ class User(user.User): if quiet: self.begin_progress = self.end_progress = self.step_progress = \ self._default_callback = yes - + def begin_progress(self, title, message, steps): """ Start showing a progress indicator to the user. - + :param title: the title of the progress meter :type title: str :param message: the message associated with the progress meter @@ -90,7 +90,7 @@ class User(user.User): self._fileout.write(_SPINNER[self.current_step]) else: self._fileout.write("00%") - + def step_progress(self): """ Advance the progress meter. @@ -108,11 +108,11 @@ class User(user.User): Stop showing the progress indicator to the user. """ self._fileout.write("\r100%\n") - + def prompt(self, title, message, accept_label, reject_label, parent=None): """ Prompt the user with a message to select an alternative. - + :param title: the title of the question, e.g.: "Undo history warning" :type title: str :param message: the message, e.g.: "Proceeding with the tool will erase @@ -140,11 +140,11 @@ class User(user.User): return reply == "" or reply == accept_label except EOFError: return False - + def warn(self, title, warning=""): """ Warn the user. - + :param title: the title of the warning :type title: str :param warning: the warning @@ -152,11 +152,11 @@ class User(user.User): :returns: none """ self._fileout.write("%s %s" % (title, warning)) - + def notify_error(self, title, error=""): """ Notify the user of an error. - + :param title: the title of the error :type title: str :param error: the error message @@ -171,7 +171,7 @@ class User(user.User): def notify_db_error(self, error): """ Notify the user of a DB error. - + :param error: the error message :type error: str :returns: none diff --git a/gramps/gen/__init__.py b/gramps/gen/__init__.py index fbb18683c..ecc759cb4 100644 --- a/gramps/gen/__init__.py +++ b/gramps/gen/__init__.py @@ -20,7 +20,7 @@ # gen/__init__.py """ -The gen module provides packages that are common to all gramps +The gen module provides packages that are common to all gramps interfaces (gui, cli and web). """ diff --git a/gramps/gen/config.py b/gramps/gen/config.py index 0995cf21d..2b72344c4 100644 --- a/gramps/gen/config.py +++ b/gramps/gen/config.py @@ -3,7 +3,7 @@ # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2005-2007 Donald N. Allingham -# Copyright (C) 2008-2009 Gary Burton +# Copyright (C) 2008-2009 Gary Burton # Copyright (C) 2009-2012 Doug Blank # Copyright (C) 2011 Tim G L Lyons # @@ -94,7 +94,7 @@ def save(filename=None): return CONFIGMAN.save(filename) def connect(key, func): - """ + """ Module shortcut to connect a key to a callback func. Returns a unique callback ID number. """ @@ -155,10 +155,10 @@ register('behavior.web-search-url', 'http://google.com/#&q=%(text)s') register('behavior.addons-url', "https://raw.githubusercontent.com/gramps-project/addons/master/gramps50") register('export.proxy-order', [ - ["privacy", 0], - ["living", 0], - ["person", 0], - ["note", 0], + ["privacy", 0], + ["living", 0], + ["person", 0], + ["note", 0], ["reference", 0], ]) @@ -187,7 +187,7 @@ register('interface.clipboard-height', 300) register('interface.clipboard-width', 300) register('interface.dont-ask', False) register('interface.view-categories', - ["Dashboard", "People", "Relationships", "Families", + ["Dashboard", "People", "Relationships", "Families", "Ancestry", "Events", "Places", "Geography", "Sources", "Citations", "Repositories", "Media", "Notes"]) register('interface.edit-filter-width', 500) @@ -279,7 +279,7 @@ register('paths.recent-import-dir', '') register('paths.report-directory', USER_HOME) register('paths.website-directory', USER_HOME) register('paths.quick-backup-directory', USER_HOME) -register('paths.quick-backup-filename', +register('paths.quick-backup-filename', "%(filename)s_%(year)d-%(month)02d-%(day)02d.%(extension)s") register('preferences.date-format', 0) diff --git a/gramps/gen/constfunc.py b/gramps/gen/constfunc.py index 1860ccb1f..7e68ba0f8 100644 --- a/gramps/gen/constfunc.py +++ b/gramps/gen/constfunc.py @@ -70,7 +70,7 @@ def lin(): if platform.system() in LINUX: return True return False - + def mac(): """ Return True if a Macintosh system @@ -93,7 +93,7 @@ def win(): def is_quartz(): """ - Tests to see if Python is currently running with gtk and + Tests to see if Python is currently running with gtk and windowing system is Mac OS-X's "quartz". """ if mac(): @@ -107,7 +107,7 @@ def is_quartz(): def has_display(): """ - Tests to see if Python is currently running with gtk + Tests to see if Python is currently running with gtk """ # FIXME: currently, Gtk.init_check() requires all strings # in argv, and we might have unicode. diff --git a/gramps/gen/datehandler/__init__.py b/gramps/gen/datehandler/__init__.py index 4174cca3f..545d25b72 100644 --- a/gramps/gen/datehandler/__init__.py +++ b/gramps/gen/datehandler/__init__.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -32,7 +32,7 @@ import logging from ..const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext # import prerequisites for localized handlers -from ._datehandler import (LANG, LANG_SHORT, LANG_TO_PARSER, LANG_TO_DISPLAY, +from ._datehandler import (LANG, LANG_SHORT, LANG_TO_PARSER, LANG_TO_DISPLAY, register_datehandler) from . import _datestrings @@ -103,6 +103,6 @@ if __name__ == "__main__": continue m = max(m, len(d.formats)) print("{}: {} {} own dg: {}".format( - l, len(d.formats), d.formats, + l, len(d.formats), d.formats, d._display_gregorian != DateDisplay._display_gregorian)) print("MAX: ", m) diff --git a/gramps/gen/datehandler/_date_ar.py b/gramps/gen/datehandler/_date_ar.py index 5b1684632..dc9a4db36 100644 --- a/gramps/gen/datehandler/_date_ar.py +++ b/gramps/gen/datehandler/_date_ar.py @@ -57,13 +57,13 @@ class DateParserAR(DateParser): 'قبل' : Date.MOD_BEFORE, 'قبل.' : Date.MOD_BEFORE, 'بعد' : Date.MOD_AFTER, - 'بعد' : Date.MOD_AFTER, + 'بعد' : Date.MOD_AFTER, 'بعد.' : Date.MOD_AFTER, - 'حوالي' : Date.MOD_ABOUT, - 'حوالي.' : Date.MOD_ABOUT, - 'حوالي' : Date.MOD_ABOUT, 'حوالي' : Date.MOD_ABOUT, - 'حوالي.' : Date.MOD_ABOUT, + 'حوالي.' : Date.MOD_ABOUT, + 'حوالي' : Date.MOD_ABOUT, + 'حوالي' : Date.MOD_ABOUT, + 'حوالي.' : Date.MOD_ABOUT, 'حوالي' : Date.MOD_ABOUT, } @@ -100,11 +100,11 @@ class DateParserAR(DateParser): 'فرنسي جمهوري': Date.CAL_FRENCH, 'فرنسي' : Date.CAL_FRENCH, 'فارسي' : Date.CAL_PERSIAN, - 'فارسي' : Date.CAL_PERSIAN, + 'فارسي' : Date.CAL_PERSIAN, 'سويدي' : Date.CAL_SWEDISH, 'سويدي' : Date.CAL_SWEDISH, } - + quality_to_int = { 'متوقع' : Date.QUAL_ESTIMATED, 'متوقع.' : Date.QUAL_ESTIMATED, @@ -113,7 +113,7 @@ class DateParserAR(DateParser): 'محسوب' : Date.QUAL_CALCULATED, 'محسوب' : Date.QUAL_CALCULATED, } - + def init_strings(self): """ This method compiles regular expression strings for matching dates. @@ -137,40 +137,40 @@ class DateParserAR(DateParser): #------------------------------------------------------------------------- class DateDisplayAR(DateDisplay): """ - Arabic language date display class. + Arabic language date display class. """ # this is used to display the 12 gregorian months - long_months = ( "", "كانون الثاني", "شباط", "آذار", "نيسان", "أيار", - "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", + long_months = ( "", "كانون الثاني", "شباط", "آذار", "نيسان", "أيار", + "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول" ) - + short_months = ( "", "كانون2", "شباط", "آذار", "نيسان", "أيار", "حزيران", "تموز", "آب", "أيلول", "تشرين1", "تشرين2", "كانون1" ) islamic = ( - "", "محرّم", "صفر", "ربيع الأول", "ربيع الثاني", - "جمادى الأولى", "جمادى الثانية", "رجب", "شعبان", + "", "محرّم", "صفر", "ربيع الأول", "ربيع الثاني", + "جمادى الأولى", "جمادى الثانية", "رجب", "شعبان", "رمضان", "شوال", "ذو القعدة", "ذو الحجة" ) formats = ( - "YYYY-MM-DD (قياسي)", "عددي", "شهر يوم, سنة", + "YYYY-MM-DD (قياسي)", "عددي", "شهر يوم, سنة", "شهر يوم, سنة", "يوم شهر سنة", "يوم شهر سنة" ) # this must agree with DateDisplayEn's "formats" definition # (since no locale-specific _display_gregorian exists, here) - + calendar = ( - "", "يوليوسي", "عبري", "فرنسي", - "فارسي", "إسلامي", "سويدي" + "", "يوليوسي", "عبري", "فرنسي", + "فارسي", "إسلامي", "سويدي" ) - + _mod_str = ("", "قبل ", "بعد ", "حوالي ", "", "", "") _qual_str = ("", "متوقع ", "محسوب ") - + _bce_str = "%s قبل الميلاد." - + def display(self, date): """ Return a text string representing the date. @@ -182,7 +182,7 @@ class DateDisplayAR(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -207,5 +207,5 @@ class DateDisplayAR(DateDisplay): # Register classes # #------------------------------------------------------------------------- -register_datehandler(('ar_AR', 'ar', 'Arabic', 'arabic'), +register_datehandler(('ar_AR', 'ar', 'Arabic', 'arabic'), DateParserAR, DateDisplayAR) diff --git a/gramps/gen/datehandler/_date_bg.py b/gramps/gen/datehandler/_date_bg.py index 620699bf2..82e91d4fd 100644 --- a/gramps/gen/datehandler/_date_bg.py +++ b/gramps/gen/datehandler/_date_bg.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -48,7 +48,7 @@ from ._datehandler import register_datehandler class DateParserBG(DateParser): modifier_to_int = { - 'преди' : Date.MOD_BEFORE, + 'преди' : Date.MOD_BEFORE, 'пр.' : Date.MOD_BEFORE, 'пр' : Date.MOD_BEFORE, 'след' : Date.MOD_AFTER, @@ -68,22 +68,22 @@ class DateParserBG(DateParser): } calendar_to_int = { - 'григориански' : Date.CAL_GREGORIAN, - 'г' : Date.CAL_GREGORIAN, - 'юлиански' : Date.CAL_JULIAN, - 'ю' : Date.CAL_JULIAN, - 'еврейски' : Date.CAL_HEBREW, - 'е' : Date.CAL_HEBREW, - 'ислямски' : Date.CAL_ISLAMIC, - 'и' : Date.CAL_ISLAMIC, - 'френски републикански' : Date.CAL_FRENCH, + 'григориански' : Date.CAL_GREGORIAN, + 'г' : Date.CAL_GREGORIAN, + 'юлиански' : Date.CAL_JULIAN, + 'ю' : Date.CAL_JULIAN, + 'еврейски' : Date.CAL_HEBREW, + 'е' : Date.CAL_HEBREW, + 'ислямски' : Date.CAL_ISLAMIC, + 'и' : Date.CAL_ISLAMIC, + 'френски републикански' : Date.CAL_FRENCH, 'републикански' : Date.CAL_FRENCH, 'фр.реп.' : Date.CAL_FRENCH, 'р' : Date.CAL_FRENCH, 'френски' : Date.CAL_FRENCH, 'фр.' : Date.CAL_FRENCH, - 'персийски' : Date.CAL_PERSIAN, - 'п' : Date.CAL_PERSIAN, + 'персийски' : Date.CAL_PERSIAN, + 'п' : Date.CAL_PERSIAN, } quality_to_int = { @@ -95,65 +95,65 @@ class DateParserBG(DateParser): } hebrew_to_int = { - "тишрей":1, - "мархешван":2, - "кислев":3, - "тевет":4, - "шват":5, - "адар":6, - "адар бет":7, - "нисан":8, - "ияр":9, - "сиван":10, - "тамуз":11, - "ав":12, - "eлул":13, + "тишрей":1, + "мархешван":2, + "кислев":3, + "тевет":4, + "шват":5, + "адар":6, + "адар бет":7, + "нисан":8, + "ияр":9, + "сиван":10, + "тамуз":11, + "ав":12, + "eлул":13, } - islamic_to_int = { - "мухаррам":1, - "саффар":2, - "рабиу-л-ауал":3, - "рабиу-с-сани":4, - "джумадал-уля":5, - "джумада-с-сания":6, - "раджаб":7, - "шаабан":8, - "рамадан":9, - "шауал":10, - "зу-л-кида":11, - "зул-л-хиджа":12, + islamic_to_int = { + "мухаррам":1, + "саффар":2, + "рабиу-л-ауал":3, + "рабиу-с-сани":4, + "джумадал-уля":5, + "джумада-с-сания":6, + "раджаб":7, + "шаабан":8, + "рамадан":9, + "шауал":10, + "зу-л-кида":11, + "зул-л-хиджа":12, } persian_to_int = { - "фарвардин":1, - "урдбихищ":2, - "хурдад":3, - "тир":4, - "мурдад":5, - "шахривар":6, - "михр":7, - "абан":8, - "азар":9, - "дай":10, - "бахман":11, - "исфаидармуз":12, + "фарвардин":1, + "урдбихищ":2, + "хурдад":3, + "тир":4, + "мурдад":5, + "шахривар":6, + "михр":7, + "абан":8, + "азар":9, + "дай":10, + "бахман":11, + "исфаидармуз":12, } french_to_int = { - "вандемер":1, - "брюмер":2, - "фример":3, - "нивоз":4, - "плювиоз":5, - "вантоз":6, - "жерминал":7, - "флореал":8, - "прериал":9, - "месидор":10, - "термидор":11, - "фрюктидор":12, - "допълнителен":13, + "вандемер":1, + "брюмер":2, + "фример":3, + "нивоз":4, + "плювиоз":5, + "вантоз":6, + "жерминал":7, + "флореал":8, + "прериал":9, + "месидор":10, + "термидор":11, + "фрюктидор":12, + "допълнителен":13, } bce = [ @@ -167,12 +167,12 @@ class DateParserBG(DateParser): _range_1 = ['между'] _range_2 = ['и'] self._span = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_span_1), '|'.join(_span_2)), + ('|'.join(_span_1), '|'.join(_span_2)), re.IGNORECASE) self._range = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_range_1), '|'.join(_range_2)), + ('|'.join(_range_1), '|'.join(_range_2)), re.IGNORECASE) - + #------------------------------------------------------------------------- # # Bulgarian displayer @@ -180,28 +180,28 @@ class DateParserBG(DateParser): #------------------------------------------------------------------------- class DateDisplayBG(DateDisplay): """ - Bulgarian language date display class. + Bulgarian language date display class. """ - long_months = ( "", "януари", "февруари", "март", "април", "май", - "юни", "юли", "август", "септември", "октомври", + long_months = ( "", "януари", "февруари", "март", "април", "май", + "юни", "юли", "август", "септември", "октомври", "ноември", "декември" ) - - short_months = ( "", "яну", "февр", "март", "апр", "май", "юни", + + short_months = ( "", "яну", "февр", "март", "апр", "май", "юни", "юли", "авг", "септ", "окт", "ное", "дек" ) - + calendar = ( - "", - "юлиански", - "еврейски", - "републикански", - "персийски", + "", + "юлиански", + "еврейски", + "републикански", + "персийски", "ислямски", "шведски" ) _mod_str = ("", "преди ", "след ", "около ", "", "", "") - + _qual_str = ("", "приблизително ", "изчислено ") _bce_str = "%s пр. Хр." @@ -212,65 +212,65 @@ class DateDisplayBG(DateDisplay): # this must agree with DateDisplayEn's "formats" definition # (since no locale-specific _display_gregorian exists, here) - hebrew = ( "", - "Тишрей", - "Мархешван", - "Кислев", - "Тевет", - "Шват", - "Адар", - "Адар бет", - "Нисан", - "Ияр", - "Сиван", - "Тамуз", - "Ав", - "Елул", + hebrew = ( "", + "Тишрей", + "Мархешван", + "Кислев", + "Тевет", + "Шват", + "Адар", + "Адар бет", + "Нисан", + "Ияр", + "Сиван", + "Тамуз", + "Ав", + "Елул", ) - islamic = ( "", - "Мухаррам", - "Саффар", - "Рабиу-л-ауал", - "Рабиу-с-сани", - "Джумадал-уля", - "Джумада-с-сания", - "Раджаб", - "Шаабан", - "Рамадан", - "Шауал", - "Зу-л-кида", - "Зул-л-хиджа", + islamic = ( "", + "Мухаррам", + "Саффар", + "Рабиу-л-ауал", + "Рабиу-с-сани", + "Джумадал-уля", + "Джумада-с-сания", + "Раджаб", + "Шаабан", + "Рамадан", + "Шауал", + "Зу-л-кида", + "Зул-л-хиджа", ) - persian = ( "", - "Фарвардин", - "Урдбихищ", - "Хурдад", - "Тир", - "Мурдад", - "Шахривар", - "Михр", - "Абан", - "Азар", - "Дай", - "Бахман", - "Исфаидармуз", + persian = ( "", + "Фарвардин", + "Урдбихищ", + "Хурдад", + "Тир", + "Мурдад", + "Шахривар", + "Михр", + "Абан", + "Азар", + "Дай", + "Бахман", + "Исфаидармуз", ) - french = ( "", - "Вандемер", - "Брюмер", - "Фример", - "Нивоз", - "Плювиоз", - "Вантоз", - "Жерминал", - "Флореал", - "Прериал", - "Мессидор", - "Термидор", - "Фрюктидор", + french = ( "", + "Вандемер", + "Брюмер", + "Фример", + "Нивоз", + "Плювиоз", + "Вантоз", + "Жерминал", + "Флореал", + "Прериал", + "Мессидор", + "Термидор", + "Фрюктидор", "Допълнителен" ) @@ -285,7 +285,7 @@ class DateDisplayBG(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -310,5 +310,5 @@ class DateDisplayBG(DateDisplay): # Register classes # #------------------------------------------------------------------------- -register_datehandler(('bg_BG', 'bg', 'bulgarian', 'Bulgarian'), +register_datehandler(('bg_BG', 'bg', 'bulgarian', 'Bulgarian'), DateParserBG, DateDisplayBG) diff --git a/gramps/gen/datehandler/_date_ca.py b/gramps/gen/datehandler/_date_ca.py index 207faf498..f712547d7 100644 --- a/gramps/gen/datehandler/_date_ca.py +++ b/gramps/gen/datehandler/_date_ca.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -# Catalan Version, 2008 +# Catalan Version, 2008 """ Catalan-specific classes for parsing and displaying dates. @@ -50,48 +50,48 @@ from ._datehandler import register_datehandler class DateParserCA(DateParser): modifier_to_int = { - 'abans de' : Date.MOD_BEFORE, - 'abans' : Date.MOD_BEFORE, - 'ab.' : Date.MOD_BEFORE, - 'després de' : Date.MOD_AFTER, - 'després' : Date.MOD_AFTER, - 'desp.' : Date.MOD_AFTER, - 'desp' : Date.MOD_AFTER, - 'aprox.' : Date.MOD_ABOUT, - 'aprox' : Date.MOD_ABOUT, - 'circa' : Date.MOD_ABOUT, - 'ca.' : Date.MOD_ABOUT, - 'ca' : Date.MOD_ABOUT, - 'c.' : Date.MOD_ABOUT, - 'cap a' : Date.MOD_ABOUT, - 'al voltant' : Date.MOD_ABOUT, - 'al voltant de': Date.MOD_ABOUT, + 'abans de' : Date.MOD_BEFORE, + 'abans' : Date.MOD_BEFORE, + 'ab.' : Date.MOD_BEFORE, + 'després de' : Date.MOD_AFTER, + 'després' : Date.MOD_AFTER, + 'desp.' : Date.MOD_AFTER, + 'desp' : Date.MOD_AFTER, + 'aprox.' : Date.MOD_ABOUT, + 'aprox' : Date.MOD_ABOUT, + 'circa' : Date.MOD_ABOUT, + 'ca.' : Date.MOD_ABOUT, + 'ca' : Date.MOD_ABOUT, + 'c.' : Date.MOD_ABOUT, + 'cap a' : Date.MOD_ABOUT, + 'al voltant' : Date.MOD_ABOUT, + 'al voltant de': Date.MOD_ABOUT, } calendar_to_int = { - 'gregorià' : Date.CAL_GREGORIAN, - 'g' : Date.CAL_GREGORIAN, - 'julià' : Date.CAL_JULIAN, - 'j' : Date.CAL_JULIAN, - 'hebreu' : Date.CAL_HEBREW, - 'h' : Date.CAL_HEBREW, - 'islàmic' : Date.CAL_ISLAMIC, - 'i' : Date.CAL_ISLAMIC, - 'revolucionari': Date.CAL_FRENCH, - 'r' : Date.CAL_FRENCH, - 'persa' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, - 'swedish' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'gregorià' : Date.CAL_GREGORIAN, + 'g' : Date.CAL_GREGORIAN, + 'julià' : Date.CAL_JULIAN, + 'j' : Date.CAL_JULIAN, + 'hebreu' : Date.CAL_HEBREW, + 'h' : Date.CAL_HEBREW, + 'islàmic' : Date.CAL_ISLAMIC, + 'i' : Date.CAL_ISLAMIC, + 'revolucionari': Date.CAL_FRENCH, + 'r' : Date.CAL_FRENCH, + 'persa' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, + 'swedish' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } quality_to_int = { - 'estimat' : Date.QUAL_ESTIMATED, - 'est.' : Date.QUAL_ESTIMATED, - 'est' : Date.QUAL_ESTIMATED, - 'calc.' : Date.QUAL_CALCULATED, - 'calc' : Date.QUAL_CALCULATED, - 'calculat' : Date.QUAL_CALCULATED, + 'estimat' : Date.QUAL_ESTIMATED, + 'est.' : Date.QUAL_ESTIMATED, + 'est' : Date.QUAL_ESTIMATED, + 'calc.' : Date.QUAL_CALCULATED, + 'calc' : Date.QUAL_CALCULATED, + 'calculat' : Date.QUAL_CALCULATED, } def init_strings(self): @@ -101,10 +101,10 @@ class DateParserCA(DateParser): _range_1 = ['entre', 'ent\.', 'ent'] _range_2 = ['i'] self._span = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_span_1), '|'.join(_span_2)), + ('|'.join(_span_1), '|'.join(_span_2)), re.IGNORECASE) self._range = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_range_1), '|'.join(_range_2)), + ('|'.join(_range_1), '|'.join(_range_2)), re.IGNORECASE) #------------------------------------------------------------------------- @@ -114,19 +114,19 @@ class DateParserCA(DateParser): #------------------------------------------------------------------------- class DateDisplayCA(DateDisplay): """ - Catalan language date display class. + Catalan language date display class. """ - long_months = ( "", "Gener", "Febrer", "Març", "Abril", "Maig", - "Juny", "Juliol", "Agost", "Setembre", "Octubre", + long_months = ( "", "Gener", "Febrer", "Març", "Abril", "Maig", + "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre" ) - - short_months = ( "", "Gen", "Feb", "Mar", "Abr", "Mai", "Jun", + + short_months = ( "", "Gen", "Feb", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Oct", "Nov", "Des" ) calendar = ( - "", "Julià", "Hebreu", - "Revolucionari", "Persa", "Islàmic", - "Suec" + "", "Julià", "Hebreu", + "Revolucionari", "Persa", "Islàmic", + "Suec" ) _mod_str = ("", "abans de ", "després de ", "cap a ", "", "", "") @@ -134,29 +134,29 @@ class DateDisplayCA(DateDisplay): _qual_str = ("", "estimat ", "calculat ") french = ( - '', - "Vendemiari", - 'Brumari', - 'Frimari', - "Nivós", - "Pluviós", - "Ventós", - 'Germinal', - "Floreal", - 'Pradial', - 'Messidor', - 'Termidor', - 'Fructidor', - 'Extra', + '', + "Vendemiari", + 'Brumari', + 'Frimari', + "Nivós", + "Pluviós", + "Ventós", + 'Germinal', + "Floreal", + 'Pradial', + 'Messidor', + 'Termidor', + 'Fructidor', + 'Extra', ) - + formats = ( - "AAAA-MM-DD (ISO)", "Numèrica", "Mes Dia, Any", + "AAAA-MM-DD (ISO)", "Numèrica", "Mes Dia, Any", "MES Dia, Any", "Dia Mes, Any", "Dia MES, Any" ) # this must agree with DateDisplayEn's "formats" definition # (since no locale-specific _display_gregorian exists, here) - + def display(self, date): """ Return a text string representing the date. @@ -168,7 +168,7 @@ class DateDisplayCA(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: diff --git a/gramps/gen/datehandler/_date_cs.py b/gramps/gen/datehandler/_date_cs.py index 3b303aa88..76493ea62 100644 --- a/gramps/gen/datehandler/_date_cs.py +++ b/gramps/gen/datehandler/_date_cs.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -48,30 +48,30 @@ from ._datehandler import register_datehandler class DateParserCZ(DateParser): """ Converts a text string into a Date object - """ + """ month_to_int = DateParser.month_to_int - + month_to_int["leden"] = 1 month_to_int["ledna"] = 1 month_to_int["lednu"] = 1 month_to_int["led"] = 1 month_to_int["I"] = 1 month_to_int["i"] = 1 - + month_to_int["únor"] = 2 month_to_int["února"] = 2 month_to_int["únoru"] = 2 month_to_int["ún"] = 2 month_to_int["II"] = 2 month_to_int["ii"] = 2 - + month_to_int["březen"] = 3 month_to_int["března"] = 3 month_to_int["březnu"] = 3 month_to_int["bře"] = 3 month_to_int["III"] = 3 month_to_int["iii"] = 3 - + month_to_int["duben"] = 4 month_to_int["dubna"] = 4 month_to_int["dubnu"] = 4 @@ -84,7 +84,7 @@ class DateParserCZ(DateParser): month_to_int["květnu"] = 5 month_to_int["V"] = 5 month_to_int["v"] = 5 - + month_to_int["červen"] = 6 month_to_int["června"] = 6 month_to_int["červnu"] = 6 @@ -97,80 +97,80 @@ class DateParserCZ(DateParser): month_to_int["čvc"] = 7 month_to_int["VII"] = 7 month_to_int["vii"] = 7 - + month_to_int["srpen"] = 8 month_to_int["srpna"] = 8 month_to_int["srpnu"] = 8 month_to_int["srp"] = 8 month_to_int["VIII"] = 8 month_to_int["viii"] = 8 - + month_to_int["září"] = 9 month_to_int["zář"] = 9 month_to_int["IX"] = 9 month_to_int["ix"] = 9 - + month_to_int["říjen"] = 10 month_to_int["října"] = 10 month_to_int["říjnu"] = 10 month_to_int["říj"] = 10 month_to_int["X"] = 10 month_to_int["x"] = 10 - + month_to_int["listopad"] = 11 month_to_int["listopadu"] = 11 month_to_int["lis"] = 11 month_to_int["XI"] = 11 month_to_int["xi"] = 11 - + month_to_int["prosinec"] = 12 month_to_int["prosince"] = 12 month_to_int["prosinci"] = 12 month_to_int["pro"] = 12 month_to_int["XII"] = 12 month_to_int["xii"] = 12 - + modifier_to_int = { - 'před' : Date.MOD_BEFORE, - 'do' : Date.MOD_BEFORE, - 'po' : Date.MOD_AFTER, - 'asi' : Date.MOD_ABOUT, - 'kolem' : Date.MOD_ABOUT, - 'přibl.' : Date.MOD_ABOUT, + 'před' : Date.MOD_BEFORE, + 'do' : Date.MOD_BEFORE, + 'po' : Date.MOD_AFTER, + 'asi' : Date.MOD_ABOUT, + 'kolem' : Date.MOD_ABOUT, + 'přibl.' : Date.MOD_ABOUT, } calendar_to_int = { 'gregoriánský' : Date.CAL_GREGORIAN, 'greg.' : Date.CAL_GREGORIAN, - 'g' : Date.CAL_GREGORIAN, - 'juliánský' : Date.CAL_JULIAN, - 'jul.' : Date.CAL_JULIAN, - 'j' : Date.CAL_JULIAN, - 'hebrejský' : Date.CAL_HEBREW, - 'hebr.' : Date.CAL_HEBREW, - 'h' : Date.CAL_HEBREW, - 'islámský' : Date.CAL_ISLAMIC, - 'isl.' : Date.CAL_ISLAMIC, - 'i' : Date.CAL_ISLAMIC, - 'francouzský republikánský' : Date.CAL_FRENCH, - 'fr.' : Date.CAL_FRENCH, - 'perský' : Date.CAL_PERSIAN, - 'per.' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, - 'švédský' : Date.CAL_SWEDISH, - 'sve.' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'g' : Date.CAL_GREGORIAN, + 'juliánský' : Date.CAL_JULIAN, + 'jul.' : Date.CAL_JULIAN, + 'j' : Date.CAL_JULIAN, + 'hebrejský' : Date.CAL_HEBREW, + 'hebr.' : Date.CAL_HEBREW, + 'h' : Date.CAL_HEBREW, + 'islámský' : Date.CAL_ISLAMIC, + 'isl.' : Date.CAL_ISLAMIC, + 'i' : Date.CAL_ISLAMIC, + 'francouzský republikánský' : Date.CAL_FRENCH, + 'fr.' : Date.CAL_FRENCH, + 'perský' : Date.CAL_PERSIAN, + 'per.' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, + 'švédský' : Date.CAL_SWEDISH, + 'sve.' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } quality_to_int = { 'přibližně' : Date.QUAL_ESTIMATED, - 'odhadem' : Date.QUAL_ESTIMATED, - 'odh.' : Date.QUAL_ESTIMATED, + 'odhadem' : Date.QUAL_ESTIMATED, + 'odh.' : Date.QUAL_ESTIMATED, 'vypočteno' : Date.QUAL_CALCULATED, - 'vypočtené' : Date.QUAL_CALCULATED, - 'vyp.' : Date.QUAL_CALCULATED, + 'vypočtené' : Date.QUAL_CALCULATED, + 'vyp.' : Date.QUAL_CALCULATED, } - + def init_strings(self): DateParser.init_strings(self) self._text2 = re.compile('(\d+)?\.?\s+?%s\.?\s*((\d+)(/\d+)?)?\s*$' @@ -179,7 +179,7 @@ class DateParserCZ(DateParser): "(od)\s+(?P.+)\s+(do)\s+(?P.+)", re.IGNORECASE) self._range = re.compile( - "(mezi)\s+(?P.+)\s+(a)\s+(?P.+)", + "(mezi)\s+(?P.+)\s+(a)\s+(?P.+)", re.IGNORECASE) @@ -190,30 +190,30 @@ class DateParserCZ(DateParser): #------------------------------------------------------------------------- class DateDisplayCZ(DateDisplay): """ - Czech language date display class. + Czech language date display class. """ - long_months = ( "", "leden", "únor", "březen", "duben", "květen", - "červen", "červenec", "srpen", "září", "říjen", + long_months = ( "", "leden", "únor", "březen", "duben", "květen", + "červen", "červenec", "srpen", "září", "říjen", "listopad", "prosinec" ) - - short_months = ( "", "led", "úno", "bře", "dub", "kvě", "čer", + + short_months = ( "", "led", "úno", "bře", "dub", "kvě", "čer", "čvc", "srp", "zář", "říj", "lis", "pro" ) calendar = ( - "", "juliánský", "hebrejský", - "francouzský republikánský", "perský", "islámský", - "švédský" + "", "juliánský", "hebrejský", + "francouzský republikánský", "perský", "islámský", + "švédský" ) _mod_str = ("", "před ", "po ", "kolem ", "", "", "") - + _qual_str = ("", "přibližně ", "vypočteno ") bce = ["před naším letopočtem", "před Kristem", "př. n. l.", "př. Kr."] + DateParser.bce formats = ( - "ISO (rrrr-mm-dd)", + "ISO (rrrr-mm-dd)", "numerický", "měsíc den, Rok", "měs den, Rok", @@ -236,7 +236,7 @@ class DateDisplayCZ(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -253,13 +253,13 @@ class DateDisplayCZ(DateDisplay): dat1 = self.display_cal[cal](start) dat2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%s%s %s %s %s%s" % (qual_str, 'od', dat1, + return "%s%s %s %s %s%s" % (qual_str, 'od', dat1, 'do', dat2, scal) elif mod == Date.MOD_RANGE: dat1 = self.display_cal[cal](start) dat2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%s%s %s %s %s%s" % (qual_str, 'mezi', + return "%s%s %s %s %s%s" % (qual_str, 'mezi', dat1, 'a', dat2, scal) else: text = self.display_cal[date.get_calendar()](start) diff --git a/gramps/gen/datehandler/_date_da.py b/gramps/gen/datehandler/_date_da.py index 3d3d0ed55..2ea663190 100644 --- a/gramps/gen/datehandler/_date_da.py +++ b/gramps/gen/datehandler/_date_da.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -48,50 +48,50 @@ from ._datehandler import register_datehandler class DateParserDa(DateParser): """ Convert a text string into a Date object, expecting a date - notation in the Danish language. If the date cannot be converted, + notation in the Danish language. If the date cannot be converted, the text string is assigned. """ # modifiers before the date modifier_to_int = { - 'før' : Date.MOD_BEFORE, - 'inden' : Date.MOD_BEFORE, - 'efter' : Date.MOD_AFTER, - 'omkring' : Date.MOD_ABOUT, + 'før' : Date.MOD_BEFORE, + 'inden' : Date.MOD_BEFORE, + 'efter' : Date.MOD_AFTER, + 'omkring' : Date.MOD_ABOUT, 'ca.' : Date.MOD_ABOUT } bce = ["f Kr"] calendar_to_int = { - 'gregoriansk ' : Date.CAL_GREGORIAN, - 'g' : Date.CAL_GREGORIAN, - 'juliansk' : Date.CAL_JULIAN, - 'j' : Date.CAL_JULIAN, - 'hebraisk' : Date.CAL_HEBREW, - 'h' : Date.CAL_HEBREW, - 'islamisk' : Date.CAL_ISLAMIC, - 'muslimsk' : Date.CAL_ISLAMIC, - 'i' : Date.CAL_ISLAMIC, - 'fransk' : Date.CAL_FRENCH, - 'fransk republikansk' : Date.CAL_FRENCH, - 'f' : Date.CAL_FRENCH, - 'persisk' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, - 'svensk' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'gregoriansk ' : Date.CAL_GREGORIAN, + 'g' : Date.CAL_GREGORIAN, + 'juliansk' : Date.CAL_JULIAN, + 'j' : Date.CAL_JULIAN, + 'hebraisk' : Date.CAL_HEBREW, + 'h' : Date.CAL_HEBREW, + 'islamisk' : Date.CAL_ISLAMIC, + 'muslimsk' : Date.CAL_ISLAMIC, + 'i' : Date.CAL_ISLAMIC, + 'fransk' : Date.CAL_FRENCH, + 'fransk republikansk' : Date.CAL_FRENCH, + 'f' : Date.CAL_FRENCH, + 'persisk' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, + 'svensk' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } - + quality_to_int = { - 'estimeret' : Date.QUAL_ESTIMATED, - 'beregnet' : Date.QUAL_CALCULATED, + 'estimeret' : Date.QUAL_ESTIMATED, + 'beregnet' : Date.QUAL_CALCULATED, } - + def init_strings(self): DateParser.init_strings(self) - self._span = re.compile("(fra)?\s*(?P.+)\s*(til|--|–)\s*(?P.+)", + self._span = re.compile("(fra)?\s*(?P.+)\s*(til|--|–)\s*(?P.+)", re.IGNORECASE) - self._range = re.compile("(mellem)\s+(?P.+)\s+og\s+(?P.+)", + self._range = re.compile("(mellem)\s+(?P.+)\s+og\s+(?P.+)", re.IGNORECASE) #------------------------------------------------------------------------- @@ -101,41 +101,41 @@ class DateParserDa(DateParser): #------------------------------------------------------------------------- class DateDisplayDa(DateDisplay): """ - Danish language date display class. + Danish language date display class. """ - long_months = ( "", "januar", "februar", "marts", "april", "maj", - "juni", "juli", "august", "september", "oktober", + long_months = ( "", "januar", "februar", "marts", "april", "maj", + "juni", "juli", "august", "september", "oktober", "november", "december" ) - - short_months = ( "", "jan", "feb", "mar", "apr", "maj", "jun", + + short_months = ( "", "jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ) formats = ( - "ÅÅÅÅ-MM-DD (ISO)", - "Numerisk", - "Måned dag, år", - "Md Dag År", - "Dag måned år", - "Dag md År", + "ÅÅÅÅ-MM-DD (ISO)", + "Numerisk", + "Måned dag, år", + "Md Dag År", + "Dag måned år", + "Dag md År", ) # this must agree with DateDisplayEn's "formats" definition # (since no locale-specific _display_gregorian exists, here) calendar = ( - "", - "juliansk", - "hebraisk", - "fransk republikansk", - "persisk", - "islamisk", - "svensk" + "", + "juliansk", + "hebraisk", + "fransk republikansk", + "persisk", + "islamisk", + "svensk" ) - + _mod_str = ("", "før ", "efter ", "ca. ", "", "", "") _qual_str = ("", "beregnet ", "beregnet ") - + _bce_str = "%s f. Kr." def display(self, date): @@ -163,12 +163,12 @@ class DateDisplayDa(DateDisplay): d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%smellem %s og %s%s" % (qual_str, d1, d2, + return "%smellem %s og %s%s" % (qual_str, d1, d2, scal) else: text = self.display_cal[date.get_calendar()](start) scal = self.format_extras(cal, newyear) - return "%s%s%s%s" % (qual_str, self._mod_str[mod], + return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, scal) #------------------------------------------------------------------------- diff --git a/gramps/gen/datehandler/_date_de.py b/gramps/gen/datehandler/_date_de.py index 1985fee3a..e5616966c 100644 --- a/gramps/gen/datehandler/_date_de.py +++ b/gramps/gen/datehandler/_date_de.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -48,14 +48,14 @@ from ._datehandler import register_datehandler class DateParserDE(DateParser): month_to_int = DateParser.month_to_int - # Always add german and austrian name variants no matter what the current + # Always add german and austrian name variants no matter what the current # locale is month_to_int["januar"] = 1 month_to_int["jan"] = 1 month_to_int["jänner"] = 1 month_to_int["jän"] = 1 - # Add other common latin, + # Add other common latin, month_to_int["januaris"] = 1 month_to_int["januarii"] = 1 @@ -88,7 +88,7 @@ class DateParserDE(DateParser): month_to_int["xbris"] = 12 month_to_int["december"] = 12 - # local and historical variants + # local and historical variants month_to_int["jenner"] = 1 month_to_int["feber"] = 2 @@ -135,55 +135,55 @@ class DateParserDE(DateParser): month_to_int["heilmond"] = 12 month_to_int["christmond"] = 12 month_to_int["dustermond"] = 12 - + modifier_to_int = { - 'vor' : Date.MOD_BEFORE, - 'nach' : Date.MOD_AFTER, - 'gegen' : Date.MOD_ABOUT, - 'um' : Date.MOD_ABOUT, - 'etwa' : Date.MOD_ABOUT, - 'circa' : Date.MOD_ABOUT, - 'ca.' : Date.MOD_ABOUT, + 'vor' : Date.MOD_BEFORE, + 'nach' : Date.MOD_AFTER, + 'gegen' : Date.MOD_ABOUT, + 'um' : Date.MOD_ABOUT, + 'etwa' : Date.MOD_ABOUT, + 'circa' : Date.MOD_ABOUT, + 'ca.' : Date.MOD_ABOUT, } calendar_to_int = { - 'gregorianisch' : Date.CAL_GREGORIAN, - 'greg.' : Date.CAL_GREGORIAN, - 'julianisch' : Date.CAL_JULIAN, - 'jul.' : Date.CAL_JULIAN, - 'hebräisch' : Date.CAL_HEBREW, - 'hebr.' : Date.CAL_HEBREW, - 'islamisch' : Date.CAL_ISLAMIC, - 'isl.' : Date.CAL_ISLAMIC, - 'französisch republikanisch': Date.CAL_FRENCH, - 'franz.' : Date.CAL_FRENCH, - 'persisch' : Date.CAL_PERSIAN, - 'schwedisch' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'gregorianisch' : Date.CAL_GREGORIAN, + 'greg.' : Date.CAL_GREGORIAN, + 'julianisch' : Date.CAL_JULIAN, + 'jul.' : Date.CAL_JULIAN, + 'hebräisch' : Date.CAL_HEBREW, + 'hebr.' : Date.CAL_HEBREW, + 'islamisch' : Date.CAL_ISLAMIC, + 'isl.' : Date.CAL_ISLAMIC, + 'französisch republikanisch': Date.CAL_FRENCH, + 'franz.' : Date.CAL_FRENCH, + 'persisch' : Date.CAL_PERSIAN, + 'schwedisch' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } quality_to_int = { - 'geschätzt' : Date.QUAL_ESTIMATED, - 'gesch.' : Date.QUAL_ESTIMATED, - 'errechnet' : Date.QUAL_CALCULATED, - 'berechnet' : Date.QUAL_CALCULATED, - 'ber.' : Date.QUAL_CALCULATED, + 'geschätzt' : Date.QUAL_ESTIMATED, + 'gesch.' : Date.QUAL_ESTIMATED, + 'errechnet' : Date.QUAL_CALCULATED, + 'berechnet' : Date.QUAL_CALCULATED, + 'ber.' : Date.QUAL_CALCULATED, } - bce = ["vor unserer Zeitrechnung", "vor unserer Zeit", - "vor der Zeitrechnung", "vor der Zeit", - "v. u. Z.", "v. d. Z.", "v.u.Z.", "v.d.Z.", + bce = ["vor unserer Zeitrechnung", "vor unserer Zeit", + "vor der Zeitrechnung", "vor der Zeit", + "v. u. Z.", "v. d. Z.", "v.u.Z.", "v.d.Z.", "vor Christi Geburt", "vor Christus", "v. Chr."] + DateParser.bce - + def init_strings(self): DateParser.init_strings(self) self._span = re.compile("(von|vom)\s+(?P.+)\s+(bis)\s+(?P.+)", re.IGNORECASE) self._range = re.compile("zwischen\s+(?P.+)\s+und\s+(?P.+)", re.IGNORECASE) - self._text2 = re.compile('(\d+)?.?\s+?%s\s*((\d+)(/\d+)?)?' % self._mon_str, + self._text2 = re.compile('(\d+)?.?\s+?%s\s*((\d+)(/\d+)?)?' % self._mon_str, re.IGNORECASE) - self._jtext2 = re.compile('(\d+)?.?\s+?%s\s*((\d+)(/\d+)?)?' % self._jmon_str, + self._jtext2 = re.compile('(\d+)?.?\s+?%s\s*((\d+)(/\d+)?)?' % self._jmon_str, re.IGNORECASE) #------------------------------------------------------------------------- @@ -193,30 +193,30 @@ class DateParserDE(DateParser): #------------------------------------------------------------------------- class DateDisplayDE(DateDisplay): """ - German language date display class. + German language date display class. """ - - long_months = ( "", "Januar", "Februar", "März", "April", "Mai", - "Juni", "Juli", "August", "September", "Oktober", + + long_months = ( "", "Januar", "Februar", "März", "April", "Mai", + "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember" ) - - short_months = ( "", "Jan", "Feb", "Mär", "Apr", "Mai", "Jun", + + short_months = ( "", "Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez" ) calendar = ( - "", "julianisch", "hebräisch", - "französisch republikanisch", "persisch", "islamisch", - "schwedisch" + "", "julianisch", "hebräisch", + "französisch republikanisch", "persisch", "islamisch", + "schwedisch" ) _mod_str = ("", "vor ", "nach ", "etwa ", "", "", "") - + _qual_str = ("", "geschätzt ", "errechnet ") - + _bce_str = "%s v. u. Z." formats = ( - "JJJJ-MM-DD (ISO)", "Numerisch", "Monat Tag Jahr", + "JJJJ-MM-DD (ISO)", "Numerisch", "Monat Tag Jahr", "MONAT Tag Jahr", "Tag. Monat Jahr", "Tag. MONAT Jahr" ) # this definition must agree with its "_display_gregorian" method @@ -248,7 +248,7 @@ class DateDisplayDE(DateDisplay): else: value = "%s %s" % (self.long_months[date_val[1]], year) else: - value = "%s %d, %s" % (self.long_months[date_val[1]], + value = "%s %d, %s" % (self.long_months[date_val[1]], date_val[0], year) elif self.format == 3: # month_abbreviation day, year @@ -258,7 +258,7 @@ class DateDisplayDE(DateDisplay): else: value = "%s %s" % (self.short_months[date_val[1]], year) else: - value = "%s %d, %s" % (self.short_months[date_val[1]], + value = "%s %d, %s" % (self.short_months[date_val[1]], date_val[0], year) elif self.format == 4: # day. month_name year @@ -268,7 +268,7 @@ class DateDisplayDE(DateDisplay): else: value = "%s %s" % (self.long_months[date_val[1]], year) else: - value = "%d. %s %s" % (date_val[0], + value = "%d. %s %s" % (date_val[0], self.long_months[date_val[1]], year) else: # day. month_abbreviation year @@ -278,7 +278,7 @@ class DateDisplayDE(DateDisplay): else: value = "%s %s" % (self.short_months[date_val[1]], year) else: - value = "%d. %s %s" % (date_val[0], + value = "%d. %s %s" % (date_val[0], self.short_months[date_val[1]], year) if date_val[2] < 0: return self._bce_str % value @@ -296,7 +296,7 @@ class DateDisplayDE(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -321,6 +321,6 @@ class DateDisplayDE(DateDisplay): # Register classes # #------------------------------------------------------------------------- -register_datehandler(('de_DE', 'german', 'German', 'de_AT', 'de_CH', - 'de_LI', 'de_LU', 'de_BE', 'de'), +register_datehandler(('de_DE', 'german', 'German', 'de_AT', 'de_CH', + 'de_LI', 'de_LU', 'de_BE', 'de'), DateParserDE, DateDisplayDE) diff --git a/gramps/gen/datehandler/_date_el.py b/gramps/gen/datehandler/_date_el.py index 8a1828a39..0b46ab16f 100644 --- a/gramps/gen/datehandler/_date_el.py +++ b/gramps/gen/datehandler/_date_el.py @@ -67,11 +67,11 @@ class DateParserEL(DateParser): 'μετά από την' : Date.MOD_AFTER, 'μετά από το' : Date.MOD_AFTER, 'μετά από τον' : Date.MOD_AFTER, - 'μετά' : Date.MOD_AFTER, + 'μετά' : Date.MOD_AFTER, 'μετ.' : Date.MOD_AFTER, 'γύρω στο' : Date.MOD_ABOUT, 'γύρω στον' : Date.MOD_ABOUT, - 'γύρω στις' : Date.MOD_ABOUT, + 'γύρω στις' : Date.MOD_ABOUT, 'περίπου το' : Date.MOD_ABOUT, 'περ.' : Date.MOD_ABOUT, 'γυρ.' : Date.MOD_ABOUT, @@ -93,11 +93,11 @@ class DateParserEL(DateParser): 'γαλλικής δημοκρατίας': Date.CAL_FRENCH, 'γ' : Date.CAL_FRENCH, 'περσικό' : Date.CAL_PERSIAN, - 'π' : Date.CAL_PERSIAN, + 'π' : Date.CAL_PERSIAN, 'σουηδικό' : Date.CAL_SWEDISH, 'σ' : Date.CAL_SWEDISH, } - + quality_to_int = { 'κατʼ εκτίμηση' : Date.QUAL_ESTIMATED, 'εκτιμώμενη' : Date.QUAL_ESTIMATED, @@ -108,7 +108,7 @@ class DateParserEL(DateParser): 'υπολογισμένη' : Date.QUAL_CALCULATED, 'με υπολογισμό' : Date.QUAL_CALCULATED, } - + def init_strings(self): """ This method compiles regular expression strings for matching dates. @@ -122,7 +122,7 @@ class DateParserEL(DateParser): ('|'.join(_span_1), '|'.join(_span_2)), re.IGNORECASE) self._range = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_range_1), '|'.join(_range_2)), + ('|'.join(_range_1), '|'.join(_range_2)), re.IGNORECASE) #------------------------------------------------------------------------- @@ -132,14 +132,14 @@ class DateParserEL(DateParser): #------------------------------------------------------------------------- class DateDisplayEL(DateDisplay): """ - Greek language date display class. + Greek language date display class. """ # this is used to display the 12 gregorian months long_months = ( "", "Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος" ) - + short_months = ( "", "Ιαν", "Φεβ", "Μαρ", "Απρ", "Μάι", "Ιουν", "Ιουλ", "Αύγ", "Σεπ", "Οκτ", "Νοε", "Δεκ" ) @@ -189,7 +189,7 @@ class DateDisplayEL(DateDisplay): else: value = "%s %s" % (self.long_months[date_val[1]], year) else: - value = "%d %s %s" % (date_val[0], + value = "%d %s %s" % (date_val[0], self.long_months[date_val[1]], year) else: # day month_abbreviation year @@ -199,13 +199,13 @@ class DateDisplayEL(DateDisplay): else: value = "%s %s" % (self.short_months[date_val[1]], year) else: - value = "%d %s %s" % (date_val[0], + value = "%d %s %s" % (date_val[0], self.short_months[date_val[1]], year) if date_val[2] < 0: return self._bce_str % value else: return value - + def display(self, date): """ Return a text string representing the date. @@ -217,7 +217,7 @@ class DateDisplayEL(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -242,5 +242,5 @@ class DateDisplayEL(DateDisplay): # Register classes # #------------------------------------------------------------------------- -register_datehandler(('el_GR', 'el_CY', 'el', 'Greek', 'greek'), +register_datehandler(('el_GR', 'el_CY', 'el', 'Greek', 'greek'), DateParserEL, DateDisplayEL) diff --git a/gramps/gen/datehandler/_date_es.py b/gramps/gen/datehandler/_date_es.py index 890f1cb6d..1c7c65827 100644 --- a/gramps/gen/datehandler/_date_es.py +++ b/gramps/gen/datehandler/_date_es.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -48,49 +48,49 @@ from ._datehandler import register_datehandler class DateParserES(DateParser): modifier_to_int = { - 'antes de' : Date.MOD_BEFORE, - 'antes' : Date.MOD_BEFORE, - 'ant.' : Date.MOD_BEFORE, - 'ant' : Date.MOD_BEFORE, - 'después de' : Date.MOD_AFTER, - 'después' : Date.MOD_AFTER, - 'desp.' : Date.MOD_AFTER, - 'desp' : Date.MOD_AFTER, - 'aprox.' : Date.MOD_ABOUT, - 'aprox' : Date.MOD_ABOUT, - 'apr.' : Date.MOD_ABOUT, - 'apr' : Date.MOD_ABOUT, - 'circa' : Date.MOD_ABOUT, - 'ca.' : Date.MOD_ABOUT, - 'ca' : Date.MOD_ABOUT, - 'c.' : Date.MOD_ABOUT, - 'hacia' : Date.MOD_ABOUT, + 'antes de' : Date.MOD_BEFORE, + 'antes' : Date.MOD_BEFORE, + 'ant.' : Date.MOD_BEFORE, + 'ant' : Date.MOD_BEFORE, + 'después de' : Date.MOD_AFTER, + 'después' : Date.MOD_AFTER, + 'desp.' : Date.MOD_AFTER, + 'desp' : Date.MOD_AFTER, + 'aprox.' : Date.MOD_ABOUT, + 'aprox' : Date.MOD_ABOUT, + 'apr.' : Date.MOD_ABOUT, + 'apr' : Date.MOD_ABOUT, + 'circa' : Date.MOD_ABOUT, + 'ca.' : Date.MOD_ABOUT, + 'ca' : Date.MOD_ABOUT, + 'c.' : Date.MOD_ABOUT, + 'hacia' : Date.MOD_ABOUT, } calendar_to_int = { - 'gregoriano' : Date.CAL_GREGORIAN, - 'g' : Date.CAL_GREGORIAN, - 'juliano' : Date.CAL_JULIAN, - 'j' : Date.CAL_JULIAN, - 'hebreo' : Date.CAL_HEBREW, - 'h' : Date.CAL_HEBREW, - 'islámico' : Date.CAL_ISLAMIC, - 'i' : Date.CAL_ISLAMIC, - 'revolucionario' : Date.CAL_FRENCH, - 'r' : Date.CAL_FRENCH, - 'persa' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, - 'swedish' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'gregoriano' : Date.CAL_GREGORIAN, + 'g' : Date.CAL_GREGORIAN, + 'juliano' : Date.CAL_JULIAN, + 'j' : Date.CAL_JULIAN, + 'hebreo' : Date.CAL_HEBREW, + 'h' : Date.CAL_HEBREW, + 'islámico' : Date.CAL_ISLAMIC, + 'i' : Date.CAL_ISLAMIC, + 'revolucionario' : Date.CAL_FRENCH, + 'r' : Date.CAL_FRENCH, + 'persa' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, + 'swedish' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } quality_to_int = { - 'estimado' : Date.QUAL_ESTIMATED, - 'est.' : Date.QUAL_ESTIMATED, - 'est' : Date.QUAL_ESTIMATED, - 'calc.' : Date.QUAL_CALCULATED, - 'calc' : Date.QUAL_CALCULATED, - 'calculado' : Date.QUAL_CALCULATED, + 'estimado' : Date.QUAL_ESTIMATED, + 'est.' : Date.QUAL_ESTIMATED, + 'est' : Date.QUAL_ESTIMATED, + 'calc.' : Date.QUAL_CALCULATED, + 'calc' : Date.QUAL_CALCULATED, + 'calculado' : Date.QUAL_CALCULATED, } def init_strings(self): @@ -100,10 +100,10 @@ class DateParserES(DateParser): _range_1 = ['entre', 'ent\.', 'ent'] _range_2 = ['y'] self._span = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_span_1), '|'.join(_span_2)), + ('|'.join(_span_1), '|'.join(_span_2)), re.IGNORECASE) self._range = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_range_1), '|'.join(_range_2)), + ('|'.join(_range_1), '|'.join(_range_2)), re.IGNORECASE) #------------------------------------------------------------------------- @@ -113,21 +113,21 @@ class DateParserES(DateParser): #------------------------------------------------------------------------- class DateDisplayES(DateDisplay): """ - Spanish language date display class. + Spanish language date display class. """ # TODO: Translate these month strings: - long_months = ( "", "enero", "febrero", "marzo", "abril", "mayo", - "junio", "julio", "agosto", "septiembre", "octubre", + long_months = ( "", "enero", "febrero", "marzo", "abril", "mayo", + "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre" ) - - short_months = ( "", "enero", "feb.", "marzo", "abr.", "mayo", - "jun.", "jul.", "agosto", "set.", "oct.", "nov.", + + short_months = ( "", "enero", "feb.", "marzo", "abr.", "mayo", + "jun.", "jul.", "agosto", "set.", "oct.", "nov.", "dic" ) calendar = ( - "", "Juliano", "Hebreo", - "Revolucionario", "Persa", "Islámico", - "Swedish" + "", "Juliano", "Hebreo", + "Revolucionario", "Persa", "Islámico", + "Swedish" ) _mod_str = ("", "antes de ", "después de ", "hacia ", "", "", "") @@ -135,12 +135,12 @@ class DateDisplayES(DateDisplay): _qual_str = ("", "estimado ", "calculado ") formats = ( - "AAAA-MM-DD (ISO)", "Numérica", "Mes Día, Año", + "AAAA-MM-DD (ISO)", "Numérica", "Mes Día, Año", "MES Día, Año", "Día Mes, Año", "Día MES, Año" ) # this must agree with DateDisplayEn's "formats" definition # (since no locale-specific _display_gregorian exists, here) - + def display(self, date): """ Return a text string representing the date. @@ -152,7 +152,7 @@ class DateDisplayES(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: diff --git a/gramps/gen/datehandler/_date_fi.py b/gramps/gen/datehandler/_date_fi.py index 7f280934c..3eb57a08d 100644 --- a/gramps/gen/datehandler/_date_fi.py +++ b/gramps/gen/datehandler/_date_fi.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -53,57 +53,57 @@ class DateParserFI(DateParser): # NOTE: these need to be in lower case because the "key" comparison # is done as lower case. In the display method correct capitalization # can be used. - + modifier_to_int = { # examples: # - ennen 1.1.2005 # - noin 1.1.2005 - 'ennen' : Date.MOD_BEFORE, - 'e.' : Date.MOD_BEFORE, - 'noin' : Date.MOD_ABOUT, - 'n.' : Date.MOD_ABOUT, + 'ennen' : Date.MOD_BEFORE, + 'e.' : Date.MOD_BEFORE, + 'noin' : Date.MOD_ABOUT, + 'n.' : Date.MOD_ABOUT, } modifier_after_to_int = { # examples: # - 1.1.2005 jälkeen - 'jälkeen' : Date.MOD_AFTER, - 'j.' : Date.MOD_AFTER, + 'jälkeen' : Date.MOD_AFTER, + 'j.' : Date.MOD_AFTER, } bce = ["ekr.", "ekr"] calendar_to_int = { - 'gregoriaaninen' : Date.CAL_GREGORIAN, - 'greg.' : Date.CAL_GREGORIAN, - 'juliaaninen' : Date.CAL_JULIAN, - 'jul.' : Date.CAL_JULIAN, - 'heprealainen' : Date.CAL_HEBREW, - 'hepr.' : Date.CAL_HEBREW, - 'islamilainen' : Date.CAL_ISLAMIC, - 'isl.' : Date.CAL_ISLAMIC, - 'ranskan vallankumouksen aikainen': Date.CAL_FRENCH, - 'ranskan v.' : Date.CAL_FRENCH, - 'persialainen' : Date.CAL_PERSIAN, - 'pers.' : Date.CAL_PERSIAN, - 'svensk' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'gregoriaaninen' : Date.CAL_GREGORIAN, + 'greg.' : Date.CAL_GREGORIAN, + 'juliaaninen' : Date.CAL_JULIAN, + 'jul.' : Date.CAL_JULIAN, + 'heprealainen' : Date.CAL_HEBREW, + 'hepr.' : Date.CAL_HEBREW, + 'islamilainen' : Date.CAL_ISLAMIC, + 'isl.' : Date.CAL_ISLAMIC, + 'ranskan vallankumouksen aikainen': Date.CAL_FRENCH, + 'ranskan v.' : Date.CAL_FRENCH, + 'persialainen' : Date.CAL_PERSIAN, + 'pers.' : Date.CAL_PERSIAN, + 'svensk' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } quality_to_int = { - 'arviolta' : Date.QUAL_ESTIMATED, - 'arv.' : Date.QUAL_ESTIMATED, - 'laskettuna' : Date.QUAL_CALCULATED, - 'lask.' : Date.QUAL_CALCULATED, + 'arviolta' : Date.QUAL_ESTIMATED, + 'arv.' : Date.QUAL_ESTIMATED, + 'laskettuna' : Date.QUAL_CALCULATED, + 'lask.' : Date.QUAL_CALCULATED, } def init_strings(self): DateParser.init_strings(self) self._text2 = re.compile('(\d+)?\.?\s+?%s\.?\s*((\d+)(/\d+)?)?\s*$' % self._mon_str, re.IGNORECASE) - self._span = re.compile("(?P.+)\s+(-)\s+(?P.+)", + self._span = re.compile("(?P.+)\s+(-)\s+(?P.+)", re.IGNORECASE) self._range = re.compile( - "(vuosien\s*)?(?P.+)\s+ja\s+(?P.+)\s+välillä", + "(vuosien\s*)?(?P.+)\s+ja\s+(?P.+)\s+välillä", re.IGNORECASE) #------------------------------------------------------------------------- @@ -113,17 +113,17 @@ class DateParserFI(DateParser): #------------------------------------------------------------------------- class DateDisplayFI(DateDisplay): """ - Finnish language date display class. + Finnish language date display class. """ _bce_str = "%s ekr." formats = ( - "VVVV-KK-PP (ISO)", + "VVVV-KK-PP (ISO)", "PP.KK.VVVV", "Päivä Kuukausi Vuosi" # Day, full month name, year ) # this definition must agree with its "_display_calendar" method - + display = DateDisplay.display_formatted def _display_calendar(self, date_val, long_months, short_months = None, diff --git a/gramps/gen/datehandler/_date_hr.py b/gramps/gen/datehandler/_date_hr.py index cf81ed643..dc4813fec 100644 --- a/gramps/gen/datehandler/_date_hr.py +++ b/gramps/gen/datehandler/_date_hr.py @@ -51,13 +51,13 @@ from ._datehandler import register_datehandler #------------------------------------------------------------------------- class DateParserHR(DateParser): modifier_to_int = { - 'prije' : Date.MOD_BEFORE, + 'prije' : Date.MOD_BEFORE, 'pr. ' : Date.MOD_BEFORE, 'poslije' : Date.MOD_AFTER, 'po. ' : Date.MOD_AFTER, 'okolo' : Date.MOD_ABOUT, 'ok. ' : Date.MOD_ABOUT, - + } quality_to_int = { @@ -76,8 +76,8 @@ class DateParserHR(DateParser): """ DateParser.init_strings(self) #~ DateParser.calendar_to_int.update({ - #~ 'персидский' : Date.CAL_PERSIAN, - #~ 'п' : Date.CAL_PERSIAN, + #~ 'персидский' : Date.CAL_PERSIAN, + #~ 'п' : Date.CAL_PERSIAN, #~ }) _span_1 = ['od'] _span_2 = ['do'] @@ -97,10 +97,10 @@ class DateParserHR(DateParser): #------------------------------------------------------------------------- class DateDisplayHR(DateDisplay): """ - Croatian language date display class. + Croatian language date display class. """ # TODO fix BUG 7064: non-Gregorian calendars wrongly use BCE notation for negative dates - # not refactoring _bce_str into base class because it'll be gone under #7064 + # not refactoring _bce_str into base class because it'll be gone under #7064 _bce_str = "%s p.n.e." display = DateDisplay.display_formatted diff --git a/gramps/gen/datehandler/_date_it.py b/gramps/gen/datehandler/_date_it.py index 43c42169b..f0f9cd184 100644 --- a/gramps/gen/datehandler/_date_it.py +++ b/gramps/gen/datehandler/_date_it.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -50,44 +50,44 @@ from ._datehandler import register_datehandler class DateParserIT(DateParser): modifier_to_int = { - 'prima del' : Date.MOD_BEFORE, - 'prima' : Date.MOD_BEFORE, - 'dopo del' : Date.MOD_AFTER, - 'dopo' : Date.MOD_AFTER, - 'approssimativamente' : Date.MOD_ABOUT, - 'apross.' : Date.MOD_ABOUT, - 'apross' : Date.MOD_ABOUT, - 'circa il' : Date.MOD_ABOUT, - 'circa' : Date.MOD_ABOUT, - 'ca.' : Date.MOD_ABOUT, - 'ca' : Date.MOD_ABOUT, - 'c.' : Date.MOD_ABOUT, + 'prima del' : Date.MOD_BEFORE, + 'prima' : Date.MOD_BEFORE, + 'dopo del' : Date.MOD_AFTER, + 'dopo' : Date.MOD_AFTER, + 'approssimativamente' : Date.MOD_ABOUT, + 'apross.' : Date.MOD_ABOUT, + 'apross' : Date.MOD_ABOUT, + 'circa il' : Date.MOD_ABOUT, + 'circa' : Date.MOD_ABOUT, + 'ca.' : Date.MOD_ABOUT, + 'ca' : Date.MOD_ABOUT, + 'c.' : Date.MOD_ABOUT, } calendar_to_int = { - 'gregoriano' : Date.CAL_GREGORIAN, - 'g' : Date.CAL_GREGORIAN, - 'giuliano' : Date.CAL_JULIAN, - 'j' : Date.CAL_JULIAN, - 'ebraico' : Date.CAL_HEBREW, - 'e' : Date.CAL_HEBREW, - 'islamico' : Date.CAL_ISLAMIC, - 'i' : Date.CAL_ISLAMIC, - 'rivoluzionario': Date.CAL_FRENCH, - 'r' : Date.CAL_FRENCH, - 'persiano' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, - 'svedese' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'gregoriano' : Date.CAL_GREGORIAN, + 'g' : Date.CAL_GREGORIAN, + 'giuliano' : Date.CAL_JULIAN, + 'j' : Date.CAL_JULIAN, + 'ebraico' : Date.CAL_HEBREW, + 'e' : Date.CAL_HEBREW, + 'islamico' : Date.CAL_ISLAMIC, + 'i' : Date.CAL_ISLAMIC, + 'rivoluzionario': Date.CAL_FRENCH, + 'r' : Date.CAL_FRENCH, + 'persiano' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, + 'svedese' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } quality_to_int = { - 'stimata' : Date.QUAL_ESTIMATED, - 'st.' : Date.QUAL_ESTIMATED, - 'st' : Date.QUAL_ESTIMATED, - 'calcolata' : Date.QUAL_CALCULATED, - 'calc.' : Date.QUAL_CALCULATED, - 'calc' : Date.QUAL_CALCULATED, + 'stimata' : Date.QUAL_ESTIMATED, + 'st.' : Date.QUAL_ESTIMATED, + 'st' : Date.QUAL_ESTIMATED, + 'calcolata' : Date.QUAL_CALCULATED, + 'calc.' : Date.QUAL_CALCULATED, + 'calc' : Date.QUAL_CALCULATED, } def init_strings(self): @@ -97,10 +97,10 @@ class DateParserIT(DateParser): _range_1 = ['tra', 'fra'] _range_2 = ['e'] self._span = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_span_1), '|'.join(_span_2)), + ('|'.join(_span_1), '|'.join(_span_2)), re.IGNORECASE) self._range = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_range_1), '|'.join(_range_2)), + ('|'.join(_range_1), '|'.join(_range_2)), re.IGNORECASE) #------------------------------------------------------------------------- @@ -110,19 +110,19 @@ class DateParserIT(DateParser): #------------------------------------------------------------------------- class DateDisplayIT(DateDisplay): """ - Italian language date display class. + Italian language date display class. """ - long_months = ( "", "gennaio", "febbraio", "marzo", "aprile", - "maggio", "giugno", "luglio", "agosto", "settembre", + long_months = ( "", "gennaio", "febbraio", "marzo", "aprile", + "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre" ) - short_months = ( "", "gen", "feb", "mar", "apr", "mag", "giu", + short_months = ( "", "gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic" ) calendar = ( - "", "Giuliano", "Ebraico", - "Rivoluzionario", "Persiano", "Islamico", - "Svedese" + "", "Giuliano", "Ebraico", + "Rivoluzionario", "Persiano", "Islamico", + "Svedese" ) _mod_str = ("", "prima del ", "dopo del ", "circa il ", "", "", "") @@ -130,29 +130,29 @@ class DateDisplayIT(DateDisplay): _qual_str = ("", "stimata ", "calcolata ") french = ( - '', - 'vendemmiaio', - 'brumaio', - 'frimaio', - 'nevoso', - 'piovoso', - 'ventoso', - 'germile', - 'fiorile', - 'pratile', - 'messidoro', - 'termidoro', - 'fruttidoro', - 'extra', + '', + 'vendemmiaio', + 'brumaio', + 'frimaio', + 'nevoso', + 'piovoso', + 'ventoso', + 'germile', + 'fiorile', + 'pratile', + 'messidoro', + 'termidoro', + 'fruttidoro', + 'extra', ) - + formats = ( - "AAAA-MM-DD (ISO)", "Numerico", "Mese Giorno Anno", + "AAAA-MM-DD (ISO)", "Numerico", "Mese Giorno Anno", "MES Giorno, Anno", "Giorno Mese Anno", "Giorno MES Anno" ) # this must agree with DateDisplayEn's "formats" definition # (since no locale-specific _display_gregorian exists, here) - + def display(self, date): """ Return a text string representing the date. @@ -164,7 +164,7 @@ class DateDisplayIT(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -189,5 +189,5 @@ class DateDisplayIT(DateDisplay): # Register classes # #------------------------------------------------------------------------- -register_datehandler(('it_IT', 'it', 'italian', 'Italian', 'it_CH'), +register_datehandler(('it_IT', 'it', 'italian', 'Italian', 'it_CH'), DateParserIT, DateDisplayIT) diff --git a/gramps/gen/datehandler/_date_ja.py b/gramps/gen/datehandler/_date_ja.py index d0dc29ee2..b2ae0c5c4 100644 --- a/gramps/gen/datehandler/_date_ja.py +++ b/gramps/gen/datehandler/_date_ja.py @@ -93,7 +93,7 @@ class DateParserJA(DateParser): '共和暦' : Date.CAL_FRENCH, 'f' : Date.CAL_FRENCH, 'イラン暦' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, 'スウェーデン暦' : Date.CAL_SWEDISH, 's' : Date.CAL_SWEDISH, }) diff --git a/gramps/gen/datehandler/_date_lt.py b/gramps/gen/datehandler/_date_lt.py index 4dad8b644..d9a58d045 100644 --- a/gramps/gen/datehandler/_date_lt.py +++ b/gramps/gen/datehandler/_date_lt.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -68,9 +68,9 @@ class DateParserLT(DateParser): month_to_int["spalis"] = 10 month_to_int["lapkritis"] = 11 month_to_int["gruodis"] = 12 - + # For not full months - + month_to_int["saus"] = 1 month_to_int["vasa"] = 2 month_to_int["vasar"] = 2 @@ -101,31 +101,31 @@ class DateParserLT(DateParser): month_to_int["gruod"] = 12 modifier_to_int = { - 'prieš' : Date.MOD_BEFORE, - 'po' : Date.MOD_AFTER, - 'apie' : Date.MOD_ABOUT, + 'prieš' : Date.MOD_BEFORE, + 'po' : Date.MOD_AFTER, + 'apie' : Date.MOD_ABOUT, } calendar_to_int = { - 'grigaliaus' : Date.CAL_GREGORIAN, - 'g' : Date.CAL_GREGORIAN, - 'julijaus' : Date.CAL_JULIAN, - 'j' : Date.CAL_JULIAN, - 'hebrajų' : Date.CAL_HEBREW, - 'h' : Date.CAL_HEBREW, - 'islamo' : Date.CAL_ISLAMIC, - 'i' : Date.CAL_ISLAMIC, - 'prancūzų respublikos': Date.CAL_FRENCH, - 'r' : Date.CAL_FRENCH, - 'persų' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, - 'švedų' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'grigaliaus' : Date.CAL_GREGORIAN, + 'g' : Date.CAL_GREGORIAN, + 'julijaus' : Date.CAL_JULIAN, + 'j' : Date.CAL_JULIAN, + 'hebrajų' : Date.CAL_HEBREW, + 'h' : Date.CAL_HEBREW, + 'islamo' : Date.CAL_ISLAMIC, + 'i' : Date.CAL_ISLAMIC, + 'prancūzų respublikos': Date.CAL_FRENCH, + 'r' : Date.CAL_FRENCH, + 'persų' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, + 'švedų' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } quality_to_int = { - 'apytikriai' : Date.QUAL_ESTIMATED, - 'apskaičiuota' : Date.QUAL_CALCULATED, + 'apytikriai' : Date.QUAL_ESTIMATED, + 'apskaičiuota' : Date.QUAL_CALCULATED, } def init_strings(self): @@ -150,35 +150,35 @@ class DateParserLT(DateParser): #------------------------------------------------------------------------- class DateDisplayLT(DateDisplay): """ - Lithuanian language date display class. + Lithuanian language date display class. """ - - long_months = ( "", "sausio", "vasario", "kovo", "balandžio", "gegužės", - "birželio", "liepos", "rugpjūčio", "rugsėjo", "spalio", + + long_months = ( "", "sausio", "vasario", "kovo", "balandžio", "gegužės", + "birželio", "liepos", "rugpjūčio", "rugsėjo", "spalio", "lapkričio", "gruodžio" ) - - long_months_vardininkas = ( "", "sausis", "vasaris", "kovas", "balandis", "gegužė", - "birželis", "liepa", "rugpjūtis", "rugsėjis", "spalis", - "lapkritis", "gruodis" ) - - short_months = ( "", "Sau", "Vas", "Kov", "Bal", "Geg", "Bir", + + long_months_vardininkas = ( "", "sausis", "vasaris", "kovas", "balandis", "gegužė", + "birželis", "liepa", "rugpjūtis", "rugsėjis", "spalis", + "lapkritis", "gruodis" ) + + short_months = ( "", "Sau", "Vas", "Kov", "Bal", "Geg", "Bir", "Lie", "Rgp", "Rgs", "Spa", "Lap", "Grd" ) - + calendar = ( - "", "julijaus", - "hebrajų", - "prancūzų respublikos", - "persų", - "islamo", - "švedų" + "", "julijaus", + "hebrajų", + "prancūzų respublikos", + "persų", + "islamo", + "švedų" ) - _mod_str = ("", - "prieš ", - "po ", - "apie ", + _mod_str = ("", + "prieš ", + "po ", + "apie ", "", "", "") - + _qual_str = ("", "apytikriai ", "apskaičiuota ") formats = ( @@ -231,7 +231,7 @@ class DateDisplayLT(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -240,18 +240,18 @@ class DateDisplayLT(DateDisplay): d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%s%s %s %s %s%s" % (qual_str, 'nuo', d1, 'iki', + return "%s%s %s %s %s%s" % (qual_str, 'nuo', d1, 'iki', d2, scal) elif mod == Date.MOD_RANGE: d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%s%s %s %s %s%s" % (qual_str, 'tarp', d1, 'ir', + return "%s%s %s %s %s%s" % (qual_str, 'tarp', d1, 'ir', d2, scal) else: text = self.display_cal[date.get_calendar()](start) scal = self.format_extras(cal, newyear) - return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, + return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, scal) #------------------------------------------------------------------------- diff --git a/gramps/gen/datehandler/_date_nb.py b/gramps/gen/datehandler/_date_nb.py index 7ce415ffc..5e21139f1 100644 --- a/gramps/gen/datehandler/_date_nb.py +++ b/gramps/gen/datehandler/_date_nb.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -48,50 +48,50 @@ from ._datehandler import register_datehandler class DateParserNb(DateParser): """ Convert a text string into a Date object, expecting a date - notation in the Norwegian language. If the date cannot be converted, + notation in the Norwegian language. If the date cannot be converted, the text string is assigned. """ # modifiers before the date modifier_to_int = { - 'før' : Date.MOD_BEFORE, - 'innen' : Date.MOD_BEFORE, - 'etter' : Date.MOD_AFTER, - 'omkring' : Date.MOD_ABOUT, + 'før' : Date.MOD_BEFORE, + 'innen' : Date.MOD_BEFORE, + 'etter' : Date.MOD_AFTER, + 'omkring' : Date.MOD_ABOUT, 'ca' : Date.MOD_ABOUT } bce = ["f Kr"] calendar_to_int = { - 'gregoriansk ' : Date.CAL_GREGORIAN, - 'g' : Date.CAL_GREGORIAN, - 'juliansk' : Date.CAL_JULIAN, - 'j' : Date.CAL_JULIAN, - 'hebraisk' : Date.CAL_HEBREW, - 'h' : Date.CAL_HEBREW, - 'islamisk' : Date.CAL_ISLAMIC, - 'muslimsk' : Date.CAL_ISLAMIC, - 'i' : Date.CAL_ISLAMIC, - 'fransk' : Date.CAL_FRENCH, - 'fransk republikansk' : Date.CAL_FRENCH, - 'f' : Date.CAL_FRENCH, - 'persisk' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, - 'svensk' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'gregoriansk ' : Date.CAL_GREGORIAN, + 'g' : Date.CAL_GREGORIAN, + 'juliansk' : Date.CAL_JULIAN, + 'j' : Date.CAL_JULIAN, + 'hebraisk' : Date.CAL_HEBREW, + 'h' : Date.CAL_HEBREW, + 'islamisk' : Date.CAL_ISLAMIC, + 'muslimsk' : Date.CAL_ISLAMIC, + 'i' : Date.CAL_ISLAMIC, + 'fransk' : Date.CAL_FRENCH, + 'fransk republikansk' : Date.CAL_FRENCH, + 'f' : Date.CAL_FRENCH, + 'persisk' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, + 'svensk' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } - + quality_to_int = { - 'estimert' : Date.QUAL_ESTIMATED, - 'beregnet' : Date.QUAL_CALCULATED, + 'estimert' : Date.QUAL_ESTIMATED, + 'beregnet' : Date.QUAL_CALCULATED, } - + def init_strings(self): DateParser.init_strings(self) - self._span = re.compile("(fra)?\s*(?P.+)\s*(til|--|–)\s*(?P.+)", + self._span = re.compile("(fra)?\s*(?P.+)\s*(til|--|–)\s*(?P.+)", re.IGNORECASE) - self._range = re.compile("(mellom)\s+(?P.+)\s+og\s+(?P.+)", + self._range = re.compile("(mellom)\s+(?P.+)\s+og\s+(?P.+)", re.IGNORECASE) #------------------------------------------------------------------------- @@ -101,41 +101,41 @@ class DateParserNb(DateParser): #------------------------------------------------------------------------- class DateDisplayNb(DateDisplay): """ - Norwegian language date display class. + Norwegian language date display class. """ - long_months = ( "", "januar", "februar", "mars", "april", "mai", - "juni", "juli", "august", "september", "oktober", + long_months = ( "", "januar", "februar", "mars", "april", "mai", + "juni", "juli", "august", "september", "oktober", "november", "desember" ) - - short_months = ( "", "jan", "feb", "mar", "apr", "mai", "jun", + + short_months = ( "", "jan", "feb", "mar", "apr", "mai", "jun", "jul", "aug", "sep", "okt", "nov", "des" ) formats = ( - "ÅÅÅÅ-MM-DD (ISO)", - "Numerisk", - "Måned dag, år", - "Mån Dag År", - "Dag måned år", - "Dag Mån År", + "ÅÅÅÅ-MM-DD (ISO)", + "Numerisk", + "Måned dag, år", + "Mån Dag År", + "Dag måned år", + "Dag Mån År", ) # this must agree with DateDisplayEn's "formats" definition # (since no locale-specific _display_gregorian exists, here) calendar = ( - "", - "juliansk", - "hebraisk", - "fransk republikansk", - "persisk", - "islamisk", - "svensk" + "", + "juliansk", + "hebraisk", + "fransk republikansk", + "persisk", + "islamisk", + "svensk" ) - + _mod_str = ("", "før ", "etter ", "ca ", "", "", "") _qual_str = ("", "beregnet ", "beregnet ") - + _bce_str = "%s f Kr" def display(self, date): @@ -163,12 +163,12 @@ class DateDisplayNb(DateDisplay): d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%smellom %s og %s%s" % (qual_str, d1, d2, + return "%smellom %s og %s%s" % (qual_str, d1, d2, scal) else: text = self.display_cal[date.get_calendar()](start) scal = self.format_extras(cal, newyear) - return "%s%s%s%s" % (qual_str, self._mod_str[mod], + return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, scal) #------------------------------------------------------------------------- diff --git a/gramps/gen/datehandler/_date_nl.py b/gramps/gen/datehandler/_date_nl.py index 10ccdd6a0..0dd441baa 100644 --- a/gramps/gen/datehandler/_date_nl.py +++ b/gramps/gen/datehandler/_date_nl.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -58,7 +58,7 @@ class DateParserNL(DateParser): # no matter what the current locale is month_to_int["januari"] = 1 month_to_int["jan"] = 1 - # Add other common latin, local and historical variants + # Add other common latin, local and historical variants month_to_int["januaris"] = 1 month_to_int["feber"] = 2 month_to_int["februaris"] = 2 @@ -81,53 +81,53 @@ class DateParserNL(DateParser): month_to_int["10bris"] = 12 month_to_int["xber"] = 12 month_to_int["xbris"] = 12 - + modifier_to_int = { - 'voor' : Date.MOD_BEFORE, - 'na' : Date.MOD_AFTER, - 'tegen' : Date.MOD_ABOUT, - 'om' : Date.MOD_ABOUT, - 'rond' : Date.MOD_ABOUT, - 'circa' : Date.MOD_ABOUT, - 'ca.' : Date.MOD_ABOUT, + 'voor' : Date.MOD_BEFORE, + 'na' : Date.MOD_AFTER, + 'tegen' : Date.MOD_ABOUT, + 'om' : Date.MOD_ABOUT, + 'rond' : Date.MOD_ABOUT, + 'circa' : Date.MOD_ABOUT, + 'ca.' : Date.MOD_ABOUT, } calendar_to_int = { - 'gregoriaans' : Date.CAL_GREGORIAN, - 'greg.' : Date.CAL_GREGORIAN, - 'juliaans' : Date.CAL_JULIAN, - 'jul.' : Date.CAL_JULIAN, - 'hebreeuws' : Date.CAL_HEBREW, - 'hebr.' : Date.CAL_HEBREW, - 'islamitisch' : Date.CAL_ISLAMIC, - 'isl.' : Date.CAL_ISLAMIC, - 'franse republiek': Date.CAL_FRENCH, - 'fran.' : Date.CAL_FRENCH, - 'persisch' : Date.CAL_PERSIAN, - 'zweeds' : Date.CAL_SWEDISH, - 'z' : Date.CAL_SWEDISH, + 'gregoriaans' : Date.CAL_GREGORIAN, + 'greg.' : Date.CAL_GREGORIAN, + 'juliaans' : Date.CAL_JULIAN, + 'jul.' : Date.CAL_JULIAN, + 'hebreeuws' : Date.CAL_HEBREW, + 'hebr.' : Date.CAL_HEBREW, + 'islamitisch' : Date.CAL_ISLAMIC, + 'isl.' : Date.CAL_ISLAMIC, + 'franse republiek': Date.CAL_FRENCH, + 'fran.' : Date.CAL_FRENCH, + 'persisch' : Date.CAL_PERSIAN, + 'zweeds' : Date.CAL_SWEDISH, + 'z' : Date.CAL_SWEDISH, } quality_to_int = { - 'geschat' : Date.QUAL_ESTIMATED, - 'gesch.' : Date.QUAL_ESTIMATED, - 'berekend' : Date.QUAL_CALCULATED, - 'ber.' : Date.QUAL_CALCULATED, + 'geschat' : Date.QUAL_ESTIMATED, + 'gesch.' : Date.QUAL_ESTIMATED, + 'berekend' : Date.QUAL_CALCULATED, + 'ber.' : Date.QUAL_CALCULATED, } bce = ["voor onze tijdrekening", "voor Christus", "v. Chr."] + DateParser.bce - + def init_strings(self): DateParser.init_strings(self) - self._span = re.compile("(van)\s+(?P.+)\s+(tot)\s+(?P.+)", + self._span = re.compile("(van)\s+(?P.+)\s+(tot)\s+(?P.+)", re.IGNORECASE) - self._range = re.compile("tussen\s+(?P.+)\s+en\s+(?P.+)", + self._range = re.compile("tussen\s+(?P.+)\s+en\s+(?P.+)", re.IGNORECASE) self._text2 = re.compile('(\d+)?.?\s+?%s\s*((\d+)(/\d+)?)?' - % self._mon_str, + % self._mon_str, re.IGNORECASE) self._jtext2 = re.compile('(\d+)?.?\s+?%s\s*((\d+)(/\d+)?)?' - % self._jmon_str, + % self._jmon_str, re.IGNORECASE) #------------------------------------------------------------------------- @@ -137,29 +137,29 @@ class DateParserNL(DateParser): #------------------------------------------------------------------------- class DateDisplayNL(DateDisplay): """ - Dutch language date display class. + Dutch language date display class. """ # TODO: Translate these month strings: - long_months = ( "", "januari", "februari", "maart", "april", "mei", - "juni", "juli", "augustus", "september", "oktober", + long_months = ( "", "januari", "februari", "maart", "april", "mei", + "juni", "juli", "augustus", "september", "oktober", "november", "december" ) - - short_months = ( "", "jan", "feb", "mrt", "apr", "mei", "jun", + + short_months = ( "", "jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ) - + calendar = ( - "", "juliaans", "hebreeuws", + "", "juliaans", "hebreeuws", "franse republiek", "persisch", "islamitisch", "zweeds" ) _mod_str = ("", "voor ", "na ", "rond ", "", "", "") - + _qual_str = ("", "geschat ", "berekend ") - + _bce_str = "%s v. Chr." formats = ( - "JJJJ-MM-DD (ISO)", "Numerisch DD/MM/JJ", "Maand Dag, Jaar", + "JJJJ-MM-DD (ISO)", "Numerisch DD/MM/JJ", "Maand Dag, Jaar", "Mnd. Dag Jaar", "Dag Maand Jaar", "Dag Mnd. Jaar" ) # this definition must agree with its "_display_gregorian" method @@ -192,7 +192,7 @@ class DateDisplayNL(DateDisplay): else: value = "%s %s" % (self.long_months[date_val[1]], year) else: - value = "%s %d, %s" % (self.long_months[date_val[1]], + value = "%s %d, %s" % (self.long_months[date_val[1]], date_val[0], year) elif self.format == 3: # month_abbreviation day, year @@ -202,7 +202,7 @@ class DateDisplayNL(DateDisplay): else: value = "%s %s" % (self.short_months[date_val[1]], year) else: - value = "%s %d, %s" % (self.short_months[date_val[1]], + value = "%s %d, %s" % (self.short_months[date_val[1]], date_val[0], year) elif self.format == 4: # day month_name year @@ -212,7 +212,7 @@ class DateDisplayNL(DateDisplay): else: value = "%s %s" % (self.long_months[date_val[1]], year) else: - value = "%d %s %s" % (date_val[0], + value = "%d %s %s" % (date_val[0], self.long_months[date_val[1]], year) else: # day month_abbreviation year @@ -222,7 +222,7 @@ class DateDisplayNL(DateDisplay): else: value = "%s %s" % (self.short_months[date_val[1]], year) else: - value = "%d %s %s" % (date_val[0], + value = "%d %s %s" % (date_val[0], self.short_months[date_val[1]], year) if date_val[2] < 0: return self._bce_str % value @@ -240,7 +240,7 @@ class DateDisplayNL(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -249,18 +249,18 @@ class DateDisplayNL(DateDisplay): d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%s%s %s %s %s%s" % (qual_str, 'van', d1, + return "%s%s %s %s %s%s" % (qual_str, 'van', d1, 'tot', d2, scal) elif mod == Date.MOD_RANGE: d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%stussen %s en %s%s" % (qual_str, d1, d2, + return "%stussen %s en %s%s" % (qual_str, d1, d2, scal) else: text = self.display_cal[date.get_calendar()](start) scal = self.format_extras(cal, newyear) - return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, + return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, scal) #------------------------------------------------------------------------- @@ -268,5 +268,5 @@ class DateDisplayNL(DateDisplay): # Register classes # #------------------------------------------------------------------------- -register_datehandler(('nl_NL', 'dutch', 'Dutch', 'nl_BE', 'nl'), +register_datehandler(('nl_NL', 'dutch', 'Dutch', 'nl_BE', 'nl'), DateParserNL, DateDisplayNL) diff --git a/gramps/gen/datehandler/_date_pl.py b/gramps/gen/datehandler/_date_pl.py index cc5b38047..7dc4afb01 100644 --- a/gramps/gen/datehandler/_date_pl.py +++ b/gramps/gen/datehandler/_date_pl.py @@ -112,7 +112,7 @@ class DateParserPL(DateParser): month_to_int["paz"] = 10 modifier_to_int = { - 'przed' : Date.MOD_BEFORE, + 'przed' : Date.MOD_BEFORE, 'po' : Date.MOD_AFTER, 'około' : Date.MOD_ABOUT, 'ok.' : Date.MOD_ABOUT, @@ -135,7 +135,7 @@ class DateParserPL(DateParser): 'francuski republikański': Date.CAL_FRENCH, 'franc.' : Date.CAL_FRENCH, 'perski' : Date.CAL_PERSIAN, - 'szwedzki' : Date.CAL_SWEDISH, + 'szwedzki' : Date.CAL_SWEDISH, 's' : Date.CAL_SWEDISH, # Alternative forms: nouns without polish accent letters # (misspellings sometimes used in emails) @@ -153,7 +153,7 @@ class DateParserPL(DateParser): bce = ["przed naszą erą", "przed Chrystusem", "p.n.e."] + DateParser.bce - + def init_strings(self): DateParser.init_strings(self) self._span = re.compile("(od)\s+(?P.+)\s+(do)\s+(?P.+)", re.IGNORECASE) @@ -171,26 +171,26 @@ class DateParserPL(DateParser): #------------------------------------------------------------------------- class DateDisplayPL(DateDisplay): """ - Polish language date display class. + Polish language date display class. """ - long_months = ( "", "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", - "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", + long_months = ( "", "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", + "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień" ) - - short_months = ( "", "Sty", "Lut", "Mar", "Kwi", "Maj", "Cze", + + short_months = ( "", "Sty", "Lut", "Mar", "Kwi", "Maj", "Cze", "Lip", "Sie", "Wrz", "Paź", "Lis", "Gru" ) - + calendar = ( - "", "juliański", "hebrajski", - "francuski republikański", "perski", "islamski", - "swedish" + "", "juliański", "hebrajski", + "francuski republikański", "perski", "islamski", + "swedish" ) _mod_str = ("", "przed ", "po ", "ok. ", "", "", "") - + _qual_str = ("", "szacowany ", "obliczony ") - + _bce_str = "%s p.n.e." formats = ( @@ -198,7 +198,7 @@ class DateDisplayPL(DateDisplay): "Dzień.Miesiąc.Rok", "Dzień Miesiąc Rok", "Dzień MieRzym Rok" ) # this definition must agree with its "_display_gregorian" method - + roman_months = ( "", "I", @@ -242,7 +242,7 @@ class DateDisplayPL(DateDisplay): else: value = "%s %s" % (self.long_months[date_val[1]], year) else: - value = "%s %d, %s" % (self.long_months[date_val[1]], + value = "%s %d, %s" % (self.long_months[date_val[1]], date_val[0], year) elif self.format == 3: # day. month_number. year @@ -261,7 +261,7 @@ class DateDisplayPL(DateDisplay): else: value = "%s %s" % (self.long_months[date_val[1]], year) else: - value = "%d %s %s" % (date_val[0], + value = "%d %s %s" % (date_val[0], self.long_months[date_val[1]], year) else: # day Roman_number_month year @@ -271,7 +271,7 @@ class DateDisplayPL(DateDisplay): else: value = "%s %s" % (self.roman_months[date_val[1]], year) else: - value = "%d %s %s" % (date_val[0], + value = "%d %s %s" % (date_val[0], self.roman_months[date_val[1]], year) if date_val[2] < 0: return self._bce_str % value @@ -289,7 +289,7 @@ class DateDisplayPL(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -298,18 +298,18 @@ class DateDisplayPL(DateDisplay): d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%s%s %s %s %s%s" % (qual_str, 'od', d1, 'do', d2, + return "%s%s %s %s %s%s" % (qual_str, 'od', d1, 'do', d2, scal) elif mod == Date.MOD_RANGE: d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%s%s %s %s %s%s" % (qual_str, 'między', d1, 'a', d2, + return "%s%s %s %s %s%s" % (qual_str, 'między', d1, 'a', d2, scal) else: text = self.display_cal[date.get_calendar()](start) scal = self.format_extras(cal, newyear) - return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, + return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, scal) #------------------------------------------------------------------------- diff --git a/gramps/gen/datehandler/_date_pt.py b/gramps/gen/datehandler/_date_pt.py index 913653373..8bee5d0fe 100644 --- a/gramps/gen/datehandler/_date_pt.py +++ b/gramps/gen/datehandler/_date_pt.py @@ -50,10 +50,10 @@ from ._datehandler import register_datehandler class DateParserPT(DateParser): modifier_to_int = { - 'antes de' : Date.MOD_BEFORE, - 'antes' : Date.MOD_BEFORE, - 'ant.' : Date.MOD_BEFORE, - 'ant' : Date.MOD_BEFORE, + 'antes de' : Date.MOD_BEFORE, + 'antes' : Date.MOD_BEFORE, + 'ant.' : Date.MOD_BEFORE, + 'ant' : Date.MOD_BEFORE, 'até' : Date.MOD_BEFORE, 'depois de' : Date.MOD_AFTER, 'depois' : Date.MOD_AFTER, @@ -85,8 +85,8 @@ class DateParserPT(DateParser): 'r' : Date.CAL_FRENCH, 'persa' : Date.CAL_PERSIAN, 'p' : Date.CAL_PERSIAN, - 'swedish' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'swedish' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } quality_to_int = { @@ -118,19 +118,19 @@ class DateParserPT(DateParser): #------------------------------------------------------------------------- class DateDisplayPT(DateDisplay): """ - Portuguese language date display class. + Portuguese language date display class. """ - long_months = ( "", "Janeiro", "Fevereiro", "Março", "Abril", "Maio", - "Junho", "Julho", "Agosto", "Setembro", "Outubro", + long_months = ( "", "Janeiro", "Fevereiro", "Março", "Abril", "Maio", + "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ) - - short_months = ( "", "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", + + short_months = ( "", "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez" ) - + calendar = ( - "", "Juliano", "Hebreu", - "Revolucionário", "Persa", "Islâmico", - "Sueco" + "", "Juliano", "Hebreu", + "Revolucionário", "Persa", "Islâmico", + "Sueco" ) _mod_str = ("","antes de ","depois de ","por volta de ","","","") @@ -143,7 +143,7 @@ class DateDisplayPT(DateDisplay): ) # this must agree with DateDisplayEn's "formats" definition # (since no locale-specific _display_gregorian exists, here) - + def display(self,date): """ Return a text string representing the date. @@ -155,7 +155,7 @@ class DateDisplayPT(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: diff --git a/gramps/gen/datehandler/_date_ru.py b/gramps/gen/datehandler/_date_ru.py index 973c8cc93..c5489a2cd 100644 --- a/gramps/gen/datehandler/_date_ru.py +++ b/gramps/gen/datehandler/_date_ru.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -47,49 +47,49 @@ from ._datehandler import register_datehandler #------------------------------------------------------------------------- class DateParserRU(DateParser): modifier_to_int = { - 'перед' : Date.MOD_BEFORE, - 'по' : Date.MOD_BEFORE, - 'до' : Date.MOD_BEFORE, - 'после' : Date.MOD_AFTER, - 'п.' : Date.MOD_AFTER, - 'п' : Date.MOD_AFTER, - 'с' : Date.MOD_AFTER, - 'ок' : Date.MOD_ABOUT, - 'ок.' : Date.MOD_ABOUT, - 'около' : Date.MOD_ABOUT, - 'примерно' : Date.MOD_ABOUT, - 'прим' : Date.MOD_ABOUT, - 'прим.' : Date.MOD_ABOUT, - 'приблизительно' : Date.MOD_ABOUT, - 'приб.' : Date.MOD_ABOUT, - 'прибл.' : Date.MOD_ABOUT, - 'приб' : Date.MOD_ABOUT, - 'прибл' : Date.MOD_ABOUT, + 'перед' : Date.MOD_BEFORE, + 'по' : Date.MOD_BEFORE, + 'до' : Date.MOD_BEFORE, + 'после' : Date.MOD_AFTER, + 'п.' : Date.MOD_AFTER, + 'п' : Date.MOD_AFTER, + 'с' : Date.MOD_AFTER, + 'ок' : Date.MOD_ABOUT, + 'ок.' : Date.MOD_ABOUT, + 'около' : Date.MOD_ABOUT, + 'примерно' : Date.MOD_ABOUT, + 'прим' : Date.MOD_ABOUT, + 'прим.' : Date.MOD_ABOUT, + 'приблизительно' : Date.MOD_ABOUT, + 'приб.' : Date.MOD_ABOUT, + 'прибл.' : Date.MOD_ABOUT, + 'приб' : Date.MOD_ABOUT, + 'прибл' : Date.MOD_ABOUT, } quality_to_int = { - 'оценено' : Date.QUAL_ESTIMATED, - 'оцен.' : Date.QUAL_ESTIMATED, - 'оц.' : Date.QUAL_ESTIMATED, - 'оцен' : Date.QUAL_ESTIMATED, - 'оц' : Date.QUAL_ESTIMATED, - 'вычислено' : Date.QUAL_CALCULATED, - 'вычисл.' : Date.QUAL_CALCULATED, - 'выч.' : Date.QUAL_CALCULATED, - 'вычисл' : Date.QUAL_CALCULATED, - 'выч' : Date.QUAL_CALCULATED, + 'оценено' : Date.QUAL_ESTIMATED, + 'оцен.' : Date.QUAL_ESTIMATED, + 'оц.' : Date.QUAL_ESTIMATED, + 'оцен' : Date.QUAL_ESTIMATED, + 'оц' : Date.QUAL_ESTIMATED, + 'вычислено' : Date.QUAL_CALCULATED, + 'вычисл.' : Date.QUAL_CALCULATED, + 'выч.' : Date.QUAL_CALCULATED, + 'вычисл' : Date.QUAL_CALCULATED, + 'выч' : Date.QUAL_CALCULATED, } bce = [ - 'до нашей эры', 'до н. э.', 'до н.э.', + 'до нашей эры', 'до н. э.', 'до н.э.', 'до н э', 'до нэ'] + DateParser.bce def init_strings(self): DateParser.init_strings(self) DateParser.calendar_to_int.update({ - 'персидский' : Date.CAL_PERSIAN, - 'п' : Date.CAL_PERSIAN, + 'персидский' : Date.CAL_PERSIAN, + 'п' : Date.CAL_PERSIAN, }) _span_1 = ['с', 'от'] #_span_2 = ['по', 'до'] # <-- clashes with bce parsing :-( @@ -102,7 +102,7 @@ class DateParserRU(DateParser): self._range = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % ('|'.join(_range_1), '|'.join(_range_2)), re.IGNORECASE) - + #------------------------------------------------------------------------- # # Russian displayer @@ -110,7 +110,7 @@ class DateParserRU(DateParser): #------------------------------------------------------------------------- class DateDisplayRU(DateDisplay): """ - Russian language date display class. + Russian language date display class. """ # TODO fix BUG 7064: non-Gregorian calendars wrongly use BCE notation for negative dates diff --git a/gramps/gen/datehandler/_date_sk.py b/gramps/gen/datehandler/_date_sk.py index f95f14c7c..0f628b1e4 100644 --- a/gramps/gen/datehandler/_date_sk.py +++ b/gramps/gen/datehandler/_date_sk.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -48,36 +48,36 @@ from ._datehandler import register_datehandler class DateParserSK(DateParser): modifier_to_int = { - 'pred' : Date.MOD_BEFORE, - 'do' : Date.MOD_BEFORE, - 'po' : Date.MOD_AFTER, - 'asi' : Date.MOD_ABOUT, - 'okolo' : Date.MOD_ABOUT, - 'pribl.' : Date.MOD_ABOUT, + 'pred' : Date.MOD_BEFORE, + 'do' : Date.MOD_BEFORE, + 'po' : Date.MOD_AFTER, + 'asi' : Date.MOD_ABOUT, + 'okolo' : Date.MOD_ABOUT, + 'pribl.' : Date.MOD_ABOUT, } calendar_to_int = { - 'gregoriánsky' : Date.CAL_GREGORIAN, - 'g' : Date.CAL_GREGORIAN, - 'juliánsky' : Date.CAL_JULIAN, - 'j' : Date.CAL_JULIAN, - 'hebrejský' : Date.CAL_HEBREW, - 'h' : Date.CAL_HEBREW, - 'islamský' : Date.CAL_ISLAMIC, - 'i' : Date.CAL_ISLAMIC, - 'republikánsky' : Date.CAL_FRENCH, - 'r' : Date.CAL_FRENCH, - 'perzský' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, - 'švédsky' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'gregoriánsky' : Date.CAL_GREGORIAN, + 'g' : Date.CAL_GREGORIAN, + 'juliánsky' : Date.CAL_JULIAN, + 'j' : Date.CAL_JULIAN, + 'hebrejský' : Date.CAL_HEBREW, + 'h' : Date.CAL_HEBREW, + 'islamský' : Date.CAL_ISLAMIC, + 'i' : Date.CAL_ISLAMIC, + 'republikánsky' : Date.CAL_FRENCH, + 'r' : Date.CAL_FRENCH, + 'perzský' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, + 'švédsky' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } quality_to_int = { - 'odhadovaný' : Date.QUAL_ESTIMATED, - 'odh.' : Date.QUAL_ESTIMATED, - 'vypočítaný' : Date.QUAL_CALCULATED, - 'vyp.' : Date.QUAL_CALCULATED, + 'odhadovaný' : Date.QUAL_ESTIMATED, + 'odh.' : Date.QUAL_ESTIMATED, + 'vypočítaný' : Date.QUAL_CALCULATED, + 'vyp.' : Date.QUAL_CALCULATED, } def init_strings(self): @@ -87,10 +87,10 @@ class DateParserSK(DateParser): _range_1 = ['medzi'] _range_2 = ['a'] self._span = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_span_1), '|'.join(_span_2)), + ('|'.join(_span_1), '|'.join(_span_2)), re.IGNORECASE) self._range = re.compile("(%s)\s+(?P.+)\s+(%s)\s+(?P.+)" % - ('|'.join(_range_1), '|'.join(_range_2)), + ('|'.join(_range_1), '|'.join(_range_2)), re.IGNORECASE) #------------------------------------------------------------------------- @@ -100,27 +100,27 @@ class DateParserSK(DateParser): #------------------------------------------------------------------------- class DateDisplaySK(DateDisplay): """ - Slovak language date display class. + Slovak language date display class. """ - long_months = ( "", "január", "február", "marec", "apríl", "máj", - "jún", "júl", "august", "september", "október", + long_months = ( "", "január", "február", "marec", "apríl", "máj", + "jún", "júl", "august", "september", "október", "november", "december" ) - - short_months = ( "", "jan", "feb", "mar", "apr", "máj", "jún", + + short_months = ( "", "jan", "feb", "mar", "apr", "máj", "jún", "júl", "aug", "sep", "okt", "nov", "dec" ) - + calendar = ( - "", "juliánsky", "hebrejský", - "republikánsky", "perzský", "islamský", - "švédsky" + "", "juliánsky", "hebrejský", + "republikánsky", "perzský", "islamský", + "švédsky" ) _mod_str = ("", "pred ", "po ", "okolo ", "", "", "") - + _qual_str = ("", "odh. ", "vyp. ") formats = ( - "RRRR-MM-DD (ISO)", "numerický", "Mesiac Deň, Rok", + "RRRR-MM-DD (ISO)", "numerický", "Mesiac Deň, Rok", "MES Deň, Rok", "Deň, Mesiac, Rok", "Deň MES Rok" ) # this must agree with DateDisplayEn's "formats" definition @@ -137,7 +137,7 @@ class DateDisplaySK(DateDisplay): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -146,13 +146,13 @@ class DateDisplaySK(DateDisplay): d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%s%s %s %s %s%s" % (qual_str, 'od', d1, + return "%s%s %s %s %s%s" % (qual_str, 'od', d1, 'do', d2, scal) elif mod == Date.MOD_RANGE: d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%s%s %s %s %s%s" % (qual_str, 'medzi', + return "%s%s %s %s %s%s" % (qual_str, 'medzi', d1, 'a', d2, scal) else: text = self.display_cal[date.get_calendar()](start) diff --git a/gramps/gen/datehandler/_date_sl.py b/gramps/gen/datehandler/_date_sl.py index 364869318..60976e039 100644 --- a/gramps/gen/datehandler/_date_sl.py +++ b/gramps/gen/datehandler/_date_sl.py @@ -51,9 +51,9 @@ class DateParserSL(DateParser): """ Converts a text string into a Date object """ - + modifier_to_int = { - 'pred' : Date.MOD_BEFORE, + 'pred' : Date.MOD_BEFORE, 'pr.' : Date.MOD_BEFORE, 'po' : Date.MOD_AFTER, 'okoli' : Date.MOD_ABOUT, @@ -61,11 +61,11 @@ class DateParserSL(DateParser): 'okr.' : Date.MOD_ABOUT, 'ok.' : Date.MOD_ABOUT, 'cca.' : Date.MOD_ABOUT, - 'cca' : Date.MOD_ABOUT, - 'circa' : Date.MOD_ABOUT, + 'cca' : Date.MOD_ABOUT, + 'circa' : Date.MOD_ABOUT, 'ca.' : Date.MOD_ABOUT, 'približno' : Date.MOD_ABOUT, - 'pribl.' : Date.MOD_ABOUT, + 'pribl.' : Date.MOD_ABOUT, } quality_to_int = { @@ -91,11 +91,11 @@ class DateParserSL(DateParser): % self._mon_str, re.IGNORECASE) # match Day.Month.Year. self._numeric = re.compile("((\d+)[/\.-])?\s*((\d+)[/\.-])?\s*(\d+)\.?$") - - self._span = re.compile("od\s+(?P.+)\s+do\s+(?P.+)", + + self._span = re.compile("od\s+(?P.+)\s+do\s+(?P.+)", re.IGNORECASE) self._range = re.compile( - "med\s+(?P.+)\s+in\s+(?P.+)", + "med\s+(?P.+)\s+in\s+(?P.+)", re.IGNORECASE) self._jtext2 = re.compile('(\d+)?.?\s+?%s\s*((\d+)(/\d+)?)?'\ % self._jmon_str, re.IGNORECASE) @@ -107,10 +107,10 @@ class DateParserSL(DateParser): #------------------------------------------------------------------------- class DateDisplaySL(DateDisplay): """ - Slovenian language date display class. + Slovenian language date display class. """ # TODO fix BUG 7064: non-Gregorian calendars wrongly use BCE notation for negative dates - # not refactoring _bce_str into base class because it'll be gone under #7064 + # not refactoring _bce_str into base class because it'll be gone under #7064 _bce_str = "%s pr.Kr." display = DateDisplay.display_formatted @@ -120,6 +120,6 @@ class DateDisplaySL(DateDisplay): # Register classes # #------------------------------------------------------------------------- -register_datehandler(("sl", "SL", "sl_SI", "slovenščina", "slovenian", "Slovenian", +register_datehandler(("sl", "SL", "sl_SI", "slovenščina", "slovenian", "Slovenian", "sl_SI.UTF8", "sl_SI.UTF-8", "sl_SI.utf-8", "sl_SI.utf8"), DateParserSL, DateDisplaySL) diff --git a/gramps/gen/datehandler/_date_sr.py b/gramps/gen/datehandler/_date_sr.py index f03d76942..c99cd3496 100644 --- a/gramps/gen/datehandler/_date_sr.py +++ b/gramps/gen/datehandler/_date_sr.py @@ -53,7 +53,7 @@ class DateParserSR(DateParser): Converts a text string into a Date object """ month_to_int = DateParser.month_to_int - + month_to_int["januar"] = 1 month_to_int["januara"] = 1 month_to_int["jan"] = 1 @@ -61,7 +61,7 @@ class DateParserSR(DateParser): month_to_int["јануара"] = 1 month_to_int["јануар"] = 1 month_to_int["i"] = 1 - + month_to_int["februar"] = 2 month_to_int["februara"] = 2 month_to_int["feb"] = 2 @@ -69,7 +69,7 @@ class DateParserSR(DateParser): month_to_int["фебруар"] = 2 month_to_int["фебруара"] = 2 month_to_int["ii"] = 2 - + month_to_int["mart"] = 3 month_to_int["marta"] = 3 month_to_int["mar"] = 3 @@ -77,7 +77,7 @@ class DateParserSR(DateParser): month_to_int["март"] = 3 month_to_int["марта"] = 3 month_to_int["iii"] = 3 - + month_to_int["april"] = 4 month_to_int["aprila"] = 4 month_to_int["apr"] = 4 @@ -91,7 +91,7 @@ class DateParserSR(DateParser): month_to_int["мај"] = 5 month_to_int["маја"] = 5 month_to_int["v"] = 5 - + month_to_int["jun"] = 6 month_to_int["juna"] = 6 month_to_int["јун"] = 6 @@ -103,7 +103,7 @@ class DateParserSR(DateParser): month_to_int["јул"] = 7 month_to_int["јула"] = 7 month_to_int["vii"] = 7 - + month_to_int["avgust"] = 8 month_to_int["avgusta"] = 8 month_to_int["avg"] = 8 @@ -111,7 +111,7 @@ class DateParserSR(DateParser): month_to_int["август"] = 8 month_to_int["августа"] = 8 month_to_int["viii"] = 8 - + month_to_int["septembar"] = 9 month_to_int["septembra"] = 9 month_to_int["sep"] = 9 @@ -119,7 +119,7 @@ class DateParserSR(DateParser): month_to_int["септембар"] = 9 month_to_int["септембра"] = 9 month_to_int["ix"] = 9 - + month_to_int["oktobar"] = 10 month_to_int["oktobra"] = 10 month_to_int["okt"] = 10 @@ -127,7 +127,7 @@ class DateParserSR(DateParser): month_to_int["октобар"] = 10 month_to_int["октобра"] = 10 month_to_int["x"] = 10 - + month_to_int["novembar"] = 11 month_to_int["novembra"] = 11 month_to_int["nov"] = 11 @@ -135,7 +135,7 @@ class DateParserSR(DateParser): month_to_int["новембар"] = 11 month_to_int["новембра"] = 11 month_to_int["xi"] = 11 - + month_to_int["decembar"] = 12 month_to_int["decembra"] = 12 month_to_int["dec"] = 12 @@ -143,14 +143,14 @@ class DateParserSR(DateParser): month_to_int["децембар"] = 12 month_to_int["децембра"] = 12 month_to_int["xii"] = 12 - + modifier_to_int = { - 'pre' : Date.MOD_BEFORE, + 'pre' : Date.MOD_BEFORE, 'posle' : Date.MOD_AFTER, 'oko' : Date.MOD_ABOUT, 'cca' : Date.MOD_ABOUT, - 'пре' : Date.MOD_BEFORE, + 'пре' : Date.MOD_BEFORE, 'после' : Date.MOD_AFTER, 'око' : Date.MOD_ABOUT, } @@ -168,8 +168,8 @@ class DateParserSR(DateParser): 'franc.' : Date.CAL_FRENCH, 'persijski' : Date.CAL_PERSIAN, 'pers. ' : Date.CAL_PERSIAN, - 'švedski' : Date.CAL_SWEDISH, - 'šv.' : Date.CAL_SWEDISH, + 'švedski' : Date.CAL_SWEDISH, + 'šv.' : Date.CAL_SWEDISH, 'грегоријански' : Date.CAL_GREGORIAN, 'грег.' : Date.CAL_GREGORIAN, @@ -183,8 +183,8 @@ class DateParserSR(DateParser): 'франц.' : Date.CAL_FRENCH, 'персијски' : Date.CAL_PERSIAN, 'перс. ' : Date.CAL_PERSIAN, - 'шведски' : Date.CAL_SWEDISH, - 'шв' : Date.CAL_SWEDISH, + 'шведски' : Date.CAL_SWEDISH, + 'шв' : Date.CAL_SWEDISH, } quality_to_int = { @@ -269,7 +269,7 @@ class DateDisplaySR_Base(DateDisplay): else: value = "%s %s." % (self.short_months[date_val[1]], year) else: - value = "%d. %s %s." % (date_val[0], + value = "%d. %s %s." % (date_val[0], self.short_months[date_val[1]], year) elif self.format == 3: # day. month_name year. @@ -279,7 +279,7 @@ class DateDisplaySR_Base(DateDisplay): else: value = "%s %s." % (self.long_months[date_val[1]], year) else: - value = "%d. %s %s." % (date_val[0], + value = "%d. %s %s." % (date_val[0], self.long_months[date_val[1]], year) else: # day. Roman_number_month year. @@ -311,7 +311,7 @@ class DateDisplaySR_Base(DateDisplay): span2 = self._span2 range1 = self._range1 range2 = self._range2 - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -331,7 +331,7 @@ class DateDisplaySR_Base(DateDisplay): else: text = self.display_cal[date.get_calendar()](start) scal = self.format_extras(cal, newyear) - return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, + return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, scal) class DateDisplaySR_Latin(DateDisplaySR_Base): @@ -348,23 +348,23 @@ class DateDisplaySR_Latin(DateDisplaySR_Base): short_months = ("", "jan", "feb", "mar", "apr", "maj", "jun", "jul", "avg", "sep", "okt", "nov", "dec" - ) + ) calendar = ( - "", "julijanski", "hebrejski", + "", "julijanski", "hebrejski", "francuski republikanski", "persijski", "islamski", - "švedski" + "švedski" ) _mod_str = ("", "pre ", "posle ", "oko ", "", "", "") _qual_str = ("", "procenjeno ", "izračunato ") - + _bce_str = "%s p.n.e." formats = ( - "GGGG-MM-DD (ISO-8601)", - "Numerički (DD.MM.GGGG.)", + "GGGG-MM-DD (ISO-8601)", + "Numerički (DD.MM.GGGG.)", "D. MMM GGGG.", "D. Mesec GGGG.", "D. Rb GGGG." @@ -390,23 +390,23 @@ class DateDisplaySR_Cyrillic(DateDisplaySR_Base): short_months = ("", "Јан", "Феб", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Нов", "Дец" - ) + ) calendar = ( - "", "Јулиан", "хебрејски", + "", "Јулиан", "хебрејски", "француски републиканац", "Персиан", "исламски", - "шведски" + "шведски" ) _mod_str = ("", "пре ", "после ", "око ", "", "", "") _qual_str = ("", "процењено ", "израчунато ") - + _bce_str = "%s п.н.е." formats = ( - "ГГГГ-ММ-ДД (ISO-8601)", - "Нумеричка (ДД.ММ.ГГГГ.)", + "ГГГГ-ММ-ДД (ISO-8601)", + "Нумеричка (ДД.ММ.ГГГГ.)", "Д. МММ ГГГГ.", "Д. Месец ГГГГ.", "Д. Rb ГГГГ." diff --git a/gramps/gen/datehandler/_date_sv.py b/gramps/gen/datehandler/_date_sv.py index 38b044ce1..d3e38cd5a 100644 --- a/gramps/gen/datehandler/_date_sv.py +++ b/gramps/gen/datehandler/_date_sv.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -48,56 +48,56 @@ from ._datehandler import register_datehandler class DateParserSv(DateParser): """ Convert a text string into a Date object, expecting a date - notation in the swedish language. If the date cannot be converted, + notation in the swedish language. If the date cannot be converted, the text string is assigned. """ # modifiers before the date modifier_to_int = { - 'före' : Date.MOD_BEFORE, - 'innan' : Date.MOD_BEFORE, - 'efter' : Date.MOD_AFTER, - 'omkring' : Date.MOD_ABOUT, - 'ca' : Date.MOD_ABOUT, + 'före' : Date.MOD_BEFORE, + 'innan' : Date.MOD_BEFORE, + 'efter' : Date.MOD_AFTER, + 'omkring' : Date.MOD_ABOUT, + 'ca' : Date.MOD_ABOUT, 'c:a' : Date.MOD_ABOUT } bce = ["f Kr"] calendar_to_int = { - 'gregoriansk ' : Date.CAL_GREGORIAN, - 'g' : Date.CAL_GREGORIAN, - 'juliansk' : Date.CAL_JULIAN, - 'j' : Date.CAL_JULIAN, - 'hebreisk' : Date.CAL_HEBREW, - 'h' : Date.CAL_HEBREW, - 'islamisk' : Date.CAL_ISLAMIC, - 'muslimsk' : Date.CAL_ISLAMIC, - 'i' : Date.CAL_ISLAMIC, - 'fransk' : Date.CAL_FRENCH, - 'fransk republikansk' : Date.CAL_FRENCH, - 'f' : Date.CAL_FRENCH, - 'persisk' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, - 'svensk' : Date.CAL_SWEDISH, - 's' : Date.CAL_SWEDISH, + 'gregoriansk ' : Date.CAL_GREGORIAN, + 'g' : Date.CAL_GREGORIAN, + 'juliansk' : Date.CAL_JULIAN, + 'j' : Date.CAL_JULIAN, + 'hebreisk' : Date.CAL_HEBREW, + 'h' : Date.CAL_HEBREW, + 'islamisk' : Date.CAL_ISLAMIC, + 'muslimsk' : Date.CAL_ISLAMIC, + 'i' : Date.CAL_ISLAMIC, + 'fransk' : Date.CAL_FRENCH, + 'fransk republikansk' : Date.CAL_FRENCH, + 'f' : Date.CAL_FRENCH, + 'persisk' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, + 'svensk' : Date.CAL_SWEDISH, + 's' : Date.CAL_SWEDISH, } - + quality_to_int = { - 'uppskattat' : Date.QUAL_ESTIMATED, - 'uppskattad' : Date.QUAL_ESTIMATED, - 'bedömt' : Date.QUAL_ESTIMATED, - 'bedömd' : Date.QUAL_ESTIMATED, - 'beräknat' : Date.QUAL_CALCULATED, - 'beräknad' : Date.QUAL_CALCULATED, + 'uppskattat' : Date.QUAL_ESTIMATED, + 'uppskattad' : Date.QUAL_ESTIMATED, + 'bedömt' : Date.QUAL_ESTIMATED, + 'bedömd' : Date.QUAL_ESTIMATED, + 'beräknat' : Date.QUAL_CALCULATED, + 'beräknad' : Date.QUAL_CALCULATED, } - + def init_strings(self): """ Define, in Swedish, span and range regular expressions""" DateParser.init_strings(self) - self._span = re.compile("(från)?\s*(?P.+)\s*(till|--|–)\s*(?P.+)", + self._span = re.compile("(från)?\s*(?P.+)\s*(till|--|–)\s*(?P.+)", re.IGNORECASE) - self._range = re.compile("(mellan)\s+(?P.+)\s+och\s+(?P.+)", + self._range = re.compile("(mellan)\s+(?P.+)\s+och\s+(?P.+)", re.IGNORECASE) #------------------------------------------------------------------------- @@ -107,40 +107,40 @@ class DateParserSv(DateParser): #------------------------------------------------------------------------- class DateDisplaySv(DateDisplay): """ - Swedish language date display class. + Swedish language date display class. """ - long_months = ( "", "januari", "februari", "mars", "april", "maj", - "juni", "juli", "augusti", "september", "oktober", + long_months = ( "", "januari", "februari", "mars", "april", "maj", + "juni", "juli", "augusti", "september", "oktober", "november", "december" ) - + short_months = ( "", "jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ) - + formats = ( - "ÅÅÅÅ-MM-DD (ISO)", - "År/mån/dag", - "Månad dag, år", - "MÅN DAG ÅR", - "Dag månad år", - "DAG MÅN ÅR", + "ÅÅÅÅ-MM-DD (ISO)", + "År/mån/dag", + "Månad dag, år", + "MÅN DAG ÅR", + "Dag månad år", + "DAG MÅN ÅR", ) # this must agree with DateDisplayEn's "formats" definition # (since no locale-specific _display_gregorian exists, here) calendar = ( - "", - "juliansk", - "hebreisk", - "fransk republikansk", - "persisk", - "islamisk", + "", + "juliansk", + "hebreisk", + "fransk republikansk", + "persisk", + "islamisk", "svensk" ) - + _mod_str = ("", "före ", "efter ", "c:a ", "", "", "") _qual_str = ("", "uppskattat ", "beräknat ") - + _bce_str = "%s f Kr" def display(self, date): @@ -168,12 +168,12 @@ class DateDisplaySv(DateDisplay): d1 = self.display_cal[cal](start) d2 = self.display_cal[cal](date.get_stop_date()) scal = self.format_extras(cal, newyear) - return "%smellan %s och %s%s" % (qual_str, d1, d2, + return "%smellan %s och %s%s" % (qual_str, d1, d2, scal) else: text = self.display_cal[date.get_calendar()](start) scal = self.format_extras(cal, newyear) - return "%s%s%s%s" % (qual_str, self._mod_str[mod], + return "%s%s%s%s" % (qual_str, self._mod_str[mod], text, scal) #------------------------------------------------------------------------- diff --git a/gramps/gen/datehandler/_date_zh_CN.py b/gramps/gen/datehandler/_date_zh_CN.py index b80e3723b..7159f90e0 100644 --- a/gramps/gen/datehandler/_date_zh_CN.py +++ b/gramps/gen/datehandler/_date_zh_CN.py @@ -52,7 +52,7 @@ class DateParserZH_CN(DateParser): Convert a text string into a Date object. If the date cannot be converted, the text string is assigned. """ - + # modifiers before the date modifier_to_int = { '以前' : Date.MOD_BEFORE, @@ -89,7 +89,7 @@ class DateParserZH_CN(DateParser): month_to_int["shí'èryuè"] = 12 month_to_int["假閏"] = 13 month_to_int["jiǎ rùn yùe"] = 13 - + calendar_to_int = { '阳历' : Date.CAL_GREGORIAN, 'g' : Date.CAL_GREGORIAN, @@ -102,16 +102,16 @@ class DateParserZH_CN(DateParser): '法国共和历' : Date.CAL_FRENCH, 'f' : Date.CAL_FRENCH, '伊郎历' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, '瑞典历' : Date.CAL_SWEDISH, 's' : Date.CAL_SWEDISH, } - + quality_to_int = { '据估计' : Date.QUAL_ESTIMATED, '据计算' : Date.QUAL_CALCULATED, } - + # FIXME translate these English strings into simplified-Chinese ones bce = ["before calendar", "negative year"] + DateParser.bce @@ -131,7 +131,7 @@ class DateParserZH_CN(DateParser): ('|'.join(_range_1), '|'.join(_range_2)), re.IGNORECASE) self._numeric = re.compile("((\d+)年\s*)?((\d+)月\s*)?(\d+)?日?\s*$") - + #------------------------------------------------------------------------- # # Simplified-Chinese display @@ -139,14 +139,14 @@ class DateParserZH_CN(DateParser): #------------------------------------------------------------------------- class DateDisplayZH_CN(DateDisplay): """ - Simplified-Chinese language date display class. + Simplified-Chinese language date display class. """ formats = ( "年年年年-月月-日日 (ISO)", "数字格式", ) # this definition must agree with its "_display_calendar" method - + # FIXME translate these English strings into simplified-Chinese ones _bce_str = "%s B.C.E." @@ -178,5 +178,5 @@ class DateDisplayZH_CN(DateDisplay): # #------------------------------------------------------------------------- -register_datehandler(('zh_CN', 'zh_SG', 'zh', 'chinese', 'Chinese'), +register_datehandler(('zh_CN', 'zh_SG', 'zh', 'chinese', 'Chinese'), DateParserZH_CN, DateDisplayZH_CN) diff --git a/gramps/gen/datehandler/_date_zh_TW.py b/gramps/gen/datehandler/_date_zh_TW.py index 07a2e8c49..cf1596fb4 100644 --- a/gramps/gen/datehandler/_date_zh_TW.py +++ b/gramps/gen/datehandler/_date_zh_TW.py @@ -52,7 +52,7 @@ class DateParserZH_TW(DateParser): Convert a text string into a Date object. If the date cannot be converted, the text string is assigned. """ - + # modifiers before the date modifier_to_int = { '以前' : Date.MOD_BEFORE, @@ -89,7 +89,7 @@ class DateParserZH_TW(DateParser): month_to_int["shí'èryuè"] = 12 month_to_int["假閏"] = 13 month_to_int["jiǎ rùn yùe"] = 13 - + calendar_to_int = { '陽曆' : Date.CAL_GREGORIAN, 'g' : Date.CAL_GREGORIAN, @@ -102,16 +102,16 @@ class DateParserZH_TW(DateParser): '法國共和歷' : Date.CAL_FRENCH, 'f' : Date.CAL_FRENCH, '伊郎歷' : Date.CAL_PERSIAN, - 'p' : Date.CAL_PERSIAN, + 'p' : Date.CAL_PERSIAN, '瑞典歷' : Date.CAL_SWEDISH, 's' : Date.CAL_SWEDISH, } - + quality_to_int = { '據估計' : Date.QUAL_ESTIMATED, '據計算' : Date.QUAL_CALCULATED, } - + # FIXME translate these English strings into traditional-Chinese ones bce = ["before calendar", "negative year"] + DateParser.bce @@ -131,7 +131,7 @@ class DateParserZH_TW(DateParser): ('|'.join(_range_1), '|'.join(_range_2)), re.IGNORECASE) self._numeric = re.compile("((\d+)年\s*)?((\d+)月\s*)?(\d+)?日?\s*$") - + #------------------------------------------------------------------------- # # Traditional-Chinese display @@ -139,14 +139,14 @@ class DateParserZH_TW(DateParser): #------------------------------------------------------------------------- class DateDisplayZH_TW(DateDisplay): """ - Traditional-Chinese language date display class. + Traditional-Chinese language date display class. """ formats = ( "年年年年-月月-日日 (ISO)", "數字格式", ) # this definition must agree with its "_display_calendar" method - + # FIXME translate these English strings into traditional-Chinese ones _bce_str = "%s B.C.E." @@ -178,5 +178,5 @@ class DateDisplayZH_TW(DateDisplay): # #------------------------------------------------------------------------- -register_datehandler(('zh_TW', 'zh_HK'), +register_datehandler(('zh_TW', 'zh_HK'), DateParserZH_TW, DateDisplayZH_TW) diff --git a/gramps/gen/datehandler/_datedisplay.py b/gramps/gen/datehandler/_datedisplay.py index f84f4f0f1..636de3074 100644 --- a/gramps/gen/datehandler/_datedisplay.py +++ b/gramps/gen/datehandler/_datedisplay.py @@ -1,4 +1,4 @@ -# -*- coding: utf-8 -*- +# -*- coding: utf-8 -*- # # Gramps - a GTK+/GNOME based genealogy program # @@ -51,7 +51,7 @@ from ._datestrings import DateStrings #------------------------------------------------------------------------- class DateDisplay(object): """ - Base date display class. + Base date display class. """ _locale = GrampsLocale(lang='en_US', languages='en') @@ -60,23 +60,23 @@ class DateDisplay(object): _ = _grampslocale.glocale.translation.sgettext formats = ( # format 0 - must always be ISO - _("YYYY-MM-DD (ISO)"), + _("YYYY-MM-DD (ISO)"), # format # 1 - must always be locale-preferred numerical format # such as YY.MM.DD, MM-DD-YY, or whatever your locale prefers. - # This should be the format that is used under the locale by + # This should be the format that is used under the locale by # strftime() for '%x'. # You may translate this as "Numerical", "System preferred", or similar. - _("date format|Numerical"), + _("date format|Numerical"), # Full month name, day, year - _("Month Day, Year"), + _("Month Day, Year"), # Abbreviated month name, day, year - _("MON DAY, YEAR"), + _("MON DAY, YEAR"), # Day, full month name, year - _("Day Month Year"), + _("Day Month Year"), # Day, abbreviated month name, year _("DAY MON YEAR") @@ -84,7 +84,7 @@ class DateDisplay(object): """ .. note:: Will be overridden if a locale-specific date displayer exists. - If your localized :meth:`~_display_calendar`/:meth:`~_display_gregorian` + If your localized :meth:`~_display_calendar`/:meth:`~_display_gregorian` are overridden, you should override the whole formats list according to your own formats, and you need not localize the format names here. This ``formats`` must agree with @@ -93,7 +93,7 @@ class DateDisplay(object): del _ newyear = ("", "Mar1", "Mar25", "Sep1") - + _bce_str = "%s B.C.E." # this will be overridden if a locale-specific date displayer exists @@ -110,12 +110,12 @@ class DateDisplay(object): self.persian = self._ds.persian self.islamic = self._ds.islamic self.display_cal = [ - self._display_gregorian, - self._display_julian, - self._display_hebrew, - self._display_french, - self._display_persian, - self._display_islamic, + self._display_gregorian, + self._display_julian, + self._display_hebrew, + self._display_french, + self._display_persian, + self._display_islamic, self._display_swedish] self._mod_str = self._ds.modifiers self._qual_str = self._ds.qualifiers @@ -129,7 +129,7 @@ class DateDisplay(object): self._ = _ = self._locale.translation.sgettext self.FORMATS_long_month_year = { # Inflection control due to modifier. -# Protocol: DateDisplayXX passes a key to the dictionary in the +# Protocol: DateDisplayXX passes a key to the dictionary in the # parameter ``inflect`` to ``_display_calendar``. # The modifier passed is not necessarily the one printed, it's just # a representative that induces the same inflection control. @@ -137,7 +137,7 @@ class DateDisplay(object): # all require genitive form for May, whereas no modifier (just "May 1234") # require nominative, so DateDisplayRU.display will pass "before" # in all 3 cases, collapsing the 3 modifiers into 1. -# +# # Another example in Russian is that "between April 1234 and June 1235" # requires the same inflection for both April and June, so just "between" # is used by DateDisplayRU.display, collapsing two more modifiers into 1. @@ -231,7 +231,7 @@ class DateDisplay(object): "" : _("{short_month} {year}"), - "from" + "from" # first date in a span # If "from " needs a special inflection in your # language, translate this to "{short_month.f[X]} {year}" @@ -239,7 +239,7 @@ class DateDisplay(object): # else leave it untranslated : _("from|{short_month} {year}"), - "to" + "to" # second date in a span # If "to " needs a special inflection in your # language, translate this to "{short_month.f[X]} {year}" @@ -247,7 +247,7 @@ class DateDisplay(object): # else leave it untranslated : _("to|{short_month} {year}"), - "between" + "between" # first date in a range # If "between " needs a special inflection in your # language, translate this to "{short_month.f[X]} {year}" @@ -255,7 +255,7 @@ class DateDisplay(object): # else leave it untranslated : _("between|{short_month} {year}"), - "and" + "and" # second date in a range # If "and " needs a special inflection in your # language, translate this to "{short_month.f[X]} {year}" @@ -263,21 +263,21 @@ class DateDisplay(object): # else leave it untranslated : _("and|{short_month} {year}"), - "before" + "before" # If "before " needs a special inflection in your # language, translate this to "{short_month.f[X]} {year}" # (where X is one of the month-name inflections you defined) # else leave it untranslated : _("before|{short_month} {year}"), - "after" + "after" # If "after " needs a special inflection in your # language, translate this to "{short_month.f[X]} {year}" # (where X is one of the month-name inflections you defined) # else leave it untranslated : _("after|{short_month} {year}"), - "about" + "about" # If "about " needs a special inflection in your # language, translate this to "{short_month.f[X]} {year}" # (where X is one of the month-name inflections you defined) @@ -338,7 +338,7 @@ class DateDisplay(object): newyear = date.get_new_year() qual_str = self._qual_str[qual] - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -356,7 +356,7 @@ class DateDisplay(object): def _slash_year(self, val, slash): if val < 0: val = - val - + if slash: if (val-1) % 100 == 99: year = "%d/%d" % (val - 1, (val%1000)) @@ -366,9 +366,9 @@ class DateDisplay(object): year = "%d/%d" % (val - 1, (val%10)) else: year = "%d" % (val) - + return year - + def display_iso(self, date_val): # YYYY-MM-DD (ISO) year = self._slash_year(date_val[2], date_val[3]) @@ -391,21 +391,21 @@ class DateDisplay(object): cal = date.get_calendar() qual_str = self._qual_str[date.get_quality()] scal = self.format_extras(cal, date.get_new_year()) - d1 = self.display_cal[cal](date.get_start_date(), + d1 = self.display_cal[cal](date.get_start_date(), # If there is no special inflection for "from " # in your language, DON'T translate this string. Otherwise, # "translate" this to "from" in ENGLISH!!! ENGLISH!!! inflect=self._("from-date|")) - d2 = self.display_cal[cal](date.get_stop_date(), + d2 = self.display_cal[cal](date.get_stop_date(), # If there is no special inflection for "to " # in your language, DON'T translate this string. Otherwise, # "translate" this to "to" in ENGLISH!!! ENGLISH!!! inflect=self._("to-date|")) return self._("{date_quality}from {date_start} to {date_stop}" "{nonstd_calendar_and_ny}").format( - date_quality=qual_str, - date_start=d1, - date_stop=d2, + date_quality=qual_str, + date_start=d1, + date_stop=d2, nonstd_calendar_and_ny=scal) def dd_range(self, date): @@ -428,9 +428,9 @@ class DateDisplay(object): inflect=self._("and-date|")) return self._("{date_quality}between {date_start} and {date_stop}" "{nonstd_calendar_and_ny}").format( - date_quality=qual_str, - date_start=d1, - date_stop=d2, + date_quality=qual_str, + date_start=d1, + date_stop=d2, nonstd_calendar_and_ny=scal) def display_formatted(self, date): @@ -445,7 +445,7 @@ class DateDisplay(object): qual_str = self._qual_str[qual] _ = self._ - + if mod == Date.MOD_TEXTONLY: return date.get_text() elif start == Date.EMPTY: @@ -500,13 +500,13 @@ class DateDisplay(object): scal = self.format_extras(cal, newyear) return _("{date_quality}{noncompound_modifier}{date}" "{nonstd_calendar_and_ny}").format( - date_quality=qual_str, + date_quality=qual_str, noncompound_modifier=modifier, - date=text, + date=text, nonstd_calendar_and_ny=scal) def _display_gregorian(self, date_val, **kwargs): - return self._display_calendar(date_val, self.long_months, + return self._display_calendar(date_val, self.long_months, self.short_months, **kwargs) # Julian and Swedish date display is the same as Gregorian @@ -713,7 +713,7 @@ class DateDisplay(object): class DateDisplayEn(DateDisplay): """ - English language date display class. + English language date display class. """ diff --git a/gramps/gen/datehandler/_datehandler.py b/gramps/gen/datehandler/_datehandler.py index 30e477aa2..95dc3b1fc 100644 --- a/gramps/gen/datehandler/_datehandler.py +++ b/gramps/gen/datehandler/_datehandler.py @@ -50,16 +50,16 @@ from gramps.gen.utils.grampslocale import GrampsLocale #------------------------------------------------------------------------- # -# Constants +# Constants # #------------------------------------------------------------------------- LANG = glocale.calendar # If LANG contains ".UTF-8" use only the part to the left of "." -# Otherwise some date handler will not load. +# Otherwise some date handler will not load. if LANG and ".UTF-8" in LANG.upper(): LANG = LANG.split(".")[0] - + if not LANG: if "LANG" in os.environ: LANG = os.environ["LANG"] diff --git a/gramps/gen/datehandler/_dateparser.py b/gramps/gen/datehandler/_dateparser.py index 104ce1872..02670fb52 100644 --- a/gramps/gen/datehandler/_dateparser.py +++ b/gramps/gen/datehandler/_dateparser.py @@ -115,7 +115,7 @@ def french_valid(date_tuple): valid = True # year 1 starts on 22.9.1792 if date_tuple[2] < 1: - valid = False + valid = False return valid def _build_prefix_table(month_to_int, month_variants): @@ -193,7 +193,7 @@ class DateParser(object): """ _locale = GrampsLocale(lang='en', languages='en') - + _fmt_parse = re.compile(".*%(\S).*%(\S).*%(\S).*") # RFC-2822 only uses capitalized English abbreviated names, no locales. @@ -234,7 +234,7 @@ class DateParser(object): #alternative spelling "cheshvan": 2, "adar sheni": 7, "iyar" : 9, #GEDCOM months - "tsh" : 1, "csh": 5, "ksl": 3, "tvt": 4, "shv": 5, "adr": 6, + "tsh" : 1, "csh": 5, "ksl": 3, "tvt": 4, "shv": 5, "adr": 6, "ads" : 7, "nsn": 8, "iyr": 9, "svn":10, "tmz":11, "aav":12, "ell":13, } @@ -285,10 +285,10 @@ class DateParser(object): newyear_to_int = { "jan1": Date.NEWYEAR_JAN1, "mar1": Date.NEWYEAR_MAR1, - "mar25": Date.NEWYEAR_MAR25, + "mar25": Date.NEWYEAR_MAR25, "sep1" : Date.NEWYEAR_SEP1, } - + quality_to_int = { 'estimated' : Date.QUAL_ESTIMATED, 'est.' : Date.QUAL_ESTIMATED, @@ -305,7 +305,7 @@ class DateParser(object): # see init_strings, so there is no need to override this if you have no aliases # for "today". # We also secretly support "$T" like in some reports. - + _langs = set() def __init_prefix_tables(self): lang = self._locale.lang @@ -316,9 +316,9 @@ class DateParser(object): DateParser._langs.add(lang) ds = DateStrings(self._locale) log.debug("Begin building parser prefix tables for {}".format(lang)) - _build_prefix_table(DateParser.month_to_int, + _build_prefix_table(DateParser.month_to_int, _generate_variants( - zip(ds.long_months, ds.short_months, + zip(ds.long_months, ds.short_months, ds.swedish_SV, ds.alt_long_months))) _build_prefix_table(DateParser.hebrew_to_int, _generate_variants(zip(ds.hebrew))) @@ -367,14 +367,14 @@ class DateParser(object): def init_strings(self): """ This method compiles regular expression strings for matching dates. - + Most of the re's in most languages can stay as is. span and range most likely will need to change. Whatever change is done, this method may be called first as DateParser.init_strings(self) so that the invariant expresions don't need to be repeteadly coded. All differences can be coded after DateParser.init_strings(self) call, that way they override stuff from this method. - + .. seealso:: :class:`.DateParserRU` as an example. """ _ = self._locale.translation.gettext @@ -419,7 +419,7 @@ class DateParser(object): self._qual = re.compile("(.* ?)%s\s+(.+)" % self._qual_str, re.IGNORECASE) - + self._span = re.compile("(from)\s+(?P.+)\s+to\s+(?P.+)", re.IGNORECASE) self._range = re.compile("(bet|bet.|between)\s+(?P.+)\s+and\s+(?P.+)", @@ -456,7 +456,7 @@ class DateParser(object): self._numeric = re.compile("((\d+)[/\.]\s*)?((\d+)[/\.]\s*)?(\d+)\s*$") self._iso = re.compile("(\d+)(/(\d+))?-(\d+)-(\d+)\s*$") self._isotimestamp = re.compile("^\s*?(\d{4})([01]\d)([0123]\d)(?:(?:[012]\d[0-5]\d[0-5]\d)|(?:\s+[012]\d:[0-5]\d(?::[0-5]\d)?))?\s*?$") - self._rfc = re.compile("(%s,)?\s+(\d|\d\d)\s+%s\s+(\d+)\s+\d\d:\d\d(:\d\d)?\s+(\+|-)\d\d\d\d" + self._rfc = re.compile("(%s,)?\s+(\d|\d\d)\s+%s\s+(\d+)\s+\d\d:\d\d(:\d\d)?\s+(\+|-)\d\d\d\d" % (self._rfc_day_str, self._rfc_mon_str)) self._today = re.compile("^\s*%s\s*$" % self._today_str, re.IGNORECASE) @@ -498,7 +498,7 @@ class DateParser(object): return self._parse_calendar(text, self._stext, self._stext2, self.swedish_to_int,swedish_valid) - + def _parse_calendar(self, text, regex1, regex2, mmap, check=None): match = regex1.match(text.lower()) if match: @@ -564,9 +564,9 @@ class DateParser(object): if check and not check((d, m, y)): value = Date.EMPTY return value - + return Date.EMPTY - + def _parse_subdate(self, text, subparser=None, cal=None): """ Convert only the date portion of a date. @@ -676,7 +676,7 @@ class DateParser(object): def match_calendar(self, text, cal): """ Try parsing calendar. - + Return calendar index and the text with calendar removed. """ match = self._cal.match(text) @@ -688,7 +688,7 @@ class DateParser(object): def match_calendar_newyear(self, text, cal, newyear): """ Try parsing calendar and newyear code. - + Return newyear index and the text with calendar removed. """ match = self._calny.match(text) @@ -707,7 +707,7 @@ class DateParser(object): def match_newyear(self, text, newyear): """ Try parsing calendar and newyear code. - + Return newyear index and the text with calendar removed. """ match = self._ny.match(text) @@ -724,7 +724,7 @@ class DateParser(object): def match_quality(self, text, qual): """ Try matching quality. - + Return quality index and the text with quality removed. """ match = self._qual.match(text) @@ -736,7 +736,7 @@ class DateParser(object): def match_span(self, text, cal, ny, qual, date): """ Try matching span date. - + On success, set the date and return 1. On failure return 0. """ match = self._span.match(text) @@ -763,7 +763,7 @@ class DateParser(object): def match_range(self, text, cal, ny, qual, date): """ Try matching range date. - + On success, set the date and return 1. On failure return 0. """ match = self._range.match(text) @@ -782,7 +782,7 @@ class DateParser(object): return 0 if bc2: stop = self.invert_year(stop) - + date.set(qual, Date.MOD_RANGE, cal, start + stop, newyear=ny) return 1 return 0 @@ -790,7 +790,7 @@ class DateParser(object): def match_bce(self, text): """ Try matching BCE qualifier. - + Return BCE (True/False) and the text with matched part removed. """ match = self._bce_re.match(text) @@ -807,7 +807,7 @@ class DateParser(object): def match_modifier(self, text, cal, ny, qual, bc, date): """ Try matching date with modifier. - + On success, set the date and return 1. On failure return 0. """ # modifiers before the date @@ -864,7 +864,7 @@ class DateParser(object): qual = Date.QUAL_NONE cal = Date.CAL_GREGORIAN newyear = Date.NEWYEAR_JAN1 - + (text, cal, newyear) = self.match_calendar_newyear(text, cal, newyear) (text, newyear) = self.match_newyear(text, newyear) (text, cal) = self.match_calendar(text, cal) @@ -897,7 +897,7 @@ class DateParser(object): def invert_year(self, subdate): return (subdate[0], subdate[1], -subdate[2], subdate[3]) - + def parse(self, text): """ Parses the text, returning a :class:`.Date` object. diff --git a/gramps/gen/datehandler/_datestrings.py b/gramps/gen/datehandler/_datestrings.py index a94a709b7..09377dc38 100644 --- a/gramps/gen/datehandler/_datestrings.py +++ b/gramps/gen/datehandler/_datestrings.py @@ -1,4 +1,4 @@ -# -*- coding: utf-8 -*- +# -*- coding: utf-8 -*- # # Gramps - a GTK+/GNOME based genealogy program # @@ -56,7 +56,7 @@ class DateStrings(object): String tables for :class:`.DateDisplay` and :class:`.DateParser`. """ - # This table needs not be localized, it's only for parsing + # This table needs not be localized, it's only for parsing # Swedish calendar dates using Swedish month names. # Display of these months uses the regular long_months. # TODO should we pack these into alt_long_months instead? @@ -72,171 +72,171 @@ class DateStrings(object): _ = locale.translation.lexgettext self.long_months = ( "", - # TRANSLATORS: see + # TRANSLATORS: see # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates # to learn how to select proper inflection to be used in your localized # DateDisplayer code! - _("localized lexeme inflections||January"), - _("localized lexeme inflections||February"), - _("localized lexeme inflections||March"), - _("localized lexeme inflections||April"), - _("localized lexeme inflections||May"), - _("localized lexeme inflections||June"), - _("localized lexeme inflections||July"), - _("localized lexeme inflections||August"), - _("localized lexeme inflections||September"), - _("localized lexeme inflections||October"), - _("localized lexeme inflections||November"), + _("localized lexeme inflections||January"), + _("localized lexeme inflections||February"), + _("localized lexeme inflections||March"), + _("localized lexeme inflections||April"), + _("localized lexeme inflections||May"), + _("localized lexeme inflections||June"), + _("localized lexeme inflections||July"), + _("localized lexeme inflections||August"), + _("localized lexeme inflections||September"), + _("localized lexeme inflections||October"), + _("localized lexeme inflections||November"), _("localized lexeme inflections||December") ) self.short_months = ( "", - # TRANSLATORS: see + # TRANSLATORS: see # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates # to learn how to select proper inflection to be used in your localized # DateDisplayer code! - _("localized lexeme inflections - short month form||Jan"), - _("localized lexeme inflections - short month form||Feb"), - _("localized lexeme inflections - short month form||Mar"), - _("localized lexeme inflections - short month form||Apr"), - _("localized lexeme inflections - short month form||May"), - _("localized lexeme inflections - short month form||Jun"), - _("localized lexeme inflections - short month form||Jul"), - _("localized lexeme inflections - short month form||Aug"), - _("localized lexeme inflections - short month form||Sep"), - _("localized lexeme inflections - short month form||Oct"), - _("localized lexeme inflections - short month form||Nov"), + _("localized lexeme inflections - short month form||Jan"), + _("localized lexeme inflections - short month form||Feb"), + _("localized lexeme inflections - short month form||Mar"), + _("localized lexeme inflections - short month form||Apr"), + _("localized lexeme inflections - short month form||May"), + _("localized lexeme inflections - short month form||Jun"), + _("localized lexeme inflections - short month form||Jul"), + _("localized lexeme inflections - short month form||Aug"), + _("localized lexeme inflections - short month form||Sep"), + _("localized lexeme inflections - short month form||Oct"), + _("localized lexeme inflections - short month form||Nov"), _("localized lexeme inflections - short month form||Dec") ) _ = locale.translation.sgettext self.alt_long_months = ( "", - # TRANSLATORS: see + # TRANSLATORS: see # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates # to learn how to add proper alternatives to be recognized in your localized # DateParser code! - _("alternative month names for January||"), - _("alternative month names for February||"), - _("alternative month names for March||"), - _("alternative month names for April||"), - _("alternative month names for May||"), - _("alternative month names for June||"), - _("alternative month names for July||"), - _("alternative month names for August||"), - _("alternative month names for September||"), - _("alternative month names for October||"), - _("alternative month names for November||"), + _("alternative month names for January||"), + _("alternative month names for February||"), + _("alternative month names for March||"), + _("alternative month names for April||"), + _("alternative month names for May||"), + _("alternative month names for June||"), + _("alternative month names for July||"), + _("alternative month names for August||"), + _("alternative month names for September||"), + _("alternative month names for October||"), + _("alternative month names for November||"), _("alternative month names for December||") ) self.calendar = ( # Must appear in the order indexed by Date.CAL_... numeric constants - _("calendar|Gregorian"), - _("calendar|Julian"), - _("calendar|Hebrew"), - _("calendar|French Republican"), - _("calendar|Persian"), + _("calendar|Gregorian"), + _("calendar|Julian"), + _("calendar|Hebrew"), + _("calendar|French Republican"), + _("calendar|Persian"), _("calendar|Islamic"), _("calendar|Swedish") ) _ = locale.translation.lexgettext self.hebrew = ( - "", - # TRANSLATORS: see + "", + # TRANSLATORS: see # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates # to learn how to select proper inflection to be used in your localized # DateDisplayer code! - _("Hebrew month lexeme|Tishri"), - _("Hebrew month lexeme|Heshvan"), - _("Hebrew month lexeme|Kislev"), - _("Hebrew month lexeme|Tevet"), - _("Hebrew month lexeme|Shevat"), - _("Hebrew month lexeme|AdarI"), - _("Hebrew month lexeme|AdarII"), - _("Hebrew month lexeme|Nisan"), - _("Hebrew month lexeme|Iyyar"), - _("Hebrew month lexeme|Sivan"), - _("Hebrew month lexeme|Tammuz"), - _("Hebrew month lexeme|Av"), + _("Hebrew month lexeme|Tishri"), + _("Hebrew month lexeme|Heshvan"), + _("Hebrew month lexeme|Kislev"), + _("Hebrew month lexeme|Tevet"), + _("Hebrew month lexeme|Shevat"), + _("Hebrew month lexeme|AdarI"), + _("Hebrew month lexeme|AdarII"), + _("Hebrew month lexeme|Nisan"), + _("Hebrew month lexeme|Iyyar"), + _("Hebrew month lexeme|Sivan"), + _("Hebrew month lexeme|Tammuz"), + _("Hebrew month lexeme|Av"), _("Hebrew month lexeme|Elul") ) self.french = ( - "", - # TRANSLATORS: see + "", + # TRANSLATORS: see # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates # to learn how to select proper inflection to be used in your localized # DateDisplayer code! - _("French month lexeme|Vendémiaire"), - _("French month lexeme|Brumaire"), - _("French month lexeme|Frimaire"), - _("French month lexeme|Nivôse"), - _("French month lexeme|Pluviôse"), - _("French month lexeme|Ventôse"), - _("French month lexeme|Germinal"), - _("French month lexeme|Floréal"), - _("French month lexeme|Prairial"), - _("French month lexeme|Messidor"), - _("French month lexeme|Thermidor"), - _("French month lexeme|Fructidor"), - _("French month lexeme|Extra"), + _("French month lexeme|Vendémiaire"), + _("French month lexeme|Brumaire"), + _("French month lexeme|Frimaire"), + _("French month lexeme|Nivôse"), + _("French month lexeme|Pluviôse"), + _("French month lexeme|Ventôse"), + _("French month lexeme|Germinal"), + _("French month lexeme|Floréal"), + _("French month lexeme|Prairial"), + _("French month lexeme|Messidor"), + _("French month lexeme|Thermidor"), + _("French month lexeme|Fructidor"), + _("French month lexeme|Extra"), ) self.islamic = ( - "", - # TRANSLATORS: see + "", + # TRANSLATORS: see # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates # to learn how to select proper inflection to be used in your localized # DateDisplayer code! - _("Islamic month lexeme|Muharram"), - _("Islamic month lexeme|Safar"), - _("Islamic month lexeme|Rabi`al-Awwal"), - _("Islamic month lexeme|Rabi`ath-Thani"), - _("Islamic month lexeme|Jumada l-Ula"), - _("Islamic month lexeme|Jumada t-Tania"), - _("Islamic month lexeme|Rajab"), - _("Islamic month lexeme|Sha`ban"), - _("Islamic month lexeme|Ramadan"), - _("Islamic month lexeme|Shawwal"), - _("Islamic month lexeme|Dhu l-Qa`da"), + _("Islamic month lexeme|Muharram"), + _("Islamic month lexeme|Safar"), + _("Islamic month lexeme|Rabi`al-Awwal"), + _("Islamic month lexeme|Rabi`ath-Thani"), + _("Islamic month lexeme|Jumada l-Ula"), + _("Islamic month lexeme|Jumada t-Tania"), + _("Islamic month lexeme|Rajab"), + _("Islamic month lexeme|Sha`ban"), + _("Islamic month lexeme|Ramadan"), + _("Islamic month lexeme|Shawwal"), + _("Islamic month lexeme|Dhu l-Qa`da"), _("Islamic month lexeme|Dhu l-Hijja"), ) self.persian = ( - "", - # TRANSLATORS: see + "", + # TRANSLATORS: see # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates # to learn how to select proper inflection to be used in your localized # DateDisplayer code! - _("Persian month lexeme|Farvardin"), - _("Persian month lexeme|Ordibehesht"), - _("Persian month lexeme|Khordad"), - _("Persian month lexeme|Tir"), - _("Persian month lexeme|Mordad"), - _("Persian month lexeme|Shahrivar"), - _("Persian month lexeme|Mehr"), - _("Persian month lexeme|Aban"), - _("Persian month lexeme|Azar"), - _("Persian month lexeme|Dey"), - _("Persian month lexeme|Bahman"), + _("Persian month lexeme|Farvardin"), + _("Persian month lexeme|Ordibehesht"), + _("Persian month lexeme|Khordad"), + _("Persian month lexeme|Tir"), + _("Persian month lexeme|Mordad"), + _("Persian month lexeme|Shahrivar"), + _("Persian month lexeme|Mehr"), + _("Persian month lexeme|Aban"), + _("Persian month lexeme|Azar"), + _("Persian month lexeme|Dey"), + _("Persian month lexeme|Bahman"), _("Persian month lexeme|Esfand"), ) - self.modifiers = ("", + self.modifiers = ("", # TRANSLATORS: if the modifier is after the date # put the space ahead of the word instead of after it - _("date modifier|before "), + _("date modifier|before "), # TRANSLATORS: if the modifier is after the date # put the space ahead of the word instead of after it - _("date modifier|after "), + _("date modifier|after "), # TRANSLATORS: if the modifier is after the date # put the space ahead of the word instead of after it - _("date modifier|about "), + _("date modifier|about "), "", "", "") - self.qualifiers = ("", - _("date quality|estimated "), - _("date quality|calculated "), + self.qualifiers = ("", + _("date quality|estimated "), + _("date quality|calculated "), ) - # 6753: localized day names. Eventually should sprout into + # 6753: localized day names. Eventually should sprout into # a per-calendar type thing instead. self.long_days = ("", _("Sunday"), @@ -252,7 +252,7 @@ if __name__ == '__main__': import sys from ..utils.grampslocale import GrampsLocale from gramps.gen.const import GRAMPS_LOCALE as glocale - from ._grampslocale import (_deprecated_long_months as old_long, + from ._grampslocale import (_deprecated_long_months as old_long, _deprecated_short_months as old_short, _deprecated_long_days as old_days) from ._datedisplay import DateDisplay @@ -261,11 +261,11 @@ if __name__ == '__main__': lang_short = lang[:2] available_langs = glocale.get_available_translations() if glocale.check_available_translations(lang) is None: - print ("Translation for current language {lang} not available.\n" + print ("Translation for current language {lang} not available.\n" "Available translations: {list}.\n" "Does po/{lang_short}*.po exist in gramps source tree?!\n" "Please set your LANG / LC_ALL environment to something else...\n".format( - lang=lang, list=available_langs, lang_short=lang_short), + lang=lang, list=available_langs, lang_short=lang_short), file=sys.stderr) sys.exit(1) diff --git a/gramps/gen/datehandler/_dateutils.py b/gramps/gen/datehandler/_dateutils.py index e35cac004..97f5f21a1 100644 --- a/gramps/gen/datehandler/_dateutils.py +++ b/gramps/gen/datehandler/_dateutils.py @@ -60,9 +60,9 @@ def set_format(value): def set_date(date_base, text) : """ Set the date of the :class:`.DateBase` instance. - + The date is parsed into a :class:`.Date` instance. - + :param date_base: The :class:`.DateBase` instance to set the date to. :type date_base: :class:`.DateBase` :param text: The text to use for the text string in date @@ -74,7 +74,7 @@ def get_date(date_base) : """ Return a string representation of the date of the :class:`.DateBase` instance. - + This representation is based off the default date display format determined by the locale's :class:`.DateDisplay` instance. diff --git a/gramps/gen/datehandler/_grampslocale.py b/gramps/gen/datehandler/_grampslocale.py index c62e29d65..4af0c5c82 100644 --- a/gramps/gen/datehandler/_grampslocale.py +++ b/gramps/gen/datehandler/_grampslocale.py @@ -1,4 +1,4 @@ -# -*- coding: iso-8859-1 -*- +# -*- coding: iso-8859-1 -*- # # Gramps - a GTK+/GNOME based genealogy program # @@ -99,9 +99,9 @@ try: ) tformat = locale.nl_langinfo(locale.D_FMT).replace('%y','%Y') - # GRAMPS treats dates with '-' as ISO format, so replace separator on + # GRAMPS treats dates with '-' as ISO format, so replace separator on # locale dates that use '-' to prevent confict - tformat = tformat.replace('-', '/') + tformat = tformat.replace('-', '/') except: import time @@ -169,18 +169,18 @@ except: time.strftime('%a',(1,1,1,1,1,1,5,1,1)), # Saturday ) - # depending on the locale, the value returned for 20th Feb 2009 could be - # of the format '20/2/2009', '20/02/2009', '20.2.2009', '20.02.2009', - # '20-2-2009', '20-02-2009', '2009/02/20', '2009.02.20', '2009-02-20', - # '09-02-20' hence to reduce the possible values to test, make sure month + # depending on the locale, the value returned for 20th Feb 2009 could be + # of the format '20/2/2009', '20/02/2009', '20.2.2009', '20.02.2009', + # '20-2-2009', '20-02-2009', '2009/02/20', '2009.02.20', '2009-02-20', + # '09-02-20' hence to reduce the possible values to test, make sure month # is double digit also day should be double digit, preferably greater than # 12 for human readablity - timestr = time.strftime('%x',(2005,10,25,1,1,1,1,1,1)) - - # GRAMPS treats dates with '-' as ISO format, so replace separator on + timestr = time.strftime('%x',(2005,10,25,1,1,1,1,1,1)) + + # GRAMPS treats dates with '-' as ISO format, so replace separator on # locale dates that use '-' to prevent confict - timestr = timestr.replace('-', '/') + timestr = timestr.replace('-', '/') time2fmt_map = { '25/10/2005' : '%d/%m/%Y', '10/25/2005' : '%m/%d/%Y', @@ -189,7 +189,7 @@ except: '10.25.2005' : '%m.%d.%Y', '2005.10.25' : '%Y.%m.%d', } - + try: tformat = time2fmt_map[timestr] except KeyError as e: diff --git a/gramps/gen/datehandler/test/datedisplay_test.py b/gramps/gen/datehandler/test/datedisplay_test.py index 597dfe856..1581242e7 100644 --- a/gramps/gen/datehandler/test/datedisplay_test.py +++ b/gramps/gen/datehandler/test/datedisplay_test.py @@ -56,14 +56,14 @@ class DateDisplayInflectionsTestRU(DateDisplayTest): self.dd = self.display = self.display_RU self.months = self.dd._ds.long_months # TODO hardwired magic numbers! Bad API smell. - self.dd.set_format(4) # day month_name year + self.dd.set_format(4) # day month_name year self.may = self.months[5] def assertInflectionInDate(self, inflection, date, month=None): if month is None: month = date.get_month() month_lexeme = self.months[month] - self.assertIn(month_lexeme.f[inflection], + self.assertIn(month_lexeme.f[inflection], self.dd.display(date)) def test_month_only_date_nominative(self): @@ -85,11 +85,11 @@ class DateDisplayInflectionsTestRU(DateDisplayTest): # this depends on the fact that in Russian the short and long forms for May # will be the same! self.assertIn("до мая", self.dd.display(d1945may)) - + def test_between_month_only_dates_ablative(self): b1945may_1946may = Date() b1945may_1946may.set( - modifier=Date.MOD_RANGE, + modifier=Date.MOD_RANGE, value=(0, 5, 1945, False, 0, 5, 1946, False)) # TODO hardwired magic numbers! Bad API smell. for inflecting_format in (3,4): @@ -102,7 +102,7 @@ class DateDisplayInflectionsTestRU(DateDisplayTest): def test_month_only_date_span_from_genitive_to_accusative(self): f1945may_t1946may = Date() f1945may_t1946may.set( - modifier=Date.MOD_SPAN, + modifier=Date.MOD_SPAN, value=(0, 5, 1945, False, 0, 5, 1946, False)) # TODO hardwired magic numbers! Bad API smell. for inflecting_format in (3,4): diff --git a/gramps/gen/datehandler/test/datehandler_test.py b/gramps/gen/datehandler/test/datehandler_test.py index 8fb5a1d85..424939f79 100644 --- a/gramps/gen/datehandler/test/datehandler_test.py +++ b/gramps/gen/datehandler/test/datehandler_test.py @@ -66,7 +66,7 @@ class DateHandlerTest(unittest.TestCase): test_date.to_struct(), new_date.to_struct())) def test_simple(self): - + dates = [] for calendar in (Date.CAL_GREGORIAN, Date.CAL_JULIAN): for newyear in (Date.NEWYEAR_JAN1, Date.NEWYEAR_MAR25, (5,5)): @@ -78,8 +78,8 @@ class DateHandlerTest(unittest.TestCase): for month in range(1, 13): for day in (5, 27): d = Date() - d.set(quality, modifier, calendar, - (day, month, 1789, slash1), + d.set(quality, modifier, calendar, + (day, month, 1789, slash1), "Text comment", newyear) dates.append(d) @@ -99,26 +99,26 @@ class DateHandlerTest(unittest.TestCase): for month in range(1, 13): for day in (5, 27): d = Date() - d.set(quality, modifier, calendar, - (day, month, 1789, slash1, + d.set(quality, modifier, calendar, + (day, month, 1789, slash1, day, month, 1876, slash2), "Text comment") dates.append(d) d = Date() - d.set(quality, modifier, calendar, - (day, month, 1789, slash1, + d.set(quality, modifier, calendar, + (day, month, 1789, slash1, day, 13-month, 1876, slash2), "Text comment") dates.append(d) d = Date() - d.set(quality, modifier, calendar, - (day, month, 1789, slash1, + d.set(quality, modifier, calendar, + (day, month, 1789, slash1, 32-day, month, 1876, slash2), "Text comment") dates.append(d) d = Date() - d.set(quality, modifier, calendar, - (day, month, 1789, slash1, + d.set(quality, modifier, calendar, + (day, month, 1789, slash1, 32-day, 13-month, 1876, slash2), "Text comment") dates.append(d) @@ -141,7 +141,7 @@ class DateHandlerTest(unittest.TestCase): for l in range(1, len(dateval)): d = Date() with self.assertRaises(DateError): - d.set(Date.QUAL_NONE, Date.MOD_NONE, Date.CAL_GREGORIAN, + d.set(Date.QUAL_NONE, Date.MOD_NONE, Date.CAL_GREGORIAN, dateval[:l], "Text comment") def test_too_few_span_arguments(self): @@ -149,7 +149,7 @@ class DateHandlerTest(unittest.TestCase): for l in range(1, len(dateval)): d = Date() with self.assertRaises(DateError): - d.set(Date.QUAL_NONE, Date.MOD_SPAN, Date.CAL_GREGORIAN, + d.set(Date.QUAL_NONE, Date.MOD_SPAN, Date.CAL_GREGORIAN, dateval[:l], "Text comment") def test_invalid_day(self): diff --git a/gramps/gen/datehandler/test/dateparser_test.py b/gramps/gen/datehandler/test/dateparser_test.py index 2fbf57670..074fed89a 100644 --- a/gramps/gen/datehandler/test/dateparser_test.py +++ b/gramps/gen/datehandler/test/dateparser_test.py @@ -83,11 +83,11 @@ class Test_generate_variants(unittest.TestCase): from .._dateparser import _generate_variants self.ds = ds = _datestrings.DateStrings(GrampsLocale(languages=('ru'))) self.month_variants = list(_generate_variants( - zip(ds.long_months, ds.short_months, + zip(ds.long_months, ds.short_months, ds.swedish_SV, ds.alt_long_months))) def testVariantsSameLengthAsLongMonths(self): - self.assertEqual(len(self.ds.long_months), + self.assertEqual(len(self.ds.long_months), len(self.month_variants)) def testRussianHasDifferentVariantsForEachMonth(self): diff --git a/gramps/gen/datehandler/test/datestrings_test.py b/gramps/gen/datehandler/test/datestrings_test.py index eb4b7e639..a5bfe296f 100644 --- a/gramps/gen/datehandler/test/datestrings_test.py +++ b/gramps/gen/datehandler/test/datestrings_test.py @@ -1,4 +1,4 @@ -# -*- coding: utf-8 -*- +# -*- coding: utf-8 -*- # # Gramps - a GTK+/GNOME based genealogy program # diff --git a/gramps/gen/db/base.py b/gramps/gen/db/base.py index b5ec2f6ac..9b8cf264b 100644 --- a/gramps/gen/db/base.py +++ b/gramps/gen/db/base.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -52,9 +52,9 @@ class DbReadBase(object): def __init__(self): """ - Create a new DbReadBase instance. - - A new DbReadBase class should never be directly created. Only classes + Create a new DbReadBase instance. + + A new DbReadBase class should never be directly created. Only classes derived from this class should be created. """ self.basedb = self @@ -81,7 +81,7 @@ class DbReadBase(object): def set_feature(self, feature, value): """ - Databases can implement certain features. + Databases can implement certain features. """ self.__feature[feature] = value @@ -106,23 +106,23 @@ class DbReadBase(object): def find_backlink_handles(self, handle, include_classes=None): """ Find all objects that hold a reference to the object handle. - + Returns an iterator over a list of (class_name, handle) tuples. - + :param handle: handle of the object to search for. :type handle: database handle :param include_classes: list of class names to include in the results. Default is None which includes all classes. :type include_classes: list of class names - + This default implementation does a sequential scan through all the primary object databases and is very slow. Backends can override this method to provide much faster implementations that make use of additional capabilities of the backend. - + Note that this is a generator function, it returns a iterator for use in loops. If you want a list of the results use:: - + result_list = list(find_backlink_handles(handle)) """ raise NotImplementedError @@ -135,21 +135,21 @@ class DbReadBase(object): def find_next_event_gramps_id(self): """ - Return the next available Gramps ID for a Event object based off the + Return the next available Gramps ID for a Event object based off the event ID prefix. """ raise NotImplementedError def find_next_family_gramps_id(self): """ - Return the next available Gramps ID for a Family object based off the + Return the next available Gramps ID for a Family object based off the family ID prefix. """ raise NotImplementedError def find_next_note_gramps_id(self): """ - Return the next available Gramps ID for a Note object based off the + Return the next available Gramps ID for a Note object based off the note ID prefix. """ raise NotImplementedError @@ -163,28 +163,28 @@ class DbReadBase(object): def find_next_person_gramps_id(self): """ - Return the next available Gramps ID for a Person object based off the + Return the next available Gramps ID for a Person object based off the person ID prefix. """ raise NotImplementedError def find_next_place_gramps_id(self): """ - Return the next available Gramps ID for a Place object based off the + Return the next available Gramps ID for a Place object based off the place ID prefix. """ raise NotImplementedError def find_next_repository_gramps_id(self): """ - Return the next available Gramps ID for a Repository object based + Return the next available Gramps ID for a Repository object based off the repository ID prefix. """ raise NotImplementedError def find_next_source_gramps_id(self): """ - Return the next available Gramps ID for a Source object based off the + Return the next available Gramps ID for a Source object based off the source ID prefix. """ raise NotImplementedError @@ -229,7 +229,7 @@ class DbReadBase(object): def get_event_from_gramps_id(self, val): """ Find an Event in the database from the passed Gramps ID. - + If no such Event exists, None is returned. Needs to be overridden by the derived class. """ @@ -238,14 +238,14 @@ class DbReadBase(object): def get_event_from_handle(self, handle): """ Find a Event in the database from the passed Gramps ID. - + If no such Event exists, None is returned. """ raise NotImplementedError def get_event_handles(self): """ - Return a list of database handles, one handle for each Event in the + Return a list of database handles, one handle for each Event in the database. """ raise NotImplementedError @@ -272,7 +272,7 @@ class DbReadBase(object): def get_family_attribute_types(self): """ - Return a list of all Attribute types associated with Family instances + Return a list of all Attribute types associated with Family instances in the database. """ raise NotImplementedError @@ -298,7 +298,7 @@ class DbReadBase(object): def get_family_from_gramps_id(self, val): """ Find a Family in the database from the passed Gramps ID. - + If no such Family exists, None is returned. Need to be overridden by the derived class. """ @@ -307,7 +307,7 @@ class DbReadBase(object): def get_family_from_handle(self, handle): """ Find a Family in the database from the passed Gramps ID. - + If no such Family exists, None is returned. """ raise NotImplementedError @@ -340,7 +340,7 @@ class DbReadBase(object): def get_media_attribute_types(self): """ - Return a list of all Attribute types associated with Media and MediaRef + Return a list of all Attribute types associated with Media and MediaRef instances in the database. """ raise NotImplementedError @@ -360,8 +360,8 @@ class DbReadBase(object): def get_media_object_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each MediaObject in - the database. - + the database. + If sort_handles is True, the list is sorted by title. """ raise NotImplementedError @@ -422,21 +422,21 @@ class DbReadBase(object): def get_note_from_handle(self, handle): """ Find a Note in the database from the passed Gramps ID. - + If no such Note exists, None is returned. """ raise NotImplementedError def get_note_handles(self): """ - Return a list of database handles, one handle for each Note in the + Return a list of database handles, one handle for each Note in the database. """ raise NotImplementedError def get_note_types(self): """ - Return a list of all custom note types associated with Note instances + Return a list of all custom note types associated with Note instances in the database. """ raise NotImplementedError @@ -507,14 +507,14 @@ class DbReadBase(object): def get_object_from_handle(self, handle): """ Find an Object in the database from the passed Gramps ID. - + If no such Object exists, None is returned. """ raise NotImplementedError def get_person_attribute_types(self): """ - Return a list of all Attribute types associated with Person instances + Return a list of all Attribute types associated with Person instances in the database. """ raise NotImplementedError @@ -534,7 +534,7 @@ class DbReadBase(object): def get_person_from_gramps_id(self, val): """ Find a Person in the database from the passed Gramps ID. - + If no such Person exists, None is returned. Needs to be overridden by the derived class. """ @@ -543,7 +543,7 @@ class DbReadBase(object): def get_person_from_handle(self, handle): """ Find a Person in the database from the passed Gramps ID. - + If no such Person exists, None is returned. """ raise NotImplementedError @@ -551,8 +551,8 @@ class DbReadBase(object): def get_person_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Person in - the database. - + the database. + If sort_handles is True, the list is sorted by surnames. """ raise NotImplementedError @@ -579,7 +579,7 @@ class DbReadBase(object): def get_place_from_gramps_id(self, val): """ Find a Place in the database from the passed Gramps ID. - + If no such Place exists, None is returned. Needs to be overridden by the derived class. """ @@ -588,7 +588,7 @@ class DbReadBase(object): def get_place_from_handle(self, handle): """ Find a Place in the database from the passed Gramps ID. - + If no such Place exists, None is returned. """ raise NotImplementedError @@ -596,8 +596,8 @@ class DbReadBase(object): def get_place_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Place in - the database. - + the database. + If sort_handles is True, the list is sorted by Place title. """ raise NotImplementedError @@ -704,7 +704,7 @@ class DbReadBase(object): def get_repository_from_handle(self, handle): """ Find a Repository in the database from the passed Gramps ID. - + If no such Repository exists, None is returned. """ raise NotImplementedError @@ -718,14 +718,14 @@ class DbReadBase(object): def get_repository_types(self): """ - Return a list of all custom repository types associated with Repository + Return a list of all custom repository types associated with Repository instances in the database. """ raise NotImplementedError def get_researcher(self): """ - Return the Researcher instance, providing information about the owner + Return the Researcher instance, providing information about the owner of the database. """ raise NotImplementedError @@ -751,7 +751,7 @@ class DbReadBase(object): def get_source_from_gramps_id(self, val): """ Find a Source in the database from the passed Gramps ID. - + If no such Source exists, None is returned. Needs to be overridden by the derived class. """ @@ -760,7 +760,7 @@ class DbReadBase(object): def get_source_from_handle(self, handle): """ Find a Source in the database from the passed Gramps ID. - + If no such Source exists, None is returned. """ raise NotImplementedError @@ -769,14 +769,14 @@ class DbReadBase(object): """ Return a list of database handles, one handle for each Source in the database. - + If sort_handles is True, the list is sorted by Source title. """ raise NotImplementedError def get_source_media_types(self): """ - Return a list of all custom source media types associated with Source + Return a list of all custom source media types associated with Source instances in the database. """ raise NotImplementedError @@ -796,7 +796,7 @@ class DbReadBase(object): def get_citation_from_gramps_id(self, val): """ Find a Citation in the database from the passed Gramps ID. - + If no such Citation exists, None is returned. Needs to be overridden by the derived class. """ @@ -805,7 +805,7 @@ class DbReadBase(object): def get_citation_from_handle(self, handle): """ Find a Citation in the database from the passed Gramps ID. - + If no such Citation exists, None is returned. """ raise NotImplementedError @@ -814,7 +814,7 @@ class DbReadBase(object): """ Return a list of database handles, one handle for each Citation in the database. - + If sort_handles is True, the list is sorted by Citation title. """ raise NotImplementedError @@ -834,7 +834,7 @@ class DbReadBase(object): def get_tag_from_handle(self, handle): """ Find a Tag in the database from the passed handle. - + If no such Tag exists, None is returned. """ raise NotImplementedError @@ -842,7 +842,7 @@ class DbReadBase(object): def get_tag_from_name(self, val): """ Find a Tag in the database from the passed Tag name. - + If no such Tag exists, None is returned. Needs to be overridden by the derived class. """ @@ -852,14 +852,14 @@ class DbReadBase(object): """ Return a list of database handles, one handle for each Tag in the database. - + If sort_handles is True, the list is sorted by Tag name. """ raise NotImplementedError def get_url_types(self): """ - Return a list of all custom names types associated with Url instances + Return a list of all custom names types associated with Url instances in the database. """ raise NotImplementedError @@ -1092,10 +1092,10 @@ class DbReadBase(object): def set_event_id_prefix(self, val): """ - Set the naming template for Gramps Event ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Event ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as E%d or E%04d. """ raise NotImplementedError @@ -1111,40 +1111,40 @@ class DbReadBase(object): def set_note_id_prefix(self, val): """ - Set the naming template for Gramps Note ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Note ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as N%d or N%04d. """ raise NotImplementedError def set_object_id_prefix(self, val): """ - Set the naming template for Gramps MediaObject ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps MediaObject ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as O%d or O%04d. """ raise NotImplementedError def set_person_id_prefix(self, val): """ - Set the naming template for Gramps Person ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Person ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as I%d or I%04d. """ raise NotImplementedError def set_place_id_prefix(self, val): """ - Set the naming template for Gramps Place ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Place ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as P%d or P%04d. """ raise NotImplementedError @@ -1158,20 +1158,20 @@ class DbReadBase(object): def set_repository_id_prefix(self, val): """ - Set the naming template for Gramps Repository ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Repository ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as R%d or R%04d. """ raise NotImplementedError def set_source_id_prefix(self, val): """ - Set the naming template for Gramps Source ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Source ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as S%d or S%04d. """ raise NotImplementedError @@ -1185,9 +1185,9 @@ class DbReadBase(object): def set_redo_callback(self, callback): """ Define the callback function that is called whenever an redo operation - is executed. - - The callback function receives a single argument that is a text string + is executed. + + The callback function receives a single argument that is a text string that defines the operation. """ raise NotImplementedError @@ -1207,9 +1207,9 @@ class DbReadBase(object): def set_undo_callback(self, callback): """ Define the callback function that is called whenever an undo operation - is executed. - - The callback function receives a single argument that is a text string + is executed. + + The callback function receives a single argument that is a text string that defines the operation. """ raise NotImplementedError @@ -1235,9 +1235,9 @@ class DbWriteBase(DbReadBase): def __init__(self): """ - Create a new DbWriteBase instance. - - A new DbWriteBase class should never be directly created. Only classes + Create a new DbWriteBase instance. + + A new DbWriteBase class should never be directly created. Only classes derived from this class should be created. """ DbReadBase.__init__(self) @@ -1246,7 +1246,7 @@ class DbWriteBase(DbReadBase): """ Add an Event to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ raise NotImplementedError @@ -1255,7 +1255,7 @@ class DbWriteBase(DbReadBase): """ Add a Family to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ raise NotImplementedError @@ -1270,7 +1270,7 @@ class DbWriteBase(DbReadBase): """ Add a Note to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ raise NotImplementedError @@ -1279,7 +1279,7 @@ class DbWriteBase(DbReadBase): """ Add a MediaObject to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ raise NotImplementedError @@ -1288,7 +1288,7 @@ class DbWriteBase(DbReadBase): """ Add a Person to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ raise NotImplementedError @@ -1303,7 +1303,7 @@ class DbWriteBase(DbReadBase): """ Add a Place to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ raise NotImplementedError @@ -1312,7 +1312,7 @@ class DbWriteBase(DbReadBase): """ Add a Repository to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ raise NotImplementedError @@ -1321,7 +1321,7 @@ class DbWriteBase(DbReadBase): """ Add a Source to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ raise NotImplementedError @@ -1347,21 +1347,21 @@ class DbWriteBase(DbReadBase): def commit_base(self, obj, data_map, key, transaction, change_time): """ - Commit the specified object to the database, storing the changes as + Commit the specified object to the database, storing the changes as part of the transaction. """ raise NotImplementedError def commit_event(self, event, transaction, change_time=None): """ - Commit the specified Event to the database, storing the changes as + Commit the specified Event to the database, storing the changes as part of the transaction. """ raise NotImplementedError def commit_family(self, family, transaction, change_time=None): """ - Commit the specified Family to the database, storing the changes as + Commit the specified Family to the database, storing the changes as part of the transaction. """ raise NotImplementedError @@ -1381,14 +1381,14 @@ class DbWriteBase(DbReadBase): def commit_note(self, note, transaction, change_time=None): """ - Commit the specified Note to the database, storing the changes as part + Commit the specified Note to the database, storing the changes as part of the transaction. """ raise NotImplementedError def commit_person(self, person, transaction, change_time=None): """ - Commit the specified Person to the database, storing the changes as + Commit the specified Person to the database, storing the changes as part of the transaction. """ raise NotImplementedError @@ -1401,7 +1401,7 @@ class DbWriteBase(DbReadBase): def commit_place(self, place, transaction, change_time=None): """ - Commit the specified Place to the database, storing the changes as + Commit the specified Place to the database, storing the changes as part of the transaction. """ raise NotImplementedError @@ -1415,23 +1415,23 @@ class DbWriteBase(DbReadBase): def commit_source(self, source, transaction, change_time=None): """ - Commit the specified Source to the database, storing the changes as + Commit the specified Source to the database, storing the changes as part of the transaction. """ raise NotImplementedError def commit_tag(self, tag, transaction, change_time=None): """ - Commit the specified Tag to the database, storing the changes as + Commit the specified Tag to the database, storing the changes as part of the transaction. """ raise NotImplementedError def delete_primary_from_reference_map(self, handle, transaction): """ - Called each time an object is removed from the database. - - This can be used by subclasses to update any additional index tables + Called each time an object is removed from the database. + + This can be used by subclasses to update any additional index tables that might need to be changed. """ raise NotImplementedError @@ -1463,8 +1463,8 @@ class DbWriteBase(DbReadBase): def remove_event(self, handle, transaction): """ Remove the Event specified by the database handle from the - database, preserving the change in the passed transaction. - + database, preserving the change in the passed transaction. + This method must be overridden in the derived class. """ raise NotImplementedError @@ -1472,8 +1472,8 @@ class DbWriteBase(DbReadBase): def remove_family(self, handle, transaction): """ Remove the Family specified by the database handle from the - database, preserving the change in the passed transaction. - + database, preserving the change in the passed transaction. + This method must be overridden in the derived class. """ raise NotImplementedError @@ -1481,8 +1481,8 @@ class DbWriteBase(DbReadBase): def remove_from_surname_list(self, person): """ Check whether there are persons with the same surname left in - the database. - + the database. + If not then we need to remove the name from the list. The function must be overridden in the derived class. """ @@ -1491,8 +1491,8 @@ class DbWriteBase(DbReadBase): def remove_note(self, handle, transaction): """ Remove the Note specified by the database handle from the - database, preserving the change in the passed transaction. - + database, preserving the change in the passed transaction. + This method must be overridden in the derived class. """ raise NotImplementedError @@ -1500,17 +1500,17 @@ class DbWriteBase(DbReadBase): def remove_object(self, handle, transaction): """ Remove the MediaObjectPerson specified by the database handle from the - database, preserving the change in the passed transaction. - + database, preserving the change in the passed transaction. + This method must be overridden in the derived class. """ raise NotImplementedError def remove_person(self, handle, transaction): """ - Remove the Person specified by the database handle from the database, - preserving the change in the passed transaction. - + Remove the Person specified by the database handle from the database, + preserving the change in the passed transaction. + This method must be overridden in the derived class. """ raise NotImplementedError @@ -1518,8 +1518,8 @@ class DbWriteBase(DbReadBase): def remove_place(self, handle, transaction): """ Remove the Place specified by the database handle from the - database, preserving the change in the passed transaction. - + database, preserving the change in the passed transaction. + This method must be overridden in the derived class. """ raise NotImplementedError @@ -1527,8 +1527,8 @@ class DbWriteBase(DbReadBase): def remove_repository(self, handle, transaction): """ Remove the Repository specified by the database handle from the - database, preserving the change in the passed transaction. - + database, preserving the change in the passed transaction. + This method must be overridden in the derived class. """ raise NotImplementedError @@ -1536,8 +1536,8 @@ class DbWriteBase(DbReadBase): def remove_source(self, handle, transaction): """ Remove the Source specified by the database handle from the - database, preserving the change in the passed transaction. - + database, preserving the change in the passed transaction. + This method must be overridden in the derived class. """ raise NotImplementedError @@ -1545,8 +1545,8 @@ class DbWriteBase(DbReadBase): def remove_tag(self, handle, transaction): """ Remove the Tag specified by the database handle from the - database, preserving the change in the passed transaction. - + database, preserving the change in the passed transaction. + This method must be overridden in the derived class. """ raise NotImplementedError @@ -1565,8 +1565,8 @@ class DbWriteBase(DbReadBase): def set_name_group_mapping(self, name, group): """ - Set the default grouping name for a surname. - + Set the default grouping name for a surname. + Needs to be overridden in the derived class. """ raise NotImplementedError @@ -1580,7 +1580,7 @@ class DbWriteBase(DbReadBase): def transaction_begin(self, transaction): """ Prepare the database for the start of a new transaction. - + Two modes should be provided: transaction.batch=False for ordinary database operations that will be encapsulated in database transactions to make them ACID and that are added to Gramps transactions so that @@ -1611,9 +1611,9 @@ class DbWriteBase(DbReadBase): def update_reference_map(self, obj, transaction): """ - Called each time an object is writen to the database. - - This can be used by subclasses to update any additional index tables + Called each time an object is writen to the database. + + This can be used by subclasses to update any additional index tables that might need to be changed. """ raise NotImplementedError @@ -1635,10 +1635,10 @@ class DbWriteBase(DbReadBase): cref.ref = child.handle cref.set_father_relation(frel) cref.set_mother_relation(mrel) - + family.add_child_ref(cref) child.add_parent_family_handle(family.handle) - + if trans is None: with DbTxn(_('Add child to family'), self) as trans: self.commit_family(family, trans) @@ -1669,42 +1669,42 @@ class DbWriteBase(DbReadBase): family = self.get_family_from_handle(family_handle) person.remove_parent_family_handle(family_handle) family.remove_child_handle(person_handle) - + if (not family.get_father_handle() and not family.get_mother_handle() and not family.get_child_ref_list()): self.remove_family_relationships(family_handle, trans) else: self.commit_family(family, trans) self.commit_person(person, trans) - + def delete_person_from_database(self, person, trans): """ Deletes a person from the database, cleaning up all associated references. """ - + # clear out the default person if the person is the default person if self.get_default_person() == person: self.set_default_person_handle(None) - - # loop through the family list + + # loop through the family list for family_handle in person.get_family_handle_list(): if not family_handle: continue - + family = self.get_family_from_handle(family_handle) - + if person.get_handle() == family.get_father_handle(): family.set_father_handle(None) else: family.set_mother_handle(None) - + if not family.get_father_handle() and \ not family.get_mother_handle() and \ not family.get_child_ref_list(): self.remove_family_relationships(family_handle, trans) else: self.commit_family(family, trans) - + for family_handle in person.get_parent_family_handle_list(): if family_handle: family = self.get_family_from_handle(family_handle) @@ -1715,19 +1715,19 @@ class DbWriteBase(DbReadBase): self.remove_family_relationships(family_handle, trans) else: self.commit_family(family, trans) - + handle = person.get_handle() - + person_list = [ item[1] for item in self.find_backlink_handles(handle,['Person'])] - + for phandle in person_list: prsn = self.get_person_from_handle(phandle) prsn.remove_handle_references('Person', [handle]) self.commit_person(prsn, trans) self.remove_person(handle, trans) - + def remove_family_relationships(self, family_handle, trans=None): """ Remove a family and its relationships. @@ -1775,7 +1775,7 @@ class DbWriteBase(DbReadBase): """ person = self.get_person_from_handle(person_handle) family = self.get_family_from_handle(family_handle) - + person.remove_family_handle(family_handle) if family.get_father_handle() == person_handle: family.set_father_handle(None) @@ -1788,7 +1788,7 @@ class DbWriteBase(DbReadBase): "the family you try to remove is not consistent, please fix " "that first, for example from the family editor or by running " "the database repair tool, before removing the family.") - + if (not family.get_father_handle() and not family.get_mother_handle() and not family.get_child_ref_list()): self.remove_family_relationships(family_handle, trans) @@ -1806,7 +1806,7 @@ class DbWriteBase(DbReadBase): if event and event.type.is_marriage(): return event return None - + def get_total(self): """ Get the total of primary objects. @@ -1818,10 +1818,10 @@ class DbWriteBase(DbReadBase): place_len = self.get_number_of_places() repo_len = self.get_number_of_repositories() obj_len = self.get_number_of_media_objects() - + return person_len + family_len + event_len + \ place_len + source_len + obj_len + repo_len - + def set_birth_death_index(self, person): """ Set the birth and death indices for a person. @@ -1832,15 +1832,15 @@ class DbWriteBase(DbReadBase): for index in range(len(event_ref_list)): ref = event_ref_list[index] event = self.get_event_from_handle(ref.ref) - if (event.type.is_birth() - and ref.role.is_primary() + if (event.type.is_birth() + and ref.role.is_primary() and (birth_ref_index == -1)): birth_ref_index = index - elif (event.type.is_death() - and ref.role.is_primary() + elif (event.type.is_death() + and ref.role.is_primary() and (death_ref_index == -1)): death_ref_index = index - + person.birth_ref_index = birth_ref_index person.death_ref_index = death_ref_index diff --git a/gramps/gen/db/dbconst.py b/gramps/gen/db/dbconst.py index 21a17db80..c7b101ce0 100644 --- a/gramps/gen/db/dbconst.py +++ b/gramps/gen/db/dbconst.py @@ -71,24 +71,24 @@ CITATION_KEY = 10 TXNADD, TXNUPD, TXNDEL = 0, 1, 2 -CLASS_TO_KEY_MAP = {"Person": PERSON_KEY, - "Family": FAMILY_KEY, - "Source": SOURCE_KEY, - "Citation": CITATION_KEY, - "Event": EVENT_KEY, - "MediaObject": MEDIA_KEY, - "Place": PLACE_KEY, +CLASS_TO_KEY_MAP = {"Person": PERSON_KEY, + "Family": FAMILY_KEY, + "Source": SOURCE_KEY, + "Citation": CITATION_KEY, + "Event": EVENT_KEY, + "MediaObject": MEDIA_KEY, + "Place": PLACE_KEY, "Repository": REPOSITORY_KEY, "Note" : NOTE_KEY, "Tag": TAG_KEY} -KEY_TO_CLASS_MAP = {PERSON_KEY: "Person", - FAMILY_KEY: "Family", - SOURCE_KEY: "Source", - CITATION_KEY: "Citation", - EVENT_KEY: "Event", - MEDIA_KEY: "MediaObject", - PLACE_KEY: "Place", +KEY_TO_CLASS_MAP = {PERSON_KEY: "Person", + FAMILY_KEY: "Family", + SOURCE_KEY: "Source", + CITATION_KEY: "Citation", + EVENT_KEY: "Event", + MEDIA_KEY: "MediaObject", + PLACE_KEY: "Place", REPOSITORY_KEY: "Repository", NOTE_KEY: "Note", TAG_KEY: "Tag"} diff --git a/gramps/gen/db/exceptions.py b/gramps/gen/db/exceptions.py index 50512656e..324a51639 100644 --- a/gramps/gen/db/exceptions.py +++ b/gramps/gen/db/exceptions.py @@ -41,11 +41,11 @@ URL_BACKUP2_START = URL_MANUAL_START + '#Backing_up_a_Family_Tree">' URL_EXPORT_START = URL_MANUAL_START + '#Export_into_Gramps_formats">' class DbException(Exception): - + def __init__(self, value): Exception.__init__(self) self.value = value - + def __str__(self): return self.value @@ -57,13 +57,13 @@ class DbWriteFailure(Exception): Exception.__init__(self) self.value = value self.value2 = value2 - + def __str__(self): return self.value - + def messages(self): return self.value, self.value2 - + class DbTransactionCancel(Exception): """ Error used to indicate that a transaction needs to be canceled, @@ -78,7 +78,7 @@ class DbTransactionCancel(Exception): class DbVersionError(Exception): """ - Error used to report that a file could not be read because it is written + Error used to report that a file could not be read because it is written in an unsupported version of the file format. """ def __init__(self, tree_vers, min_vers, max_vers): @@ -98,7 +98,7 @@ class DbVersionError(Exception): {'tree_vers': self.tree_vers, 'min_vers': self.min_vers, 'max_vers': self.max_vers} - + class BsddbDowngradeError(Exception): """ Error used to report that the Berkeley database used to create the family @@ -214,10 +214,10 @@ class DbEnvironmentError(Exception): "in an empty Family Tree. Alternatively, it may be possible " "to use the Berkeley database recovery tools.") + '\n\n' + str(self.msg)) - + class DbUpgradeRequiredError(Exception): """ - Error used to report that a database needs to be upgraded before it can be + Error used to report that a database needs to be upgraded before it can be used. """ def __init__(self, oldschema, newschema): @@ -229,7 +229,7 @@ class DbUpgradeRequiredError(Exception): return _('The Family Tree you are trying to load is in the schema ' 'version %(oldschema)s format. This version of Gramps uses ' 'schema version %(newschema)s. Therefore you cannot load this ' - 'Family Tree without upgrading the schema version of the ' + 'Family Tree without upgrading the schema version of the ' 'Family Tree.\n\n' 'If you upgrade then you won\'t be able to use the previous ' 'version of Gramps, even if you subsequently ' @@ -251,7 +251,7 @@ class DbUpgradeRequiredError(Exception): 'bold_end' : '' , 'oldschema' : self.oldschema, 'newschema' : self.newschema } - + class PythonDowngradeError(Exception): """ Error used to report that the Python version used to create the family tree @@ -323,7 +323,7 @@ class PythonUpgradeRequiredError(Exception): if __name__ == "__main__": """ Call this from the CLI (in order to find the imported modules): - cd /path/to/gramps; GRAMPS_RESOURCES=. ; PYTHONPATH=. + cd /path/to/gramps; GRAMPS_RESOURCES=. ; PYTHONPATH=. python gramps/gen/db/exceptions.py """ import sys diff --git a/gramps/gen/db/txn.py b/gramps/gen/db/txn.py index d3f287559..b460879c0 100644 --- a/gramps/gen/db/txn.py +++ b/gramps/gen/db/txn.py @@ -71,38 +71,38 @@ class DbTxn(defaultdict): else: self.db.transaction_abort(self) return False - + def __init__(self, msg, grampsdb, batch=False, **kwargs): """ - Create a new transaction. - - The grampsdb should have transaction_begin/commit/abort methods, and + Create a new transaction. + + The grampsdb should have transaction_begin/commit/abort methods, and a get_undodb method to store undo actions. - + A Transaction instance can be created directly, but it is advised to - use a context to do this. Like this the user must not worry about + use a context to do this. Like this the user must not worry about calling the transaction_xx methods on the database. - + The grampsdb parameter is a reference to the DbWrite object to which this transaction will be applied. - grampsdb.get_undodb() should return a list-like interface that + grampsdb.get_undodb() should return a list-like interface that stores the commit data. This could be a simple list, or a RECNO-style - database object. + database object. The data structure used to handle the transactions (see the add method) is a Python dictionary where: - + key = (object type, transaction type) where: object type = the numeric type of an object. These are defined as PERSON_KEY = 0, FAMILY_KEY = 1, etc. as imported from dbconst. transaction type = a numeric representation of the type of transaction: TXNADD = 0, TXNUPD = 1, TXNDEL = 2 - + data = Python list where: list element = (handle, data) where: handle = handle (database key) of the object in the transaction - data = pickled representation of the object + data = pickled representation of the object """ defaultdict.__init__(self, list, {}) @@ -119,24 +119,24 @@ class DbTxn(defaultdict): def get_description(self): """ - Return the text string that describes the logical operation performed + Return the text string that describes the logical operation performed by the Transaction. """ return self.msg def set_description(self, msg): """ - Set the text string that describes the logical operation performed by + Set the text string that describes the logical operation performed by the Transaction. """ self.msg = msg def add(self, obj_type, trans_type, handle, old_data, new_data): """ - Add a commit operation to the Transaction. - - The obj_type is a constant that indicates what type of PrimaryObject - is being added. The handle is the object's database handle, and the + Add a commit operation to the Transaction. + + The obj_type is a constant that indicates what type of PrimaryObject + is being added. The handle is the object's database handle, and the data is the tuple returned by the object's serialize method. """ self.last = self.commitdb.append( @@ -152,7 +152,7 @@ class DbTxn(defaultdict): def get_recnos(self, reverse=False): """ Return a list of record numbers associated with the transaction. - + While the list is an arbitrary index of integers, it can be used to indicate record numbers for a database. """ @@ -185,7 +185,7 @@ class DbTxn(defaultdict): def testtxn(): """ Test suite - """ + """ class FakeMap(dict): """Fake database map with just two methods""" def put(self, key, data): diff --git a/gramps/gen/db/undoredo.py b/gramps/gen/db/undoredo.py index fdb4fb1cc..d1db5a1d9 100644 --- a/gramps/gen/db/undoredo.py +++ b/gramps/gen/db/undoredo.py @@ -76,34 +76,34 @@ class DbUndo(object): """ Close the backing storage. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def append(self, value): """ Add a new entry on the end. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def __getitem__(self, index): """ Returns an entry by index number. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def __setitem__(self, index, value): """ Set an entry to a value. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def __len__(self): """ Returns the number of entries. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def __redo(self, update_history): diff --git a/gramps/gen/dbstate.py b/gramps/gen/dbstate.py index c8c82d583..be17e6439 100644 --- a/gramps/gen/dbstate.py +++ b/gramps/gen/dbstate.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -45,8 +45,8 @@ class DbState(Callback): """ __signals__ = { - 'database-changed' : ((DbReadBase, ProxyDbBase), ), - 'no-database' : None, + 'database-changed' : ((DbReadBase, ProxyDbBase), ), + 'no-database' : None, } def __init__(self): @@ -102,7 +102,7 @@ class DbState(Callback): self.db.db_is_open = False self.open = False self.emit('database-changed', (self.db, )) - + def get_database(self): """ Get a reference to the current database. @@ -128,7 +128,7 @@ class DbState(Callback): self.stack.append(self.db) self.db = proxy(self.db, *args, **kwargs) self.emit('database-changed', (self.db, )) - + def pop_proxy(self): """ Remove the previously applied proxy. @@ -150,7 +150,7 @@ class DbState(Callback): pmgr = BasePluginManager.get_instance() pdata = pmgr.get_plugin(id) - + if not pdata: # This might happen if using gramps from outside, and # we haven't loaded plugins yet diff --git a/gramps/gen/display/name.py b/gramps/gen/display/name.py index 586ac749d..0cba3c958 100644 --- a/gramps/gen/display/name.py +++ b/gramps/gen/display/name.py @@ -77,7 +77,7 @@ try: WITH_GRAMPS_CONFIG=True except ImportError: WITH_GRAMPS_CONFIG=False - + #------------------------------------------------------------------------- # @@ -120,10 +120,10 @@ PAT_AS_SURN = False # #------------------------------------------------------------------------- # Because of occurring in an exec(), this couldn't be in a lambda: -# we sort names first on longest first, then last letter first, this to +# we sort names first on longest first, then last letter first, this to # avoid translations of shorter terms which appear in longer ones, eg -# namelast may not be mistaken with name, so namelast must first be -# converted to %k before name is converted. +# namelast may not be mistaken with name, so namelast must first be +# converted to %k before name is converted. ##def _make_cmp(a, b): return -cmp((len(a[1]),a[1]), (len(b[1]), b[1])) def _make_cmp_key(a): return (len(a[1]),a[1]) # set reverse to True!! @@ -164,9 +164,9 @@ def _raw_primary_surname(raw_surn_data_list): nrsur = len(raw_surn_data_list) for raw_surn_data in raw_surn_data_list: if raw_surn_data[_PRIMARY_IN_LIST]: - #if there are multiple surnames, return the primary. If there - #is only one surname, then primary has little meaning, and we - #assume a pa/matronymic should not be given as primary as it + #if there are multiple surnames, return the primary. If there + #is only one surname, then primary has little meaning, and we + #assume a pa/matronymic should not be given as primary as it #normally is defined independently if not PAT_AS_SURN and nrsur == 1 and \ (raw_surn_data[_TYPE_IN_LIST][0] == _ORIGINPATRO @@ -299,7 +299,7 @@ def _raw_single_surname(raw_surn_data_list): return ' '.join(result.split()).strip() def cleanup_name(namestring): - """Remove too long white space due to missing name parts, + """Remove too long white space due to missing name parts, so "a b" becomes "a b" and "a , b" becomes "a, b" """ parts = namestring.split() @@ -313,7 +313,7 @@ def cleanup_name(namestring): else: result += ' ' + val return result - + #------------------------------------------------------------------------- # # NameDisplay class @@ -322,8 +322,8 @@ def cleanup_name(namestring): class NameDisplay(object): """ Base class for displaying of Name instances. - - Property: + + Property: *default_format* the default name format to use *pas_as_surn* @@ -336,7 +336,7 @@ class NameDisplay(object): def __init__(self, xlocale=glocale): """ Initialize the NameDisplay class. - + If xlocale is passed in (a GrampsLocale), then the translated script will be returned instead. @@ -360,7 +360,7 @@ class NameDisplay(object): '%f %l %s', _ACT), # primary name primconnector other, given pa/matronynic suffix, primprefix # translators: long string, have a look at Preferences dialog - (Name.LNFNP, _("Main Surnames, Given Patronymic Suffix Prefix"), + (Name.LNFNP, _("Main Surnames, Given Patronymic Suffix Prefix"), '%1m %2m %o' + COMMAGLYPH + ' %f %1y %s %0m', _ACT), # DEPRECATED FORMATS (Name.PTFN, _("Patronymic, Given"), @@ -370,13 +370,13 @@ class NameDisplay(object): self.LNFN_STR = "%s" + COMMAGLYPH + " %s %s" self.name_formats = {} - + if WITH_GRAMPS_CONFIG: self.default_format = config.get('preferences.name-format') if self.default_format == 0: self.default_format = Name.LNFN config.set('preferences.name-format', self.default_format) - #if only one surname, see if pa/ma should be considered as + #if only one surname, see if pa/ma should be considered as # 'the' surname. PAT_AS_SURN = config.get('preferences.patronimic-surname') config.connect('preferences.patronimic-surname', self.change_pa_sur) @@ -399,7 +399,7 @@ class NameDisplay(object): def _format_fn(self, fmt_str): return lambda x: self.format_str(x, fmt_str) - + def _format_raw_fn(self, fmt_str): return lambda x: self.format_str_raw(x, fmt_str) @@ -416,11 +416,11 @@ class NameDisplay(object): return ' '.join(result.split()) def _raw_fn(self, raw_data): - result = raw_data[_FIRSTNAME] + result = raw_data[_FIRSTNAME] return ' '.join(result.split()) def set_name_format(self, formats): - + raw_func_dict = { Name.LNFN : self._raw_lnfn, Name.FNLN : self._raw_fnln, @@ -439,7 +439,7 @@ class NameDisplay(object): num -= 1 self.set_name_format([(num, name, fmt_str,_ACT)]) return num - + def edit_name_format(self, num, name, fmt_str): self.set_name_format([(num, name, fmt_str,_ACT)]) if self.default_format == num: @@ -458,15 +458,15 @@ class NameDisplay(object): # then we select LNFN as format. if num == Name.DEF: num = Name.LNFN - + self.default_format = num - + self.name_formats[Name.DEF] = (self.name_formats[Name.DEF][_F_NAME], self.name_formats[Name.DEF][_F_FMT], self.name_formats[Name.DEF][_F_ACT], self.name_formats[num][_F_FN], self.name_formats[num][_F_RAWFN]) - + def get_default_format(self): return self.default_format @@ -479,7 +479,7 @@ class NameDisplay(object): self.name_formats[num][_F_RAWFN]) except: pass - + def get_name_format(self, also_default=False, only_custom=False, only_active=True): @@ -488,8 +488,8 @@ class NameDisplay(object): """ the_list = [] - keys = sorted(self.name_formats, key=self.cmp_to_key(self._sort_name_format)) - + keys = sorted(self.name_formats, key=self.cmp_to_key(self._sort_name_format)) + for num in keys: if ((also_default or num) and (not only_custom or (num < 0)) and @@ -502,7 +502,7 @@ class NameDisplay(object): """ python 2 to 3 conversion, python recipe http://code.activestate.com/recipes/576653/ Convert a :func:`cmp` function into a :func:`key` function - We use this in Gramps as understanding the old compare function is + We use this in Gramps as understanding the old compare function is not trivial. This should be replaced by a proper key function """ class K(object): @@ -515,7 +515,7 @@ class NameDisplay(object): def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): - return mycmp(self.obj, other.obj) <= 0 + return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): @@ -523,22 +523,22 @@ class NameDisplay(object): return K def _sort_name_format(self, x, y): if x < 0: - if y < 0: + if y < 0: return x+y - else: + else: return -x+y else: - if y < 0: + if y < 0: return -x+y - else: + else: return x-y - + def _is_format_valid(self, num): try: if not self.name_formats[num][_F_ACT]: num = 0 except: - num = 0 + num = 0 return num #------------------------------------------------------------------------- @@ -547,9 +547,9 @@ class NameDisplay(object): def _gen_raw_func(self, format_str): """The job of building the name from a format string is rather expensive and it is called lots and lots of times. So it is worth - going to some length to optimise it as much as possible. + going to some length to optimise it as much as possible. - This method constructs a new function that is specifically written + This method constructs a new function that is specifically written to format a name given a particular format string. This is worthwhile because the format string itself rarely changes, so by caching the new function and calling it directly when asked to format a name to the @@ -574,7 +574,7 @@ class NameDisplay(object): '1m': primary[sur]= surname primary surname (main) '2m': primary[con]= connector primary surname (main) 'y' : patronymic = pa/matronymic surname (father/mother) - assumed unique - '0y': patronymic[pre] = prefix " + '0y': patronymic[pre] = prefix " '1y': patronymic[sur] = surname " '2y': patronymic[con] = connector " 'o' : notpatronymic = surnames without pa/matronymic and primary @@ -591,15 +591,15 @@ class NameDisplay(object): # we need the names of each of the variables or methods that are # called to fill in each format flag. # Dictionary is "code": ("expression", "keyword", "i18n-keyword") - d = {"t": ("raw_data[_TITLE]", "title", + d = {"t": ("raw_data[_TITLE]", "title", _("Person|title")), - "f": ("raw_data[_FIRSTNAME]", "given", + "f": ("raw_data[_FIRSTNAME]", "given", _("given")), "l": ("_raw_full_surname(raw_data[_SURNAME_LIST])", "surname", _("surname")), - "s": ("raw_data[_SUFFIX]", "suffix", + "s": ("raw_data[_SUFFIX]", "suffix", _("suffix")), - "c": ("raw_data[_CALL]", "call", + "c": ("raw_data[_CALL]", "call", _("Name|call")), "x": ("(raw_data[_NICK] or raw_data[_CALL] or raw_data[_FIRSTNAME].split(' ')[0])", "common", @@ -608,40 +608,40 @@ class NameDisplay(object): " raw_data[_FIRSTNAME]).split()][1:])", "initials", _("initials")), - "m": ("_raw_primary_surname(raw_data[_SURNAME_LIST])", - "primary", + "m": ("_raw_primary_surname(raw_data[_SURNAME_LIST])", + "primary", _("Name|primary")), - "0m": ("_raw_primary_prefix_only(raw_data[_SURNAME_LIST])", - "primary[pre]", + "0m": ("_raw_primary_prefix_only(raw_data[_SURNAME_LIST])", + "primary[pre]", _("primary[pre]")), - "1m": ("_raw_primary_surname_only(raw_data[_SURNAME_LIST])", - "primary[sur]", + "1m": ("_raw_primary_surname_only(raw_data[_SURNAME_LIST])", + "primary[sur]", _("primary[sur]")), - "2m": ("_raw_primary_conn_only(raw_data[_SURNAME_LIST])", - "primary[con]", + "2m": ("_raw_primary_conn_only(raw_data[_SURNAME_LIST])", + "primary[con]", _("primary[con]")), - "y": ("_raw_patro_surname(raw_data[_SURNAME_LIST])", "patronymic", + "y": ("_raw_patro_surname(raw_data[_SURNAME_LIST])", "patronymic", _("patronymic")), - "0y": ("_raw_patro_prefix_only(raw_data[_SURNAME_LIST])", "patronymic[pre]", + "0y": ("_raw_patro_prefix_only(raw_data[_SURNAME_LIST])", "patronymic[pre]", _("patronymic[pre]")), - "1y": ("_raw_patro_surname_only(raw_data[_SURNAME_LIST])", "patronymic[sur]", + "1y": ("_raw_patro_surname_only(raw_data[_SURNAME_LIST])", "patronymic[sur]", _("patronymic[sur]")), - "2y": ("_raw_patro_conn_only(raw_data[_SURNAME_LIST])", "patronymic[con]", + "2y": ("_raw_patro_conn_only(raw_data[_SURNAME_LIST])", "patronymic[con]", _("patronymic[con]")), - "o": ("_raw_nonpatro_surname(raw_data[_SURNAME_LIST])", "notpatronymic", + "o": ("_raw_nonpatro_surname(raw_data[_SURNAME_LIST])", "notpatronymic", _("notpatronymic")), - "r": ("_raw_nonprimary_surname(raw_data[_SURNAME_LIST])", - "rest", + "r": ("_raw_nonprimary_surname(raw_data[_SURNAME_LIST])", + "rest", _("Remaining names|rest")), - "p": ("_raw_prefix_surname(raw_data[_SURNAME_LIST])", - "prefix", + "p": ("_raw_prefix_surname(raw_data[_SURNAME_LIST])", + "prefix", _("prefix")), - "q": ("_raw_single_surname(raw_data[_SURNAME_LIST])", - "rawsurnames", + "q": ("_raw_single_surname(raw_data[_SURNAME_LIST])", + "rawsurnames", _("rawsurnames")), - "n": ("raw_data[_NICK]", "nickname", + "n": ("raw_data[_NICK]", "nickname", _("nickname")), - "g": ("raw_data[_FAMNICK]", "familynick", + "g": ("raw_data[_FAMNICK]", "familynick", _("familynick")), } args = "raw_data" @@ -650,9 +650,9 @@ class NameDisplay(object): def _gen_cooked_func(self, format_str): """The job of building the name from a format string is rather expensive and it is called lots and lots of times. So it is worth - going to some length to optimise it as much as possible. + going to some length to optimise it as much as possible. - This method constructs a new function that is specifically written + This method constructs a new function that is specifically written to format a name given a particular format string. This is worthwhile because the format string itself rarely changes, so by caching the new function and calling it directly when asked to format a name to the @@ -662,7 +662,7 @@ class NameDisplay(object): def fn(first, raw_surname_list, suffix, title, call,): return "%s %s" % (first,suffix) - + Specific symbols for parts of a name are defined (keywords given): 't' : title = title 'f' : given = given (first names) @@ -675,7 +675,7 @@ class NameDisplay(object): '1m': primary[sur]= surname primary surname (main) '2m': primary[con]= connector primary surname (main) 'y' : patronymic = pa/matronymic surname (father/mother) - assumed unique - '0y': patronymic[pre] = prefix " + '0y': patronymic[pre] = prefix " '1y': patronymic[sur] = surname " '2y': patronymic[con] = connector " 'o' : notpatronymic = surnames without pa/matronymic and primary @@ -691,48 +691,48 @@ class NameDisplay(object): # we need the names of each of the variables or methods that are # called to fill in each format flag. # Dictionary is "code": ("expression", "keyword", "i18n-keyword") - d = {"t": ("title", "title", + d = {"t": ("title", "title", _("Person|title")), - "f": ("first", "given", + "f": ("first", "given", _("given")), "l": ("_raw_full_surname(raw_surname_list)", "surname", _("surname")), - "s": ("suffix", "suffix", + "s": ("suffix", "suffix", _("suffix")), - "c": ("call", "call", + "c": ("call", "call", _("Name|call")), - "x": ("(nick or call or first.split(' ')[0])", "common", + "x": ("(nick or call or first.split(' ')[0])", "common", _("Name|common")), "i": ("''.join([word[0] +'.' for word in ('. ' + first).split()][1:])", - "initials", + "initials", _("initials")), - "m": ("_raw_primary_surname(raw_surname_list)", "primary", + "m": ("_raw_primary_surname(raw_surname_list)", "primary", _("Name|primary")), - "0m":("_raw_primary_prefix_only(raw_surname_list)", + "0m":("_raw_primary_prefix_only(raw_surname_list)", "primary[pre]", _("primary[pre]")), - "1m":("_raw_primary_surname_only(raw_surname_list)", + "1m":("_raw_primary_surname_only(raw_surname_list)", "primary[sur]",_("primary[sur]")), - "2m":("_raw_primary_conn_only(raw_surname_list)", + "2m":("_raw_primary_conn_only(raw_surname_list)", "primary[con]", _("primary[con]")), - "y": ("_raw_patro_surname(raw_surname_list)", "patronymic", + "y": ("_raw_patro_surname(raw_surname_list)", "patronymic", _("patronymic")), - "0y":("_raw_patro_prefix_only(raw_surname_list)", "patronymic[pre]", + "0y":("_raw_patro_prefix_only(raw_surname_list)", "patronymic[pre]", _("patronymic[pre]")), - "1y":("_raw_patro_surname_only(raw_surname_list)", "patronymic[sur]", + "1y":("_raw_patro_surname_only(raw_surname_list)", "patronymic[sur]", _("patronymic[sur]")), - "2y":("_raw_patro_conn_only(raw_surname_list)", "patronymic[con]", + "2y":("_raw_patro_conn_only(raw_surname_list)", "patronymic[con]", _("patronymic[con]")), - "o": ("_raw_nonpatro_surname(raw_surname_list)", "notpatronymic", + "o": ("_raw_nonpatro_surname(raw_surname_list)", "notpatronymic", _("notpatronymic")), - "r": ("_raw_nonprimary_surname(raw_surname_list)", "rest", + "r": ("_raw_nonprimary_surname(raw_surname_list)", "rest", _("Remaining names|rest")), - "p": ("_raw_prefix_surname(raw_surname_list)", "prefix", + "p": ("_raw_prefix_surname(raw_surname_list)", "prefix", _("prefix")), - "q": ("_raw_single_surname(raw_surname_list)", "rawsurnames", + "q": ("_raw_single_surname(raw_surname_list)", "rawsurnames", _("rawsurnames")), - "n": ("nick", "nickname", + "n": ("nick", "nickname", _("nickname")), - "g": ("famnick", "familynick", + "g": ("famnick", "familynick", _("familynick")), } args = "first,raw_surname_list,suffix,title,call,nick,famnick" @@ -749,7 +749,7 @@ class NameDisplay(object): Format a name from the raw name list. To make this as fast as possible this uses :func:`_gen_raw_func` to generate a new method for each new format_string. - + Is does not call :meth:`_format_str_base` because it would introduce an extra method call and we need all the speed we can squeeze out of this. """ @@ -777,10 +777,10 @@ class NameDisplay(object): '%1m': surname primary surname (main) '%2m': connector primary surname (main) '%y' : pa/matronymic surname (father/mother) - assumed unique - '%0y': prefix " + '%0y': prefix " '%1y': surname " '%2y': connector " - '%o' : surnames without patronymic + '%o' : surnames without patronymic '%r' : non-primary surnames (rest) '%p' : list of all prefixes '%q' : surnames without prefixes and connectors @@ -802,7 +802,7 @@ class NameDisplay(object): raise NameDisplayError("Incomplete format string") return s - + #------------------------------------------------------------------------- def primary_surname(self, name): @@ -944,7 +944,7 @@ class NameDisplay(object): Return the name under which to group this person. This is defined as: 1. if group name is defined on primary name, use that - 2. if group name is defined for the primary surname of the primary + 2. if group name is defined for the primary surname of the primary name, use that 3. use primary surname of primary name otherwise """ @@ -953,11 +953,11 @@ class NameDisplay(object): def name_grouping_name(self, db, pn): """ Return the name under which to group. This is defined as: - + 1. if group name is defined, use that 2. if group name is defined for the primary surname, use that 3. use primary surname itself otherwise - + :param pn: :class:`~.name.Name` object :type pn: :class:`~.name.Name` instance :returns: Returns the groupname string representation @@ -974,7 +974,7 @@ class NameDisplay(object): 1. if group name is defined, use that 2. if group name is defined for the primary surname, use that 3. use primary surname itself otherwise - + :param pn: raw unserialized data of name :type pn: tuple :returns: Returns the groupname string representation @@ -997,7 +997,7 @@ class NameDisplay(object): # %codes (ie, replace "irstnamefay" with "%f", and # "IRSTNAMEFAY" for %F) - if (len(format_str) > 2 and + if (len(format_str) > 2 and format_str[0] == format_str[-1] == '"'): pass else: @@ -1013,7 +1013,7 @@ class NameDisplay(object): # Just replace keywords with # %codes (ie, replace "firstname" with "%f", and # "FIRSTNAME" for %F) - if (len(format_str) > 2 and + if (len(format_str) > 2 and format_str[0] == format_str[-1] == '"'): pass else: @@ -1047,20 +1047,20 @@ class NameDisplay(object): ] new_fmt = format_str - # replace the specific format string flags with a + # replace the specific format string flags with a # flag that works in standard python format strings. new_fmt = re.sub("|".join(patterns), "%s", new_fmt) # replace special meaning codes we need to have verbatim in output if (len(new_fmt) > 2 and new_fmt[0] == new_fmt[-1] == '"'): - new_fmt = new_fmt.replace('\\', r'\\') + new_fmt = new_fmt.replace('\\', r'\\') new_fmt = new_fmt[1:-1].replace('"', r'\"') else: new_fmt = new_fmt.replace('\\', r'\\') new_fmt = new_fmt.replace('"', '\\\"') # find each format flag in the original format string - # for each one we find the variable name that is needed to + # for each one we find the variable name that is needed to # replace it and add this to a list. This list will be used to # generate the replacement tuple. diff --git a/gramps/gen/errors.py b/gramps/gen/errors.py index 6d8018b7e..7816e3394 100644 --- a/gramps/gen/errors.py +++ b/gramps/gen/errors.py @@ -28,7 +28,7 @@ class FilterError(Exception): Exception.__init__(self) self.value = value self.value2 = value2 - + def __str__(self): "Return string representation" return self.value diff --git a/gramps/gen/filters/__init__.py b/gramps/gen/filters/__init__.py index baea6bd32..745dcac7b 100644 --- a/gramps/gen/filters/__init__.py +++ b/gramps/gen/filters/__init__.py @@ -35,12 +35,12 @@ from ._searchfilter import SearchFilter, ExactSearchFilter #global SystemFilters #SystemFilters = FilterList(SYSTEM_FILTERS) #SystemFilters.load() - + def reload_custom_filters(): global CustomFilters CustomFilters = FilterList(CUSTOM_FILTERS) CustomFilters.load() - + #if not SystemFilters: #reload_system_filters() diff --git a/gramps/gen/filters/_filterlist.py b/gramps/gen/filters/_filterlist.py index 29e19593e..4ec9f8f94 100644 --- a/gramps/gen/filters/_filterlist.py +++ b/gramps/gen/filters/_filterlist.py @@ -49,7 +49,7 @@ class FilterList(object): Container class for managing the generic filters. It stores, saves, and loads the filters. """ - + def __init__(self, file): self.filter_namespaces = {} self.file = os.path.expanduser(file) @@ -57,17 +57,17 @@ class FilterList(object): def get_filters_dict(self, namespace='generic'): """ - This runs every for every item to be matched! + This runs every for every item to be matched! """ if self._cached.get(namespace, None) is None: filters = self.get_filters(namespace) - self._cached[namespace] = dict([(filt.name, filt) for filt + self._cached[namespace] = dict([(filt.name, filt) for filt in filters]) return self._cached[namespace] def get_filters(self, namespace='generic'): """ - This runs every for every item to be matched! + This runs every for every item to be matched! """ if namespace in self.filter_namespaces: filters = self.filter_namespaces[namespace] @@ -94,7 +94,7 @@ class FilterList(object): def add(self, namespace, filt): assert(isinstance(namespace, str)) - + if namespace not in self.filter_namespaces: self.filter_namespaces[namespace] = [] self.filter_namespaces[namespace].append(filt) diff --git a/gramps/gen/filters/_filterparser.py b/gramps/gen/filters/_filterparser.py index 85a2f9c6e..42cdd4212 100644 --- a/gramps/gen/filters/_filterparser.py +++ b/gramps/gen/filters/_filterparser.py @@ -42,7 +42,7 @@ from . import rules #------------------------------------------------------------------------- class FilterParser(handler.ContentHandler): """Parses the XML file and builds the list of filters""" - + def __init__(self, gfilter_list): handler.ContentHandler.__init__(self) self.gfilter_list = gfilter_list @@ -52,7 +52,7 @@ class FilterParser(handler.ContentHandler): self.cname = None self.namespace = 'Person' self.use_regex = False - + def setDocumentLocator(self, locator): self.locator = locator @@ -132,9 +132,9 @@ class FilterParser(handler.ContentHandler): print(_("ERROR: filter %s could not be correctly loaded. " "Edit the filter!") % self.f.get_name()) return - + self.f.add_rule(rule) - + def characters(self, data): pass @@ -152,7 +152,7 @@ class FilterParser(handler.ContentHandler): [''] + [self.a[4]] + ['', ''] + [self.a[5]] + \ ['', '0'] # New regular expression code in v3.4 - if (self.r in (rules.person.HasNameOf, + if (self.r in (rules.person.HasNameOf, rules.family.FatherHasNameOf, rules.family.MotherHasNameOf, rules.family.ChildHasNameOf) @@ -195,7 +195,7 @@ old_names_2_class = { "Is a child of filter match" : rules.person.IsChildOfFilterMatch, "Is an ancestor of" : rules.person.IsAncestorOf, "Is an ancestor of filter match": rules.person.IsAncestorOfFilterMatch, - "Is an ancestor of person not more than N generations away" : + "Is an ancestor of person not more than N generations away" : rules.person.IsLessThanNthGenerationAncestorOf, "Is an ancestor of person at least N generations away": rules.person.IsMoreThanNthGenerationAncestorOf, diff --git a/gramps/gen/filters/_genericfilter.py b/gramps/gen/filters/_genericfilter.py index 98a5d3668..17942e9b1 100644 --- a/gramps/gen/filters/_genericfilter.py +++ b/gramps/gen/filters/_genericfilter.py @@ -48,7 +48,7 @@ from ..lib.tag import Tag #------------------------------------------------------------------------- class GenericFilter(object): """Filter class that consists of several rules.""" - + logical_functions = ['or', 'and', 'xor', 'one'] def __init__(self, source=None): @@ -77,8 +77,8 @@ class GenericFilter(object): return False def is_empty(self): - return ((len(self.flist) == 0) or - (len(self.flist) == 1 and ((self.flist[0].is_empty() and + return ((len(self.flist) == 0) or + (len(self.flist) == 1 and ((self.flist[0].is_empty() and not self.invert)))) def set_logical_op(self, val): @@ -98,7 +98,7 @@ class GenericFilter(object): def get_name(self, ulocale=glocale): return self.name - + def set_name(self, name): self.name = name @@ -107,7 +107,7 @@ class GenericFilter(object): def get_comment(self): return self.comment - + def add_rule(self, rule): self.flist.append(rule) @@ -131,7 +131,7 @@ class GenericFilter(object): def check_func(self, db, id_list, task, cb_progress=None, tupleind=None): final_list = [] - + if id_list is None: with self.get_cursor(db) as cursor: for handle, data in cursor: @@ -210,7 +210,7 @@ class GenericFilter(object): return found_one def or_test(self, db, person): - return any(rule.apply(db, person) for rule in self.flist) + return any(rule.apply(db, person) for rule in self.flist) def get_check_func(self): try: @@ -228,17 +228,17 @@ class GenericFilter(object): If id_list given, the handles in id_list are used. If not given a database cursor will be used over all entries. - cb_progress is optional. If present it must be a function that takes no - parameters. If cb_progress given, it will be called occasionally to + cb_progress is optional. If present it must be a function that takes no + parameters. If cb_progress given, it will be called occasionally to indicate progress of the filtering. - - If tupleind is given, id_list is supposed to consist of a list of - tuples, with the handle being index tupleind. So + + If tupleind is given, id_list is supposed to consist of a list of + tuples, with the handle being index tupleind. So handle_0 = id_list[0][tupleind] - - :Returns: if id_list given, it is returned with the items that + + :Returns: if id_list given, it is returned with the items that do not match the filter, filtered out. - if id_list not given, all items in the database that + if id_list not given, all items in the database that match the filter are returned as a list of handles """ m = self.get_check_func() @@ -276,7 +276,7 @@ class GenericEventFilter(GenericFilter): def find_from_handle(self, db, handle): return db.get_event_from_handle(handle) - + class GenericSourceFilter(GenericFilter): def __init__(self, source=None): diff --git a/gramps/gen/filters/_searchfilter.py b/gramps/gen/filters/_searchfilter.py index 424de407e..8afab63d9 100644 --- a/gramps/gen/filters/_searchfilter.py +++ b/gramps/gen/filters/_searchfilter.py @@ -42,4 +42,4 @@ class ExactSearchFilter(SearchFilter): def match(self, handle, db): return self.invert ^ (self.func(handle).upper() == self.text.strip()) - + diff --git a/gramps/gen/filters/rules/__init__.py b/gramps/gen/filters/rules/__init__.py index cb32ec0d2..660786fc7 100644 --- a/gramps/gen/filters/rules/__init__.py +++ b/gramps/gen/filters/rules/__init__.py @@ -27,7 +27,7 @@ The following filters are provided in gen.filters.rules. Match given values: _HasCitationBase Citation with a particular value (HasCitation) - also used for Person, Family and Event having a + also used for Person, Family and Event having a particular Citation _HasEventBase Event with a particular value (HasEvent) also used for Family and Person having a particular diff --git a/gramps/gen/filters/rules/_hascitationbase.py b/gramps/gen/filters/rules/_hascitationbase.py index e580eb92d..9a70f84ea 100644 --- a/gramps/gen/filters/rules/_hascitationbase.py +++ b/gramps/gen/filters/rules/_hascitationbase.py @@ -42,12 +42,12 @@ from . import Rule #------------------------------------------------------------------------- class HasCitationBase(Rule): """Rule that checks for a citation with a particular value - + First parameter is [Volume/page, Date, Confidence] """ - labels = [ _('Volume/Page:'), - _('Date:'), + labels = [ _('Volume/Page:'), + _('Date:'), _('Confidence:') ] name = _('Citations matching parameters') description = _("Matches citations with particular parameters") @@ -68,7 +68,7 @@ class HasCitationBase(Rule): if self._apply(dbase, citation): return True return False - + def _apply(self, db, citation): if not self.match_substring(0, citation.get_page()): return False @@ -76,7 +76,7 @@ class HasCitationBase(Rule): if self.date: if not citation.get_date_object().match(self.date): return False - + if self.list[2]: if citation.get_confidence_level() < int(self.list[2]): return False diff --git a/gramps/gen/filters/rules/_haseventbase.py b/gramps/gen/filters/rules/_haseventbase.py index 47a1585ca..861860a65 100644 --- a/gramps/gen/filters/rules/_haseventbase.py +++ b/gramps/gen/filters/rules/_haseventbase.py @@ -46,16 +46,16 @@ class HasEventBase(Rule): """Rule that checks for an event with a particular value.""" - labels = [ 'Event type:', - 'Date:', - 'Place:', + labels = [ 'Event type:', + 'Date:', + 'Place:', 'Description:', 'Main Participants:' ] name = 'Events matching parameters' description = "Matches events with particular parameters" category = _('Event filters') allow_regex = True - + def prepare(self, db): self.date = None if self.list[0]: diff --git a/gramps/gen/filters/rules/_hasgallerybase.py b/gramps/gen/filters/rules/_hasgallerybase.py index 5103c3296..f9f6c2ffa 100644 --- a/gramps/gen/filters/rules/_hasgallerybase.py +++ b/gramps/gen/filters/rules/_hasgallerybase.py @@ -57,7 +57,7 @@ class HasGalleryBase(Rule): self.count_type = 1 # "equal to" self.userSelectedCount = int(self.list[0]) - + def apply(self, db, obj): count = len( obj.get_media_list()) if self.count_type == 0: # "less than" diff --git a/gramps/gen/filters/rules/_hasldsbase.py b/gramps/gen/filters/rules/_hasldsbase.py index 9663714d4..55773cb7c 100644 --- a/gramps/gen/filters/rules/_hasldsbase.py +++ b/gramps/gen/filters/rules/_hasldsbase.py @@ -49,7 +49,7 @@ class HasLDSBase(Rule): name = 'Objects with LDS events' description = "Matches objects with LDS events" category = _('General filters') - + def prepare(self, db): # things we want to do just once, not for every handle if self.list[1] == 'less than': @@ -60,7 +60,7 @@ class HasLDSBase(Rule): self.count_type = 1 # "equal to" self.userSelectedCount = int(self.list[0]) - + def apply(self, db, obj): count = len( obj.get_lds_ord_list()) if self.count_type == 0: # "less than" diff --git a/gramps/gen/filters/rules/_hassourcebase.py b/gramps/gen/filters/rules/_hassourcebase.py index 11094fed3..27290c368 100644 --- a/gramps/gen/filters/rules/_hassourcebase.py +++ b/gramps/gen/filters/rules/_hassourcebase.py @@ -43,8 +43,8 @@ class HasSourceBase(Rule): """Rule that checks for a source with a particular value""" - labels = [ 'Title:', - 'Author:', + labels = [ 'Title:', + 'Author:', 'Abbreviation:', 'Publication:' ] name = 'Sources matching parameters' diff --git a/gramps/gen/filters/rules/_hassourceofbase.py b/gramps/gen/filters/rules/_hassourceofbase.py index 49d58f04b..b79083a54 100644 --- a/gramps/gen/filters/rules/_hassourceofbase.py +++ b/gramps/gen/filters/rules/_hassourceofbase.py @@ -46,7 +46,7 @@ class HasSourceOfBase(Rule): name = 'Object with the ' category = _('Citation/source filters') description = 'Matches objects who have a particular source' - + def prepare(self,db): if self.list[0] == '': self.source_handle = None diff --git a/gramps/gen/filters/rules/_hastextmatchingsubstringof.py b/gramps/gen/filters/rules/_hastextmatchingsubstringof.py index 3f75d45cc..65eda997c 100644 --- a/gramps/gen/filters/rules/_hastextmatchingsubstringof.py +++ b/gramps/gen/filters/rules/_hastextmatchingsubstringof.py @@ -40,7 +40,7 @@ class HasTextMatchingSubstringOf(Rule): """Rule that checks for string matches in any textual information.""" labels = [ 'Substring:', - 'Case sensitive:', + 'Case sensitive:', 'Regular-Expression matching:'] name = 'Objects with records containing ' description = "Matches objects whose records contain text " \ diff --git a/gramps/gen/filters/rules/_matcheseventfilterbase.py b/gramps/gen/filters/rules/_matcheseventfilterbase.py index ddd40830f..c0c220a9b 100644 --- a/gramps/gen/filters/rules/_matcheseventfilterbase.py +++ b/gramps/gen/filters/rules/_matcheseventfilterbase.py @@ -44,7 +44,7 @@ class MatchesEventFilterBase(MatchesFilterBase): This is a base rule for subclassing by specific objects. Subclasses need to define the namespace class attribute. - + """ labels = ['Event filter name:'] @@ -58,12 +58,12 @@ class MatchesEventFilterBase(MatchesFilterBase): def prepare(self, db): MatchesFilterBase.prepare(self, db) - self.MEF_filt = self.find_filter() + self.MEF_filt = self.find_filter() def apply(self, db, object): if self.MEF_filt is None : return False - + eventlist = [x.ref for x in object.get_event_ref_list()] for eventhandle in eventlist: #check if event in event filter diff --git a/gramps/gen/filters/rules/_matchesfilterbase.py b/gramps/gen/filters/rules/_matchesfilterbase.py index 80cacca9b..1be70fc67 100644 --- a/gramps/gen/filters/rules/_matchesfilterbase.py +++ b/gramps/gen/filters/rules/_matchesfilterbase.py @@ -49,7 +49,7 @@ class MatchesFilterBase(Rule): This is a base rule for subclassing by specific objects. Subclasses need to define the namespace class attribute. - + """ labels = [_('Filter name:')] name = 'Objects matching the ' @@ -67,7 +67,7 @@ class MatchesFilterBase(Rule): LOG.warning(_("Can't find filter %s in the defined custom filters") % self.list[0]) else: - LOG.warning(_("Can't find filter %s in the defined custom filters") + LOG.warning(_("Can't find filter %s in the defined custom filters") % self.list[0]) def reset(self): @@ -85,7 +85,7 @@ class MatchesFilterBase(Rule): filt = filters[self.list[0]] return filt.check(db, obj.handle) return False - + def find_filter(self): """ Return the selected filter or None. diff --git a/gramps/gen/filters/rules/_matchessourceconfidencebase.py b/gramps/gen/filters/rules/_matchessourceconfidencebase.py index 7f5d7065b..aeed20d5b 100644 --- a/gramps/gen/filters/rules/_matchessourceconfidencebase.py +++ b/gramps/gen/filters/rules/_matchessourceconfidencebase.py @@ -48,7 +48,7 @@ class MatchesSourceConfidenceBase(Rule): name = 'Object with at least one direct source >= ' description = "Matches objects with at least one direct source with confidence level(s)" category = _('Citation/source filters') - + def apply(self, db, obj): required_conf = int(self.list[0]) for citation_handle in obj.get_citation_list(): diff --git a/gramps/gen/filters/rules/_matchessourcefilterbase.py b/gramps/gen/filters/rules/_matchessourcefilterbase.py index 25eaccf0e..2d0d42c59 100644 --- a/gramps/gen/filters/rules/_matchessourcefilterbase.py +++ b/gramps/gen/filters/rules/_matchessourcefilterbase.py @@ -60,7 +60,7 @@ class MatchesSourceFilterBase(MatchesFilterBase): def apply(self, db, object): if self.MSF_filt is None : return False - + for citation_handle in object.get_citation_list(): citation = db.get_citation_from_handle(citation_handle) sourcehandle = citation.get_reference_handle() diff --git a/gramps/gen/filters/rules/_regexpidbase.py b/gramps/gen/filters/rules/_regexpidbase.py index f6109da15..b662f3c9a 100644 --- a/gramps/gen/filters/rules/_regexpidbase.py +++ b/gramps/gen/filters/rules/_regexpidbase.py @@ -41,7 +41,7 @@ from . import Rule #------------------------------------------------------------------------- class RegExpIdBase(Rule): """ - Objects with a Gramps ID that contains a substring or matches a + Objects with a Gramps ID that contains a substring or matches a regular expression. """ diff --git a/gramps/gen/filters/rules/_rule.py b/gramps/gen/filters/rules/_rule.py index bdf8f8a3a..0f4b987b0 100644 --- a/gramps/gen/filters/rules/_rule.py +++ b/gramps/gen/filters/rules/_rule.py @@ -64,11 +64,11 @@ class Rule(object): def is_empty(self): return False - + def requestprepare(self, dbase): """ Request that the prepare method of the rule is executed if needed - + Special: Custom Filters have fixed values, so only one instance needs to exists during a search. It is stored in a FilterStore, and initialized once. @@ -98,7 +98,7 @@ class Rule(object): def requestreset(self): """ Request that the reset method of the rule is executed if possible - + Special: Custom Filters have fixed values, so only one instance needs to exists during a search. It is stored in a FilterStore, and initialized once. @@ -113,7 +113,7 @@ class Rule(object): def reset(self): """remove no longer needed memory""" pass - + def set_list(self, arg): """Store the values of this rule.""" assert isinstance(arg, list) or arg is None, "Argument is not a list" @@ -126,7 +126,7 @@ class Rule(object): def values(self): """Return the values used by this rule.""" return self.list - + def check(self): """Verify the number of rule values versus the number of rule labels.""" return len(self.list) == len(self.labels) diff --git a/gramps/gen/filters/rules/citation/__init__.py b/gramps/gen/filters/rules/citation/__init__.py index 041b03ea0..d1314d37b 100644 --- a/gramps/gen/filters/rules/citation/__init__.py +++ b/gramps/gen/filters/rules/citation/__init__.py @@ -61,7 +61,7 @@ editor_rule_list = [ MatchesFilter, MatchesPageSubstringOf, MatchesRepositoryFilter, - MatchesSourceFilter, + MatchesSourceFilter, RegExpIdOf, RegExpSourceIdOf, HasTag diff --git a/gramps/gen/filters/rules/citation/_hascitation.py b/gramps/gen/filters/rules/citation/_hascitation.py index 8fcc7acba..97f1084f3 100644 --- a/gramps/gen/filters/rules/citation/_hascitation.py +++ b/gramps/gen/filters/rules/citation/_hascitation.py @@ -45,8 +45,8 @@ from ....datehandler import parser class HasCitation(Rule): """Rule that checks for a citations with a particular value""" - labels = [ _('Volume/Page:'), - _('Date:'), + labels = [ _('Volume/Page:'), + _('Date:'), _('Confidence level:')] name = _('Citations matching parameters') category = _('General filters') @@ -68,7 +68,7 @@ class HasCitation(Rule): if self.date: if not citation.get_date_object().match(self.date): return False - + if self.list[2]: if citation.get_confidence_level() < int(self.list[2]): return False diff --git a/gramps/gen/filters/rules/citation/_hassource.py b/gramps/gen/filters/rules/citation/_hassource.py index 8b98323a0..e1570d2d6 100644 --- a/gramps/gen/filters/rules/citation/_hassource.py +++ b/gramps/gen/filters/rules/citation/_hassource.py @@ -45,15 +45,15 @@ from .._hassourcebase import HasSourceBase class HasSource(HasSourceBase): """Rule that checks for an citation with a particular value""" - labels = [ _('Title:'), - _('Author:'), + labels = [ _('Title:'), + _('Author:'), _('Abbreviation:'), _('Publication:') ] name = _('Sources matching parameters') description = _("Matches citations with a source of a particular " "value") category = _('Source filters') - + def apply(self, dbase, citation): source = dbase.get_source_from_handle( citation.get_reference_handle()) diff --git a/gramps/gen/filters/rules/citation/_matchesrepositoryfilter.py b/gramps/gen/filters/rules/citation/_matchesrepositoryfilter.py index cf30f08b7..f9905d3f6 100644 --- a/gramps/gen/filters/rules/citation/_matchesrepositoryfilter.py +++ b/gramps/gen/filters/rules/citation/_matchesrepositoryfilter.py @@ -48,19 +48,19 @@ class MatchesRepositoryFilter(MatchesFilterBase): description = _("Matches citations with sources with a repository " "reference that match a certain repository filter") category = _('General filters') - + # we want to have this filter show repository filters namespace = 'Repository' - - + + def prepare(self, db): MatchesFilterBase.prepare(self, db) self.MRF_filt = self.find_filter() - + def apply(self, db, object): if self.MRF_filt is None : return False - + source_handle = object.source_handle source = db.get_source_from_handle(source_handle) repolist = [x.ref for x in source.get_reporef_list()] diff --git a/gramps/gen/filters/rules/citation/_matchessourcefilter.py b/gramps/gen/filters/rules/citation/_matchessourcefilter.py index 0a5ba7a64..f82621d3e 100644 --- a/gramps/gen/filters/rules/citation/_matchessourcefilter.py +++ b/gramps/gen/filters/rules/citation/_matchessourcefilter.py @@ -57,11 +57,11 @@ class MatchesSourceFilter(MatchesFilterBase): def prepare(self, db): MatchesFilterBase.prepare(self, db) self.MRF_filt = self.find_filter() - + def apply(self, db, object): if self.MRF_filt is None : return False - + source_handle = object.source_handle if self.MRF_filt.check(db, source_handle): return True diff --git a/gramps/gen/filters/rules/event/__init__.py b/gramps/gen/filters/rules/event/__init__.py index 3655e8be4..41ce604dc 100644 --- a/gramps/gen/filters/rules/event/__init__.py +++ b/gramps/gen/filters/rules/event/__init__.py @@ -55,7 +55,7 @@ editor_rule_list = [ HasIdOf, HasGallery, RegExpIdOf, - HasCitation, + HasCitation, HasNote, HasNoteRegexp, HasReferenceCountOf, diff --git a/gramps/gen/filters/rules/event/_hascitation.py b/gramps/gen/filters/rules/event/_hascitation.py index 5ad0a8c72..2eb579de8 100644 --- a/gramps/gen/filters/rules/event/_hascitation.py +++ b/gramps/gen/filters/rules/event/_hascitation.py @@ -45,8 +45,8 @@ from .._hascitationbase import HasCitationBase class HasCitation(HasCitationBase): """Rule that checks for an event with a particular value""" - labels = [ _('Volume/Page:'), - _('Date:'), + labels = [ _('Volume/Page:'), + _('Date:'), _('Confidence level:')] name = _('Events with the ') description = _("Matches events with a citation of a particular " diff --git a/gramps/gen/filters/rules/event/_hasdata.py b/gramps/gen/filters/rules/event/_hasdata.py index a28f99d36..3a4f0d545 100644 --- a/gramps/gen/filters/rules/event/_hasdata.py +++ b/gramps/gen/filters/rules/event/_hasdata.py @@ -50,7 +50,7 @@ class HasData(Rule): description = _("Matches events with data of a particular value") category = _('General filters') allow_regex = True - + def prepare(self, dbase): self.event_type = self.list[0] self.date = self.list[1] @@ -61,7 +61,7 @@ class HasData(Rule): if self.date: self.date = parser.parse(self.date) - + def apply(self, db, event): if self.event_type and event.get_type() != self.event_type: # No match diff --git a/gramps/gen/filters/rules/event/_matchespersonfilter.py b/gramps/gen/filters/rules/event/_matchespersonfilter.py index 79c0a405f..269d6a372 100644 --- a/gramps/gen/filters/rules/event/_matchespersonfilter.py +++ b/gramps/gen/filters/rules/event/_matchespersonfilter.py @@ -44,7 +44,7 @@ class MatchesPersonFilter(MatchesFilterBase): This is a base rule for subclassing by specific objects. Subclasses need to define the namespace class attribute. - + """ labels = [_('Person filter name:'), _('Include Family events:')] @@ -52,13 +52,13 @@ class MatchesPersonFilter(MatchesFilterBase): description = _("Matches events of persons matched by the specified " "person filter name") category = _('General filters') - + # we want to have this filter show person filters namespace = 'Person' - + def prepare(self, db): MatchesFilterBase.prepare(self, db) - + try : if int(self.list[1]): self.MPF_famevents = True @@ -80,11 +80,11 @@ class MatchesPersonFilter(MatchesFilterBase): for (classname, handle) in db.find_backlink_handles( event.get_handle(), ['Family']): family = db.get_family_from_handle(handle) - if family.father_handle and filt.check(db, + if family.father_handle and filt.check(db, family.father_handle) : return True - if family.mother_handle and filt.check(db, + if family.mother_handle and filt.check(db, family.mother_handle) : return True - + return False diff --git a/gramps/gen/filters/rules/family/__init__.py b/gramps/gen/filters/rules/family/__init__.py index 5810c6126..8b7fd2425 100644 --- a/gramps/gen/filters/rules/family/__init__.py +++ b/gramps/gen/filters/rules/family/__init__.py @@ -72,7 +72,7 @@ editor_rule_list = [ HasReferenceCountOf, HasSourceCount, HasSourceOf, - HasCitation, + HasCitation, FamilyPrivate, HasEvent, HasAttribute, diff --git a/gramps/gen/filters/rules/family/_hascitation.py b/gramps/gen/filters/rules/family/_hascitation.py index c0cf05f94..cc6911fb5 100644 --- a/gramps/gen/filters/rules/family/_hascitation.py +++ b/gramps/gen/filters/rules/family/_hascitation.py @@ -45,8 +45,8 @@ from .._hascitationbase import HasCitationBase class HasCitation(HasCitationBase): """Rule that checks for a family with a particular value""" - labels = [ _('Volume/Page:'), - _('Date:'), + labels = [ _('Volume/Page:'), + _('Date:'), _('Confidence level:')] name = _('Families with the ') description = _("Matches families with a citation of a particular " diff --git a/gramps/gen/filters/rules/family/_hasevent.py b/gramps/gen/filters/rules/family/_hasevent.py index 0ee51eeac..aeb61d19c 100644 --- a/gramps/gen/filters/rules/family/_hasevent.py +++ b/gramps/gen/filters/rules/family/_hasevent.py @@ -44,9 +44,9 @@ from .._haseventbase import HasEventBase class HasEvent(HasEventBase): """Rule that checks for a family event with a particular value""" - labels = [ _('Family event:'), - _('Date:'), - _('Place:'), + labels = [ _('Family event:'), + _('Date:'), + _('Place:'), _('Description:'), _('Main Participants') ] name = _('Families with the ') diff --git a/gramps/gen/filters/rules/family/_isbookmarked.py b/gramps/gen/filters/rules/family/_isbookmarked.py index 9cf7b7836..400b4b609 100644 --- a/gramps/gen/filters/rules/family/_isbookmarked.py +++ b/gramps/gen/filters/rules/family/_isbookmarked.py @@ -25,7 +25,7 @@ #------------------------------------------------------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext - + #------------------------------------------------------------------------- # # GRAMPS modules diff --git a/gramps/gen/filters/rules/media/__init__.py b/gramps/gen/filters/rules/media/__init__.py index edacf8b5d..70c055d7f 100644 --- a/gramps/gen/filters/rules/media/__init__.py +++ b/gramps/gen/filters/rules/media/__init__.py @@ -41,7 +41,7 @@ from ._hastag import HasTag editor_rule_list = [ AllMedia, - HasCitation, + HasCitation, HasIdOf, RegExpIdOf, HasNoteRegexp, diff --git a/gramps/gen/filters/rules/media/_hascitation.py b/gramps/gen/filters/rules/media/_hascitation.py index 03d093940..bf1d51781 100644 --- a/gramps/gen/filters/rules/media/_hascitation.py +++ b/gramps/gen/filters/rules/media/_hascitation.py @@ -44,8 +44,8 @@ from .._hascitationbase import HasCitationBase class HasCitation(HasCitationBase): """Rule that checks for a person with a particular value""" - labels = [ _('Volume/Page:'), - _('Date:'), + labels = [ _('Volume/Page:'), + _('Date:'), _('Confidence level:')] name = _('Media with the ') description = _("Matches media with a citation of a particular " diff --git a/gramps/gen/filters/rules/media/_hasmedia.py b/gramps/gen/filters/rules/media/_hasmedia.py index 0ea6d8782..ab00433a7 100644 --- a/gramps/gen/filters/rules/media/_hasmedia.py +++ b/gramps/gen/filters/rules/media/_hasmedia.py @@ -43,10 +43,10 @@ class HasMedia(Rule): """Rule that checks for a media with a particular value""" - labels = [ _('Title:'), - _('Type:'), + labels = [ _('Title:'), + _('Type:'), _('Path:'), - _('Date:'), + _('Date:'), ] name = _('Media objects matching parameters') description = _("Matches media objects with particular parameters") diff --git a/gramps/gen/filters/rules/note/_hasnote.py b/gramps/gen/filters/rules/note/_hasnote.py index cfcf8e118..4265b2504 100644 --- a/gramps/gen/filters/rules/note/_hasnote.py +++ b/gramps/gen/filters/rules/note/_hasnote.py @@ -43,8 +43,8 @@ class HasNote(Rule): """Rule that checks for a note with a particular value""" - labels = [ _('Text:'), - _('Note type:'), + labels = [ _('Text:'), + _('Note type:'), ] name = _('Notes matching parameters') description = _("Matches Notes with particular parameters") diff --git a/gramps/gen/filters/rules/person/__init__.py b/gramps/gen/filters/rules/person/__init__.py index dbbad738d..7deba8f10 100644 --- a/gramps/gen/filters/rules/person/__init__.py +++ b/gramps/gen/filters/rules/person/__init__.py @@ -134,7 +134,7 @@ editor_rule_list = [ HasRelationship, HasDeath, HasBirth, - HasCitation, + HasCitation, HasEvent, HasFamilyEvent, HasAttribute, diff --git a/gramps/gen/filters/rules/person/_deeprelationshippathbetween.py b/gramps/gen/filters/rules/person/_deeprelationshippathbetween.py index 803bd16da..647ce18ee 100644 --- a/gramps/gen/filters/rules/person/_deeprelationshippathbetween.py +++ b/gramps/gen/filters/rules/person/_deeprelationshippathbetween.py @@ -57,26 +57,26 @@ def filter_database(db, progress, filter_name): progress.step() filt.requestreset() - + return matches def get_family_handle_people(db, exclude_handle, family_handle): people = set() - + family = db.get_family_from_handle(family_handle) def possibly_add_handle(h): if h != None and h != exclude_handle: people.add(db.get_person_from_handle(h)) - + possibly_add_handle(family.get_father_handle()) possibly_add_handle(family.get_mother_handle()) for child_ref in family.get_child_ref_list(): if child_ref: possibly_add_handle(child_ref.get_reference_handle()) - + return people def get_person_family_people(db, person, person_handle): @@ -85,16 +85,16 @@ def get_person_family_people(db, person, person_handle): def add_family_handle_list(list): for family_handle in list: people.update(get_family_handle_people(db, person_handle, family_handle)) - + add_family_handle_list(person.get_family_handle_list()) add_family_handle_list(person.get_parent_family_handle_list()) - + return people def find_deep_relations(db, progress, person, path, seen, target_people): if len(target_people) < 1: return [] - + handle = person.get_handle() if handle in seen: return [] @@ -102,7 +102,7 @@ def find_deep_relations(db, progress, person, path, seen, target_people): return_paths = [] person_path = path + [handle] - + if handle in target_people: return_paths += [person_path] target_people.remove(handle) @@ -126,16 +126,16 @@ class DeepRelationshipPathBetween(Rule): " with a filter. This produces a set of relationship paths (including" " by marriage) between the specified person and the target people." " Each path is not necessarily the shortest path.") - + def prepare(self, db): # FIXME: this should user the User class from gramps.gui.utils import ProgressMeter root_person_id = self.list[0] root_person = db.get_person_from_gramps_id(root_person_id) - + progress = ProgressMeter(_('Finding relationship paths')) progress.set_pass(header=_('Evaluating people'), mode=ProgressMeter.MODE_ACTIVITY) - + filter_name = self.list[1] target_people = filter_database(db, progress, filter_name) @@ -143,10 +143,10 @@ class DeepRelationshipPathBetween(Rule): progress.close() progress = None - + self.__matches = set() list(map(self.__matches.update, paths)) - + def reset(self): self.__matches = set() diff --git a/gramps/gen/filters/rules/person/_hasaddress.py b/gramps/gen/filters/rules/person/_hasaddress.py index 02cda0a8c..bdf8a0121 100644 --- a/gramps/gen/filters/rules/person/_hasaddress.py +++ b/gramps/gen/filters/rules/person/_hasaddress.py @@ -50,7 +50,7 @@ class HasAddress(Rule): description = _("Matches people with a certain number of personal addresses") category = _('General filters') - + def prepare(self, db): # things we want to do just once, not for every handle if self.list[1] == 'less than': @@ -61,7 +61,7 @@ class HasAddress(Rule): self.count_type = 1 # "equal to" self.userSelectedCount = int(self.list[0]) - + def apply(self, db, person): count = len( person.get_address_list()) if self.count_type == 0: # "less than" diff --git a/gramps/gen/filters/rules/person/_hasassociation.py b/gramps/gen/filters/rules/person/_hasassociation.py index 4500e2845..58b9a126a 100644 --- a/gramps/gen/filters/rules/person/_hasassociation.py +++ b/gramps/gen/filters/rules/person/_hasassociation.py @@ -49,7 +49,7 @@ class HasAssociation(Rule): name = _('People with associations') description = _("Matches people with a certain number of associations") category = _('General filters') - + def prepare(self, db): # things we want to do just once, not for every handle if self.list[1] == 'less than': @@ -60,7 +60,7 @@ class HasAssociation(Rule): self.count_type = 1 # "equal to" self.selected_count = int(self.list[0]) - + def apply(self, db, person): count = len(person.get_person_ref_list()) if self.count_type == 0: # "less than" diff --git a/gramps/gen/filters/rules/person/_hasbirth.py b/gramps/gen/filters/rules/person/_hasbirth.py index b82328dac..bd3f5ae05 100644 --- a/gramps/gen/filters/rules/person/_hasbirth.py +++ b/gramps/gen/filters/rules/person/_hasbirth.py @@ -50,13 +50,13 @@ class HasBirth(Rule): description = _("Matches people with birth data of a particular value") category = _('Event filters') allow_regex = True - + def prepare(self, db): if self.list[0]: self.date = parser.parse(self.list[0]) else: self.date = None - + def apply(self,db,person): for event_ref in person.get_event_ref_list(): if not event_ref: diff --git a/gramps/gen/filters/rules/person/_hascitation.py b/gramps/gen/filters/rules/person/_hascitation.py index adf742b7c..7e4e9999a 100644 --- a/gramps/gen/filters/rules/person/_hascitation.py +++ b/gramps/gen/filters/rules/person/_hascitation.py @@ -44,8 +44,8 @@ from .._hascitationbase import HasCitationBase class HasCitation(HasCitationBase): """Rule that checks for a person with a particular value""" - labels = [ _('Volume/Page:'), - _('Date:'), + labels = [ _('Volume/Page:'), + _('Date:'), _('Confidence level:')] name = _('People with the ') description = _("Matches people with a citation of a particular " diff --git a/gramps/gen/filters/rules/person/_hascommonancestorwith.py b/gramps/gen/filters/rules/person/_hascommonancestorwith.py index e74f4baa8..b63772081 100644 --- a/gramps/gen/filters/rules/person/_hascommonancestorwith.py +++ b/gramps/gen/filters/rules/person/_hascommonancestorwith.py @@ -93,9 +93,9 @@ class HasCommonAncestorWith(Rule): def has_common_ancestor(self, other): for handle in self.with_people: - if ((handle in self.ancestor_cache and - self.ancestor_cache[handle]) & - (other and other.handle in self.ancestor_cache and + if ((handle in self.ancestor_cache and + self.ancestor_cache[handle]) & + (other and other.handle in self.ancestor_cache and self.ancestor_cache[other.handle])): return True return False diff --git a/gramps/gen/filters/rules/person/_hasdeath.py b/gramps/gen/filters/rules/person/_hasdeath.py index 7acbb9115..9ec24e3dc 100644 --- a/gramps/gen/filters/rules/person/_hasdeath.py +++ b/gramps/gen/filters/rules/person/_hasdeath.py @@ -50,7 +50,7 @@ class HasDeath(Rule): description = _("Matches people with death data of a particular value") category = _('Event filters') allow_regex = True - + def prepare(self, db): if self.list[0]: self.date = parser.parse(self.list[0]) diff --git a/gramps/gen/filters/rules/person/_hasevent.py b/gramps/gen/filters/rules/person/_hasevent.py index 379777f5d..520e3c1c7 100644 --- a/gramps/gen/filters/rules/person/_hasevent.py +++ b/gramps/gen/filters/rules/person/_hasevent.py @@ -45,16 +45,16 @@ from .._haseventbase import HasEventBase class HasEvent(HasEventBase): """Rule that checks for a person with a particular value""" - labels = [ _('Personal event:'), - _('Date:'), - _('Place:'), + labels = [ _('Personal event:'), + _('Date:'), + _('Place:'), _('Description:'), _('Main Participants:'), _('Primary Role:') ] name = _('People with the personal ') description = _("Matches people with a personal event of a particular " "value") - + def apply(self, dbase, person): for event_ref in person.get_event_ref_list(): if not event_ref: diff --git a/gramps/gen/filters/rules/person/_hasfamilyattribute.py b/gramps/gen/filters/rules/person/_hasfamilyattribute.py index af391f2fd..19fecf322 100644 --- a/gramps/gen/filters/rules/person/_hasfamilyattribute.py +++ b/gramps/gen/filters/rules/person/_hasfamilyattribute.py @@ -47,7 +47,7 @@ class HasFamilyAttribute(Rule): "of a particular value") category = _('General filters') allow_regex = True - + def apply(self,db,person): if not self.list[0]: return False diff --git a/gramps/gen/filters/rules/person/_hasfamilyevent.py b/gramps/gen/filters/rules/person/_hasfamilyevent.py index 0fabddcde..2377b7e47 100644 --- a/gramps/gen/filters/rules/person/_hasfamilyevent.py +++ b/gramps/gen/filters/rules/person/_hasfamilyevent.py @@ -45,15 +45,15 @@ class HasFamilyEvent(Rule): """Rule that checks for a person who has a relationship event with a particular value""" - labels = [ _('Family event:'), - _('Date:'), - _('Place:'), + labels = [ _('Family event:'), + _('Date:'), + _('Place:'), _('Description:') ] name = _('People with the family ') description = _("Matches people with a family event of a particular value") category = _('Event filters') allow_regex = True - + def prepare(self,db): self.date = None try: @@ -93,7 +93,7 @@ class HasFamilyEvent(Rule): val = 0 else: val = 0 - + if val == 1: return True return False diff --git a/gramps/gen/filters/rules/person/_hasnameorigintype.py b/gramps/gen/filters/rules/person/_hasnameorigintype.py index f258fcc3a..536e0d2c6 100644 --- a/gramps/gen/filters/rules/person/_hasnameorigintype.py +++ b/gramps/gen/filters/rules/person/_hasnameorigintype.py @@ -1,7 +1,7 @@ # # Gramps - a GTK+/GNOME based genealogy program # -# Copyright (C) 2010 Gramps +# Copyright (C) 2010 Gramps # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/gramps/gen/filters/rules/person/_hasnametype.py b/gramps/gen/filters/rules/person/_hasnametype.py index 2ca1ad438..58cd6bef0 100644 --- a/gramps/gen/filters/rules/person/_hasnametype.py +++ b/gramps/gen/filters/rules/person/_hasnametype.py @@ -1,7 +1,7 @@ # # Gramps - a GTK+/GNOME based genealogy program # -# Copyright (C) 2010 Gramps +# Copyright (C) 2010 Gramps # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by diff --git a/gramps/gen/filters/rules/person/_hasnickname.py b/gramps/gen/filters/rules/person/_hasnickname.py index 37bc99f26..645b757c1 100644 --- a/gramps/gen/filters/rules/person/_hasnickname.py +++ b/gramps/gen/filters/rules/person/_hasnickname.py @@ -47,6 +47,6 @@ class HasNickname(Rule): category = _('General filters') def apply(self, db, person): - if person.get_nick_name(): + if person.get_nick_name(): return True return False diff --git a/gramps/gen/filters/rules/person/_hastextmatchingregexpof.py b/gramps/gen/filters/rules/person/_hastextmatchingregexpof.py index e948a5185..a0315651b 100644 --- a/gramps/gen/filters/rules/person/_hastextmatchingregexpof.py +++ b/gramps/gen/filters/rules/person/_hastextmatchingregexpof.py @@ -35,9 +35,9 @@ from ._hastextmatchingsubstringof import HasTextMatchingSubstringOf # "HasTextMatchingRegexOf" #------------------------------------------------------------------------- class HasTextMatchingRegexpOf(HasTextMatchingSubstringOf): - """This is wrapping HasTextMatchingSubstringOf to enable the regex_match + """This is wrapping HasTextMatchingSubstringOf to enable the regex_match parameter. - + """ def __init__(self, list, use_regex=False): HasTextMatchingSubstringOf.__init__(self, list, use_regex) diff --git a/gramps/gen/filters/rules/person/_hastextmatchingsubstringof.py b/gramps/gen/filters/rules/person/_hastextmatchingsubstringof.py index 987079c67..7903c8023 100644 --- a/gramps/gen/filters/rules/person/_hastextmatchingsubstringof.py +++ b/gramps/gen/filters/rules/person/_hastextmatchingsubstringof.py @@ -92,7 +92,7 @@ class HasTextMatchingSubstringOf(Rule): # Look for matching families if any(self.search_family(family_handle) - for family_handle in person.get_family_handle_list()): + for family_handle in person.get_family_handle_list()): return True # Look for matching media objects @@ -100,7 +100,7 @@ class HasTextMatchingSubstringOf(Rule): for media_ref in person.get_media_list()): return True return False - + def search_family(self,family_handle): if not family_handle: return False @@ -169,7 +169,7 @@ class HasTextMatchingSubstringOf(Rule): if repo and self.match_object(repo) ) - + def cache_sources(self): # search all sources and match all referents of a matching source for source in self.db.iter_sources(): @@ -185,18 +185,18 @@ class HasTextMatchingSubstringOf(Rule): (match, self.list[0], source.gramps_id)) (citation_list, citation_referents_list) = \ get_source_and_citation_referents(source.handle, self.db) - LOG.debug("the_lists %s %s" % + LOG.debug("the_lists %s %s" % (citation_list, citation_referents_list)) for (citation_handle, refs) in citation_referents_list: citation = self.db.get_citation_from_handle(citation_handle) LOG.debug("cache_sources match %s matchcitation %s string %s" " source %s citation %s" % - (match, self.match_object(citation), - self.list[0], source.gramps_id, + (match, self.match_object(citation), + self.list[0], source.gramps_id, citation.gramps_id)) if match or self.match_object(citation): # Update the maps to reflect the reference - (person_list, family_list, event_list, place_list, + (person_list, family_list, event_list, place_list, source_list, media_list, repo_list) = refs self.person_map.update(person_list) self.family_map.update(family_list) diff --git a/gramps/gen/filters/rules/person/_isancestorof.py b/gramps/gen/filters/rules/person/_isancestorof.py index 734a1fcb2..30d8e5fde 100644 --- a/gramps/gen/filters/rules/person/_isancestorof.py +++ b/gramps/gen/filters/rules/person/_isancestorof.py @@ -73,13 +73,13 @@ class IsAncestorOf(Rule): return if not first: self.map.add(person.handle) - + fam_id = person.get_main_parents_family_handle() fam = db.get_family_from_handle(fam_id) if fam: f_id = fam.get_father_handle() m_id = fam.get_mother_handle() - + if f_id: self.init_ancestor_list(db,db.get_person_from_handle(f_id),0) if m_id: diff --git a/gramps/gen/filters/rules/person/_isancestoroffiltermatch.py b/gramps/gen/filters/rules/person/_isancestoroffiltermatch.py index 421cbf78c..c20911200 100644 --- a/gramps/gen/filters/rules/person/_isancestoroffiltermatch.py +++ b/gramps/gen/filters/rules/person/_isancestoroffiltermatch.py @@ -59,7 +59,7 @@ class IsAncestorOfFilterMatch(IsAncestorOf): first = 1 except IndexError: first = 1 - + filt = MatchesFilter(self.list[0:1]) filt.requestprepare(db) for person in db.iter_people(): diff --git a/gramps/gen/filters/rules/person/_isbookmarked.py b/gramps/gen/filters/rules/person/_isbookmarked.py index dc53a6d2b..f64de73dc 100644 --- a/gramps/gen/filters/rules/person/_isbookmarked.py +++ b/gramps/gen/filters/rules/person/_isbookmarked.py @@ -26,7 +26,7 @@ #------------------------------------------------------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext - + #------------------------------------------------------------------------- # # GRAMPS modules diff --git a/gramps/gen/filters/rules/person/_isdescendantfamilyof.py b/gramps/gen/filters/rules/person/_isdescendantfamilyof.py index e1c0ec9fc..c354ba458 100644 --- a/gramps/gen/filters/rules/person/_isdescendantfamilyof.py +++ b/gramps/gen/filters/rules/person/_isdescendantfamilyof.py @@ -51,7 +51,7 @@ class IsDescendantFamilyOf(Rule): category = _('Descendant filters') description = _("Matches people that are descendants or the spouse " "of a descendant of a specified person") - + def prepare(self,db): self.db = db self.matches = set() diff --git a/gramps/gen/filters/rules/person/_isdescendantfamilyoffiltermatch.py b/gramps/gen/filters/rules/person/_isdescendantfamilyoffiltermatch.py index 190474ba5..7969549f2 100644 --- a/gramps/gen/filters/rules/person/_isdescendantfamilyoffiltermatch.py +++ b/gramps/gen/filters/rules/person/_isdescendantfamilyoffiltermatch.py @@ -48,7 +48,7 @@ class IsDescendantFamilyOfFilterMatch(IsDescendantFamilyOf): category = _('Descendant filters') description = _("Matches people that are descendants or the spouse " "of anybody matched by a filter") - + def prepare(self,db): self.db = db self.matches = set() diff --git a/gramps/gen/filters/rules/person/_isdescendantof.py b/gramps/gen/filters/rules/person/_isdescendantof.py index 2a917c3b1..cb047fa93 100644 --- a/gramps/gen/filters/rules/person/_isdescendantof.py +++ b/gramps/gen/filters/rules/person/_isdescendantof.py @@ -71,7 +71,7 @@ class IsDescendantOf(Rule): return if not first: self.map.add(person.handle) - + for fam_id in person.get_family_handle_list(): fam = self.db.get_family_from_handle(fam_id) if fam: diff --git a/gramps/gen/filters/rules/person/_isdescendantoffiltermatch.py b/gramps/gen/filters/rules/person/_isdescendantoffiltermatch.py index d0775f66b..d1281a28a 100644 --- a/gramps/gen/filters/rules/person/_isdescendantoffiltermatch.py +++ b/gramps/gen/filters/rules/person/_isdescendantoffiltermatch.py @@ -48,7 +48,7 @@ class IsDescendantOfFilterMatch(IsDescendantOf): category = _('Descendant filters') description = _("Matches people that are descendants " "of anybody matched by a filter") - + def prepare(self,db): self.db = db self.map = set() diff --git a/gramps/gen/filters/rules/person/_islessthannthgenerationancestorof.py b/gramps/gen/filters/rules/person/_islessthannthgenerationancestorof.py index 51ce81bb3..8977888d9 100644 --- a/gramps/gen/filters/rules/person/_islessthannthgenerationancestorof.py +++ b/gramps/gen/filters/rules/person/_islessthannthgenerationancestorof.py @@ -59,7 +59,7 @@ class IsLessThanNthGenerationAncestorOf(Rule): def reset(self): self.map.clear() - + def apply(self,db,person): return person.handle in self.map @@ -72,14 +72,14 @@ class IsLessThanNthGenerationAncestorOf(Rule): self.map.add(handle) if gen >= int(self.list[1]): return - + p = self.db.get_person_from_handle(handle) fam_id = p.get_main_parents_family_handle() fam = self.db.get_family_from_handle(fam_id) if fam: f_id = fam.get_father_handle() m_id = fam.get_mother_handle() - + if f_id: self.init_ancestor_list(f_id,gen+1) if m_id: diff --git a/gramps/gen/filters/rules/person/_islessthannthgenerationancestorofbookmarked.py b/gramps/gen/filters/rules/person/_islessthannthgenerationancestorofbookmarked.py index b3b1c86bf..141e11805 100644 --- a/gramps/gen/filters/rules/person/_islessthannthgenerationancestorofbookmarked.py +++ b/gramps/gen/filters/rules/person/_islessthannthgenerationancestorofbookmarked.py @@ -77,14 +77,14 @@ class IsLessThanNthGenerationAncestorOfBookmarked(Rule): self.map.add(handle) if gen >= int(self.list[0]): return - + p = self.db.get_person_from_handle(handle) fam_id = p.get_main_parents_family_handle() fam = self.db.get_family_from_handle(fam_id) if fam: f_id = fam.get_father_handle() m_id = fam.get_mother_handle() - + if f_id: self.init_ancestor_list(f_id, gen+1) if m_id: diff --git a/gramps/gen/filters/rules/person/_islessthannthgenerationancestorofdefaultperson.py b/gramps/gen/filters/rules/person/_islessthannthgenerationancestorofdefaultperson.py index f610fc358..6da490c87 100644 --- a/gramps/gen/filters/rules/person/_islessthannthgenerationancestorofdefaultperson.py +++ b/gramps/gen/filters/rules/person/_islessthannthgenerationancestorofdefaultperson.py @@ -70,14 +70,14 @@ class IsLessThanNthGenerationAncestorOfDefaultPerson(Rule): self.map.add(handle) if gen >= int(self.list[0]): return - + p = self.db.get_person_from_handle(handle) fam_id = p.get_main_parents_family_handle() fam = self.db.get_family_from_handle(fam_id) if fam: f_id = fam.get_father_handle() m_id = fam.get_mother_handle() - + if f_id: self.init_ancestor_list(f_id, gen+1) if m_id: diff --git a/gramps/gen/filters/rules/person/_ismorethannthgenerationancestorof.py b/gramps/gen/filters/rules/person/_ismorethannthgenerationancestorof.py index 2795386a3..9d81d7e18 100644 --- a/gramps/gen/filters/rules/person/_ismorethannthgenerationancestorof.py +++ b/gramps/gen/filters/rules/person/_ismorethannthgenerationancestorof.py @@ -59,7 +59,7 @@ class IsMoreThanNthGenerationAncestorOf(Rule): def reset(self): self.map.clear() - + def apply(self,db,person): return person.handle in self.map @@ -70,14 +70,14 @@ class IsMoreThanNthGenerationAncestorOf(Rule): return if gen >= int(self.list[1]): self.map.add(handle) - + p = self.db.get_person_from_handle(handle) fam_id = p.get_main_parents_family_handle() fam = self.db.get_family_from_handle(fam_id) if fam: f_id = fam.get_father_handle() m_id = fam.get_mother_handle() - + if f_id: self.init_ancestor_list(f_id, gen+1) if m_id: diff --git a/gramps/gen/filters/rules/person/_ismorethannthgenerationdescendantof.py b/gramps/gen/filters/rules/person/_ismorethannthgenerationdescendantof.py index 771935380..5e084819d 100644 --- a/gramps/gen/filters/rules/person/_ismorethannthgenerationdescendantof.py +++ b/gramps/gen/filters/rules/person/_ismorethannthgenerationdescendantof.py @@ -47,8 +47,8 @@ class IsMoreThanNthGenerationDescendantOf(Rule): category = _("Descendant filters") description = _("Matches people that are descendants of a specified " "person at least N generations away") - - + + def prepare(self ,db): self.db = db self.map = set() diff --git a/gramps/gen/filters/rules/person/_isparentoffiltermatch.py b/gramps/gen/filters/rules/person/_isparentoffiltermatch.py index 7e8f6b0de..35691b368 100644 --- a/gramps/gen/filters/rules/person/_isparentoffiltermatch.py +++ b/gramps/gen/filters/rules/person/_isparentoffiltermatch.py @@ -69,7 +69,7 @@ class IsParentOfFilterMatch(Rule): fam = self.db.get_family_from_handle(fam_id) if fam: self.map.update(parent_id - for parent_id in [fam.get_father_handle(), + for parent_id in [fam.get_father_handle(), fam.get_mother_handle()] if parent_id) - + diff --git a/gramps/gen/filters/rules/person/_isrelatedwith.py b/gramps/gen/filters/rules/person/_isrelatedwith.py index 1ace5c2ac..b6e94c972 100644 --- a/gramps/gen/filters/rules/person/_isrelatedwith.py +++ b/gramps/gen/filters/rules/person/_isrelatedwith.py @@ -58,7 +58,7 @@ class IsRelatedWith(Rule): def reset(self): self.relatives = [] - + def apply(self, db, person): return person.handle in self.relatives @@ -77,7 +77,7 @@ class IsRelatedWith(Rule): if person is None or (person.handle in relatives): continue relatives[person.handle] = True - + for family_handle in person.get_parent_family_handle_list(): family = self.db.get_family_from_handle(family_handle) if family: @@ -88,7 +88,7 @@ class IsRelatedWith(Rule): # Check Sibilings for child_ref in family.get_child_ref_list(): expand.append(self.db.get_person_from_handle(child_ref.ref)) - + for family_handle in person.get_family_handle_list(): family = self.db.get_family_from_handle(family_handle) if family: @@ -99,6 +99,6 @@ class IsRelatedWith(Rule): # Check Children for child_ref in family.get_child_ref_list(): expand.append(self.db.get_person_from_handle(child_ref.ref)) - + self.relatives = list(relatives.keys()) - return + return diff --git a/gramps/gen/filters/rules/person/_isspouseoffiltermatch.py b/gramps/gen/filters/rules/person/_isspouseoffiltermatch.py index a1d0b7f61..fa8366332 100644 --- a/gramps/gen/filters/rules/person/_isspouseoffiltermatch.py +++ b/gramps/gen/filters/rules/person/_isspouseoffiltermatch.py @@ -51,12 +51,12 @@ class IsSpouseOfFilterMatch(Rule): def prepare(self,db): self.filt = MatchesFilter (self.list) self.filt.requestprepare(db) - + def apply(self,db,person): for family_handle in person.get_family_handle_list (): family = db.get_family_from_handle(family_handle) if family: - for spouse_id in [family.get_father_handle(), + for spouse_id in [family.get_father_handle(), family.get_mother_handle()]: if not spouse_id: continue diff --git a/gramps/gen/filters/rules/person/_matcheseventfilter.py b/gramps/gen/filters/rules/person/_matcheseventfilter.py index f861a0ecb..77d44f834 100644 --- a/gramps/gen/filters/rules/person/_matcheseventfilter.py +++ b/gramps/gen/filters/rules/person/_matcheseventfilter.py @@ -45,7 +45,7 @@ class MatchesEventFilter(MatchesEventFilterBase): This is a base rule for subclassing by specific objects. Subclasses need to define the namespace class attribute. - + """ labels = [_('Event filter name:')] diff --git a/gramps/gen/filters/rules/person/_missingparent.py b/gramps/gen/filters/rules/person/_missingparent.py index 2db2bfd20..90f60685b 100644 --- a/gramps/gen/filters/rules/person/_missingparent.py +++ b/gramps/gen/filters/rules/person/_missingparent.py @@ -55,7 +55,7 @@ class MissingParent(Rule): if family: father_handle = family.get_father_handle() mother_handle = family.get_mother_handle() - if not father_handle: + if not father_handle: return True if not mother_handle: return True diff --git a/gramps/gen/filters/rules/person/_regexpname.py b/gramps/gen/filters/rules/person/_regexpname.py index 894c72c07..dc609f507 100644 --- a/gramps/gen/filters/rules/person/_regexpname.py +++ b/gramps/gen/filters/rules/person/_regexpname.py @@ -51,7 +51,7 @@ class RegExpName(Rule): def apply(self,db,person): for name in [person.get_primary_name()] + person.get_alternate_names(): - for field in [name.first_name, name.get_surname(), name.suffix, + for field in [name.first_name, name.get_surname(), name.suffix, name.title, name.nick, name.famnick, name.call]: if self.match_substring(0, field): return True diff --git a/gramps/gen/filters/rules/person/_relationshippathbetween.py b/gramps/gen/filters/rules/person/_relationshippathbetween.py index eabc795a5..a567dd45c 100644 --- a/gramps/gen/filters/rules/person/_relationshippathbetween.py +++ b/gramps/gen/filters/rules/person/_relationshippathbetween.py @@ -65,7 +65,7 @@ class RelationshipPathBetween(Rule): def desc_list(self, handle, map, first): if not first: map.add(handle) - + p = self.db.get_person_from_handle(handle) for fam_id in p.get_family_handle_list(): fam = self.db.get_family_from_handle(fam_id) @@ -73,14 +73,14 @@ class RelationshipPathBetween(Rule): for child_ref in fam.get_child_ref_list(): if child_ref.ref: self.desc_list(child_ref.ref, map, 0) - + def apply_filter(self, rank, handle, plist, pmap): person = self.db.get_person_from_handle(handle) if person is None: return plist.add(handle) pmap[person.get_handle()] = rank - + fam_id = person.get_main_parents_family_handle() family = self.db.get_family_from_handle(fam_id) if family is not None: @@ -100,7 +100,7 @@ class RelationshipPathBetween(Rule): self.apply_filter(0, p1_handle, firstList, firstMap) self.apply_filter(0, p2_handle ,secondList, secondMap) - + for person_handle in firstList & secondList: new_rank = firstMap[person_handle] if new_rank < rank: diff --git a/gramps/gen/filters/rules/person/_relationshippathbetweenbookmarks.py b/gramps/gen/filters/rules/person/_relationshippathbetweenbookmarks.py index 0b9ec71a5..44e04a96e 100644 --- a/gramps/gen/filters/rules/person/_relationshippathbetweenbookmarks.py +++ b/gramps/gen/filters/rules/person/_relationshippathbetweenbookmarks.py @@ -43,7 +43,7 @@ from .. import Rule #------------------------------------------------------------------------- class RelationshipPathBetweenBookmarks(Rule): """ - Rule that matches the ancestors of bookmarked individuals back to + Rule that matches the ancestors of bookmarked individuals back to common ancestors, producing the relationship path(s) between the bookmarked individuals. """ @@ -141,7 +141,7 @@ class RelationshipPathBetweenBookmarks(Rule): rel_path[phandle] = phandle #print " In rel_path_for_two, returning rel_path = ", rel_path return rel_path - + def init_list(self): self.map.update(self.bookmarks) if len(self.bookmarks) < 2: diff --git a/gramps/gen/filters/rules/person/_searchname.py b/gramps/gen/filters/rules/person/_searchname.py index f7503ae3f..ce88b0608 100644 --- a/gramps/gen/filters/rules/person/_searchname.py +++ b/gramps/gen/filters/rules/person/_searchname.py @@ -53,7 +53,7 @@ class SearchName(Rule): return False for name in [person.get_primary_name()] + person.get_alternate_names(): - for field in [name.first_name, name.get_surname(), name.suffix, + for field in [name.first_name, name.get_surname(), name.suffix, name.title, name.nick, name.famnick, name.call]: if src and field.upper().find(src) != -1: return True diff --git a/gramps/gen/filters/rules/place/__init__.py b/gramps/gen/filters/rules/place/__init__.py index be2978157..fb5959b69 100644 --- a/gramps/gen/filters/rules/place/__init__.py +++ b/gramps/gen/filters/rules/place/__init__.py @@ -49,7 +49,7 @@ from ._hastitle import HasTitle editor_rule_list = [ AllPlaces, - HasCitation, + HasCitation, HasGallery, HasIdOf, RegExpIdOf, diff --git a/gramps/gen/filters/rules/place/_hascitation.py b/gramps/gen/filters/rules/place/_hascitation.py index 4342fdb98..a66376a74 100644 --- a/gramps/gen/filters/rules/place/_hascitation.py +++ b/gramps/gen/filters/rules/place/_hascitation.py @@ -45,8 +45,8 @@ from .._hascitationbase import HasCitationBase class HasCitation(HasCitationBase): """Rule that checks for a family with a particular value""" - labels = [ _('Volume/Page:'), - _('Date:'), + labels = [ _('Volume/Page:'), + _('Date:'), _('Confidence level:')] name = _('Place with the ') description = _("Matches places with a citation of a particular " diff --git a/gramps/gen/filters/rules/place/_hasplace.py b/gramps/gen/filters/rules/place/_hasplace.py index 6af70dfa9..b97f89316 100644 --- a/gramps/gen/filters/rules/place/_hasplace.py +++ b/gramps/gen/filters/rules/place/_hasplace.py @@ -46,14 +46,14 @@ class HasPlace(Rule): """Rule that checks for a place with a particular value""" labels = [ _('Title:'), - _('Street:'), - _('Locality:'), - _('City:'), - _('County:'), - _('State:'), - _('Country:'), + _('Street:'), + _('Locality:'), + _('City:'), + _('County:'), + _('State:'), + _('Country:'), _('ZIP/Postal Code:'), - _('Church Parish:'), + _('Church Parish:'), ] name = _('Places matching parameters') description = _("Matches places with particular parameters") @@ -78,7 +78,7 @@ class HasPlace(Rule): # If no location data was given then we're done: match if not any(self.list[1:7] + [self.list[8]]): return True - + for location in get_locations(db, place): if self.check(location): return True diff --git a/gramps/gen/filters/rules/place/_inlatlonneighborhood.py b/gramps/gen/filters/rules/place/_inlatlonneighborhood.py index 19b14bd9a..65a02d022 100644 --- a/gramps/gen/filters/rules/place/_inlatlonneighborhood.py +++ b/gramps/gen/filters/rules/place/_inlatlonneighborhood.py @@ -46,7 +46,7 @@ class InLatLonNeighborhood(Rule): Latitude or Longitude or""" - labels = [_('Latitude:'), _('Longitude:'), + labels = [_('Latitude:'), _('Longitude:'), _('Rectangle height:'), _('Rectangle width:')] name = _('Places in neighborhood of given position') description = _("Matches places with latitude or longitude positioned in " @@ -67,7 +67,7 @@ class InLatLonNeighborhood(Rule): self.halfheight = -1 #give dummy value self.list[0] = '0.0' - + if self.list[1] : try: self.halfwidth = float(self.list[3])/2. @@ -79,7 +79,7 @@ class InLatLonNeighborhood(Rule): self.halfwidth = -1 #give dummy value self.list[1] = '0.0' - + #we allow a band instead of a triangle self.lat, self.lon = conv_lat_lon(self.list[0],self.list[1],"D.D8") if self.lat is not None and self.lon is not None : @@ -87,17 +87,17 @@ class InLatLonNeighborhood(Rule): self.lon = float(self.lon) else : self.lat = None; self.lon = None - + #we define the two squares we must look in # can be 0, so check on None if self.lat is not None and self.halfheight is not None and self.halfheight != -1 : - self.S = self.lat + self.halfheight + self.S = self.lat + self.halfheight if self.S > 90. : self.S = 90. - self.N = self.lat - self.halfheight + self.N = self.lat - self.halfheight if self.N < -90. : self.N = -90. self.doublesquares = False if self.lon is not None and self.halfwidth is not None and self.halfwidth != -1 : - if self.halfwidth >= 180. : + if self.halfwidth >= 180. : #the entire longitude is allowed, reset values self.lon = 0. self.E = 180. @@ -117,26 +117,26 @@ class InLatLonNeighborhood(Rule): self.W2 = self.W + 360. self.E2 = 180. self.W = -180 - - + + def apply(self,db,place): if self.halfheight == -1 and self.halfwidth ==-1 : return False - + # when given, must be valid if self.lat is None or self.lon is None : return False - + # if height/width given, they must be valid if self.halfheight is None or self.halfwidth is None : return False - + #now we know at least one is given in the filter and is valid - + # the place we look at must have lat AND lon entered if not ( place.get_latitude().strip and place.get_longitude().strip() ): return False - + latpl, lonpl = conv_lat_lon(place.get_latitude(), place.get_longitude(), "D.D8") if latpl and lonpl : @@ -146,18 +146,18 @@ class InLatLonNeighborhood(Rule): # check lat if latpl < self.N or latpl > self.S : return False - + if self.halfwidth != -1 : #check lon: more difficult, we may cross the 180/-180 boundary # and must keep counting if self.doublesquares : - #two squares to look in : + #two squares to look in : if (lonpl self.E) and \ (lonpl self.E2) : return False elif (lonpl self.E) : return False - + return True - + return False diff --git a/gramps/gen/filters/rules/repository/_hasrepo.py b/gramps/gen/filters/rules/repository/_hasrepo.py index cf27a6231..0ee74ef4a 100644 --- a/gramps/gen/filters/rules/repository/_hasrepo.py +++ b/gramps/gen/filters/rules/repository/_hasrepo.py @@ -43,10 +43,10 @@ class HasRepo(Rule): """Rule that checks for a repo with a particular value""" - labels = [ _('repo|Name:'), - _('Type:'), + labels = [ _('repo|Name:'), + _('Type:'), _('Address:'), - _('URL:'), + _('URL:'), ] name = _('Repositories matching parameters') description = _("Matches Repositories with particular parameters") @@ -59,7 +59,7 @@ class HasRepo(Rule): self.rtype.set_from_xml_str(self.list[1]) else: self.rtype = None - + def apply(self, db, repo): if not self.match_substring(0, repo.get_name()): return False diff --git a/gramps/gen/filters/rules/source/_hasrepository.py b/gramps/gen/filters/rules/source/_hasrepository.py index 762e6d4c0..451e64300 100644 --- a/gramps/gen/filters/rules/source/_hasrepository.py +++ b/gramps/gen/filters/rules/source/_hasrepository.py @@ -58,7 +58,7 @@ class HasRepository(Rule): self.count_type = 1 # "equal to" self.userSelectedCount = int(self.list[0]) - + def apply(self, db, obj): count = len(obj.get_reporef_list()) if self.count_type == 0: # "less than" diff --git a/gramps/gen/filters/rules/source/_hasrepositorycallnumberref.py b/gramps/gen/filters/rules/source/_hasrepositorycallnumberref.py index 573b170e5..125d252b8 100644 --- a/gramps/gen/filters/rules/source/_hasrepositorycallnumberref.py +++ b/gramps/gen/filters/rules/source/_hasrepositorycallnumberref.py @@ -46,9 +46,9 @@ class HasRepositoryCallNumberRef(Rule): "containing a substring in \"Call Number\"") category = _('General filters') allow_regex = True - + def apply(self, db, obj): for repo_ref in obj.get_reporef_list(): if self.match_substring(0, repo_ref.call_number): - return True + return True return False diff --git a/gramps/gen/filters/rules/source/_matchesrepositoryfilter.py b/gramps/gen/filters/rules/source/_matchesrepositoryfilter.py index 1a2dfc408..94bc82926 100644 --- a/gramps/gen/filters/rules/source/_matchesrepositoryfilter.py +++ b/gramps/gen/filters/rules/source/_matchesrepositoryfilter.py @@ -45,19 +45,19 @@ class MatchesRepositoryFilter(MatchesFilterBase): description = _("Matches sources with a repository reference that match a certain\n" "repository filter") category = _('General filters') - + # we want to have this filter show repository filters namespace = 'Repository' - - + + def prepare(self, db): MatchesFilterBase.prepare(self, db) self.MRF_filt = self.find_filter() - + def apply(self, db, object): if self.MRF_filt is None : return False - + repolist = [x.ref for x in object.get_reporef_list()] for repohandle in repolist: #check if repo in repository filter diff --git a/gramps/gen/lib/__init__.py b/gramps/gen/lib/__init__.py index 93357d62a..09345ab26 100644 --- a/gramps/gen/lib/__init__.py +++ b/gramps/gen/lib/__init__.py @@ -32,7 +32,7 @@ from .attribute import Attribute from .srcattribute import SrcAttribute from .eventref import EventRef from .ldsord import LdsOrd -from .mediaref import MediaRef +from .mediaref import MediaRef from .name import Name from .placename import PlaceName from .placeref import PlaceRef diff --git a/gramps/gen/lib/address.py b/gramps/gen/lib/address.py index ec395ff2c..c0f1a05a3 100644 --- a/gramps/gen/lib/address.py +++ b/gramps/gen/lib/address.py @@ -71,7 +71,7 @@ class Address(SecondaryObject, PrivacyBase, CitationBase, NoteBase, DateBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -115,7 +115,7 @@ class Address(SecondaryObject, PrivacyBase, CitationBase, NoteBase, DateBase, Convert a serialized tuple of data to an object. """ (privacy, citation_list, note_list, date, location) = data - + PrivacyBase.unserialize(self, privacy) CitationBase.unserialize(self, citation_list) NoteBase.unserialize(self, note_list) @@ -155,7 +155,7 @@ class Address(SecondaryObject, PrivacyBase, CitationBase, NoteBase, DateBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -165,7 +165,7 @@ class Address(SecondaryObject, PrivacyBase, CitationBase, NoteBase, DateBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -196,7 +196,7 @@ class Address(SecondaryObject, PrivacyBase, CitationBase, NoteBase, DateBase, Merge the content of acquisition into this address. Lost: date, street, city, county, state, country, postal and phone of - acquisition. + acquisition. :param acquisition: The address to merge with the present address. :type acquisition: Address diff --git a/gramps/gen/lib/addressbase.py b/gramps/gen/lib/addressbase.py index 749f10da7..3bd804adb 100644 --- a/gramps/gen/lib/addressbase.py +++ b/gramps/gen/lib/addressbase.py @@ -43,9 +43,9 @@ class AddressBase(object): def __init__(self, source=None): """ - Initialize a AddressBase. - - If the source is not None, then object is initialized from values of + Initialize a AddressBase. + + If the source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object @@ -63,7 +63,7 @@ class AddressBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -110,7 +110,7 @@ class AddressBase(object): def remove_address(self, address): """ Remove the specified :class:`~.address.Address` instance from the address list. - + If the instance does not exist in the list, the operation has no effect. @@ -142,7 +142,7 @@ class AddressBase(object): """ Assign the passed list to the object's list of :class:`~.address.Address` instances. - + :param address_list: List of :class:`~.address.Address` instances to be associated with the object :type address_list: list diff --git a/gramps/gen/lib/attrbase.py b/gramps/gen/lib/attrbase.py index a0ab820de..21850f57b 100644 --- a/gramps/gen/lib/attrbase.py +++ b/gramps/gen/lib/attrbase.py @@ -46,7 +46,7 @@ class AttributeRootBase(object): def __init__(self, source=None): """ Initialize a AttributeBase. - + If the source is not None, then object is initialized from values of the source object. @@ -69,7 +69,7 @@ class AttributeRootBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -117,7 +117,7 @@ class AttributeRootBase(object): """ Remove the specified :class:`~.attribute.Attribute` instance from the attribute list. - + If the instance does not exist in the list, the operation has no effect. @@ -139,7 +139,7 @@ class AttributeRootBase(object): """ Return the list of :class:`~.attribute.Attribute` instances associated with the object. - + :returns: Returns the list of :class:`~.attribute.Attribute` instances. :rtype: list """ diff --git a/gramps/gen/lib/attribute.py b/gramps/gen/lib/attribute.py index 99bcac126..ab6920c81 100644 --- a/gramps/gen/lib/attribute.py +++ b/gramps/gen/lib/attribute.py @@ -38,31 +38,31 @@ from .const import IDENTICAL, EQUAL, DIFFERENT #------------------------------------------------------------------------- # -# Root object for Attribute +# Root object for Attribute # #------------------------------------------------------------------------- class AttributeRoot(SecondaryObject, PrivacyBase): """ - Provide a simple key/value pair for describing properties. + Provide a simple key/value pair for describing properties. Used to store descriptive information. - + In GEDCOM only used for Persons: - Individual attributes should describe situations that may be permanent or + Individual attributes should describe situations that may be permanent or temporary (start at some date, end at some date, etc.), may be associated - to a place (a position held, residence, etc.) or may not (eye colour, - height, caste, profession, etc.). They may have sources and notes and - media. + to a place (a position held, residence, etc.) or may not (eye colour, + height, caste, profession, etc.). They may have sources and notes and + media. Compare with :class:`~.event.Event` - + Gramps at the moment does not support this GEDCOM Attribute structure. """ - + def __init__(self, source=None): """ Create a new Attribute object, copying from the source if provided. """ PrivacyBase.__init__(self, source) - + #type structure depends on inheriting classes self.type = None self.value = None @@ -81,7 +81,7 @@ class AttributeRoot(SecondaryObject, PrivacyBase): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -99,7 +99,7 @@ class AttributeRoot(SecondaryObject, PrivacyBase): """ return {"_class": self.__class__.__name__, "private": PrivacyBase.serialize(self), - "type": self.type.to_struct(), + "type": self.type.to_struct(), "value": self.value} @classmethod @@ -111,7 +111,7 @@ class AttributeRoot(SecondaryObject, PrivacyBase): """ default = Attribute() return (PrivacyBase.from_struct(struct.get("private", default.private)), - AttributeType.from_struct(struct.get("type", {})), + AttributeType.from_struct(struct.get("type", {})), struct.get("value", default.value)) def unserialize(self, data): @@ -145,7 +145,7 @@ class AttributeRoot(SecondaryObject, PrivacyBase): """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -155,7 +155,7 @@ class AttributeRoot(SecondaryObject, PrivacyBase): """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -165,7 +165,7 @@ class AttributeRoot(SecondaryObject, PrivacyBase): """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -222,7 +222,7 @@ class AttributeRoot(SecondaryObject, PrivacyBase): # #------------------------------------------------------------------------- class Attribute(AttributeRoot, CitationBase, NoteBase): - + def __init__(self, source=None): """ Create a new Attribute object, copying from the source if provided. @@ -230,7 +230,7 @@ class Attribute(AttributeRoot, CitationBase, NoteBase): AttributeRoot.__init__(self, source) CitationBase.__init__(self, source) NoteBase.__init__(self, source) - + if source: self.type = AttributeType(source.type) self.value = source.value @@ -250,7 +250,7 @@ class Attribute(AttributeRoot, CitationBase, NoteBase): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -270,7 +270,7 @@ class Attribute(AttributeRoot, CitationBase, NoteBase): "private": PrivacyBase.serialize(self), "citation_list": CitationBase.to_struct(self), "note_list": NoteBase.to_struct(self), - "type": self.type.to_struct(), + "type": self.type.to_struct(), "value": self.value} @classmethod @@ -283,7 +283,7 @@ class Attribute(AttributeRoot, CitationBase, NoteBase): return (PrivacyBase.from_struct(struct["private"]), CitationBase.from_struct(struct["citation_list"]), NoteBase.from_struct(struct["note_list"]), - AttributeType.from_struct(struct["type"]), + AttributeType.from_struct(struct["type"]), struct["value"]) def unserialize(self, data): @@ -301,7 +301,7 @@ class Attribute(AttributeRoot, CitationBase, NoteBase): """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ diff --git a/gramps/gen/lib/attrtype.py b/gramps/gen/lib/attrtype.py index 7c5c66ca0..e60d418ff 100644 --- a/gramps/gen/lib/attrtype.py +++ b/gramps/gen/lib/attrtype.py @@ -83,15 +83,15 @@ class AttributeType(GrampsType): def get_ignore_list(self, exception=None): """ Return a list of the types to ignore and not include in default lists. - + Exception is a sublist of types that may not be ignored - + :param exception: list of integer values corresponding with types that have to be excluded from the ignore list :type exception: list - :returns: list of integers corresponding with the types to ignore when + :returns: list of integers corresponding with the types to ignore when showing a list of different types :rtype: list - + """ return [] diff --git a/gramps/gen/lib/childref.py b/gramps/gen/lib/childref.py index 552999d60..8530556ac 100644 --- a/gramps/gen/lib/childref.py +++ b/gramps/gen/lib/childref.py @@ -79,7 +79,7 @@ class ChildRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -155,7 +155,7 @@ class ChildRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase): """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -165,7 +165,7 @@ class ChildRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase): """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -177,9 +177,9 @@ class ChildRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase): def get_handle_referents(self): """ - Return the list of child objects which may, directly or through their + Return the list of child objects which may, directly or through their children, reference primary objects.. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ diff --git a/gramps/gen/lib/childreftype.py b/gramps/gen/lib/childreftype.py index 7a9565854..70c3a3590 100644 --- a/gramps/gen/lib/childreftype.py +++ b/gramps/gen/lib/childreftype.py @@ -39,7 +39,7 @@ from .grampstype import GrampsType class ChildRefType(GrampsType): """ Provide the different ChildRef types. - + .. attribute NONE : None - no relationship .. attribute BIRTH : Birth - relation by birth. Implicates genetic relationship if no other families with other types are present @@ -50,7 +50,7 @@ class ChildRefType(GrampsType): .. attribute SPONSORED : Sponsored - parent is sponsoring the child .. attribute FOSTER : Foster - taking care of the child while the real parents are around and know of it. This can be due to the parents - not being able to care for the child, or because government has + not being able to care for the child, or because government has ordered this .. attribute UNKNOWN : Unknown - unknown relationship .. attribute CUSTOM : Custom - a relationship given by the user @@ -82,5 +82,5 @@ class ChildRefType(GrampsType): def __init__(self, value=None): GrampsType.__init__(self, value) - - + + diff --git a/gramps/gen/lib/citation.py b/gramps/gen/lib/citation.py index 1b6c1a9c1..728513989 100644 --- a/gramps/gen/lib/citation.py +++ b/gramps/gen/lib/citation.py @@ -51,13 +51,13 @@ from .handle import Handle # Citation class # #------------------------------------------------------------------------- -class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, +class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, DateBase, PrimaryObject): """ A record of a citation of a source of information. - + In GEDCOM this is called a SOURCE_CITATION. - The data provided in the <> structure is source-related + The data provided in the <> structure is source-related information specific to the data being cited. """ @@ -77,7 +77,7 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, self.page = "" # 3 self.confidence = Citation.CONF_NORMAL # 4 SrcAttributeBase.__init__(self) # 8 - + def serialize(self, no_text_date = False): """ Convert the object to a serialized tuple of data. @@ -99,7 +99,7 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -175,17 +175,17 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, TagBase.unserialize(self, tag_list) SrcAttributeBase.unserialize(self, srcattr_list) return self - + def _has_handle_reference(self, classname, handle): """ - Return True if the object has reference to a given handle of given + Return True if the object has reference to a given handle of given primary object type. - + :param classname: The name of the primary object class. :type classname: str :param handle: The handle to be checked. :type handle: str - :returns: Returns whether the object has reference to this handle of + :returns: Returns whether the object has reference to this handle of this object type. :rtype: bool """ @@ -229,7 +229,7 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Return the list of child secondary objects that may refer citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer citations. :rtype: list """ @@ -243,7 +243,7 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, :rtype: list """ return [self.page, self.gramps_id] - + def get_text_data_child_list(self): """ Return the list of child objects that may carry textual data. @@ -257,7 +257,7 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -267,7 +267,7 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -277,7 +277,7 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -304,7 +304,7 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, level_priority.index(acquisition.confidence)) self.confidence = level_priority[idx] self._merge_attribute_list(acquisition) - # N.B. a Citation can refer to only one 'Source', so the + # N.B. a Citation can refer to only one 'Source', so the # 'Source' from acquisition cannot be merged in def set_confidence_level(self, val): @@ -314,7 +314,7 @@ class Citation(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, def get_confidence_level(self): """Return the confidence level.""" return self.confidence - + def set_page(self, page): """Set the page indicator of the Citation.""" self.page = page diff --git a/gramps/gen/lib/citationbase.py b/gramps/gen/lib/citationbase.py index c88a515bd..6b19d8150 100644 --- a/gramps/gen/lib/citationbase.py +++ b/gramps/gen/lib/citationbase.py @@ -55,14 +55,14 @@ class CitationBase(object): Both these have no attributes of their own; in this respect, they differ from classes like MediaRef, which does have attributes (in that case, privacy, sources, notes and attributes). - - This class, together with the Citation class, replaces the old SourceRef + + This class, together with the Citation class, replaces the old SourceRef class. I.e. SourceRef = CitationBase + Citation """ def __init__(self, source=None): """ Create a new CitationBase, copying from source if not None. - + :param source: Object used to initialize the new object :type source: CitationBase """ @@ -78,7 +78,7 @@ class CitationBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -104,7 +104,7 @@ class CitationBase(object): :returns: Returns a serialized object """ return [Handle.from_struct(handle) for handle in struct] - + def unserialize(self, data): """ Convert a serialized tuple of data to an object. @@ -141,23 +141,23 @@ class CitationBase(object): % (citation_handle_list, self, self.citation_list)) for handle in citation_handle_list: if handle in self.citation_list: - LOG.debug('remove handle %s from citation_list %s' % + LOG.debug('remove handle %s from citation_list %s' % (handle, self.citation_list)) self.citation_list.remove(handle) - LOG.debug('get_citation_child_list %s' % + LOG.debug('get_citation_child_list %s' % self.get_citation_child_list()) for item in self.get_citation_child_list(): item.remove_citation_references(citation_handle_list) - + def get_citation_child_list(self): """ Return the list of child secondary objects that may refer citations. - + All methods which inherit from CitationBase and have other child objects - with citations, should return here a list of child objects which are + with citations, should return here a list of child objects which are CitationBase - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer citations. :rtype: list """ @@ -182,7 +182,7 @@ class CitationBase(object): :rtype: list """ list = self.citation_list - + for item in self.get_citation_child_list(): list += item.get_citation_list() for subitem in item.get_citation_child_list(): @@ -191,7 +191,7 @@ class CitationBase(object): def has_citation_reference(self, citation_handle): """ - Return True if the object or any of its child objects has reference + Return True if the object or any of its child objects has reference to this citation handle. :param citation_handle: The citation handle to be checked. @@ -226,7 +226,7 @@ class CitationBase(object): """ Merge the list of citations from acquisition with our own. - :param acquisition: The citation list of this object will be merged + :param acquisition: The citation list of this object will be merged with the current citation list. :type acquisition: CitationBase """ @@ -235,12 +235,12 @@ class CitationBase(object): def get_referenced_citation_handles(self): """ - Return the list of (classname, handle) tuples for all referenced + Return the list of (classname, handle) tuples for all referenced citations. - + This method should be used to get the :class:`~.citation.Citation` portion of the list by objects that store citation lists. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -277,22 +277,22 @@ class IndirectCitationBase(object): Citation management logic for objects that don't have citations for the primary objects, but only for the child (secondary) ones. - The derived class must implement the - :meth:`~CitationBase.get_citation_child_list` method to return the list of + The derived class must implement the + :meth:`~CitationBase.get_citation_child_list` method to return the list of child secondary objects that may refer citations. - .. note:: for most objects, this functionality is inherited from + .. note:: for most objects, this functionality is inherited from :class:`CitationBase`, which checks both the object and the child objects. """ def has_citation_reference(self, citation_handle): """ - Return True if any of the child objects has reference to this citation + Return True if any of the child objects has reference to this citation handle. - + :param citation_handle: The citation handle to be checked. :type citation_handle: str - :returns: Returns whether any of it's child objects has reference to + :returns: Returns whether any of it's child objects has reference to this citation handle. :rtype: bool """ @@ -317,7 +317,7 @@ class IndirectCitationBase(object): def remove_citation_references(self, citation_handle_list): """ - Remove references to all citation handles in the list in all child + Remove references to all citation handles in the list in all child objects. :param citation_handle_list: The list of citation handles to be removed. @@ -325,7 +325,7 @@ class IndirectCitationBase(object): """ for item in self.get_citation_child_list(): item.remove_citation_references(citation_handle_list) - + def get_citation_list(self): """ Return the list of :class:`~gen.lib.citation.Citation` handles diff --git a/gramps/gen/lib/date.py b/gramps/gen/lib/date.py index 4939571e9..780dbeb8d 100644 --- a/gramps/gen/lib/date.py +++ b/gramps/gen/lib/date.py @@ -11,7 +11,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -46,9 +46,9 @@ log = logging.getLogger(".Date") from ..const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext -from .gcalendar import (gregorian_sdn, julian_sdn, hebrew_sdn, +from .gcalendar import (gregorian_sdn, julian_sdn, hebrew_sdn, french_sdn, persian_sdn, islamic_sdn, swedish_sdn, - gregorian_ymd, julian_ymd, hebrew_ymd, + gregorian_ymd, julian_ymd, hebrew_ymd, french_ymd, persian_ymd, islamic_ymd, swedish_ymd) from ..config import config @@ -212,7 +212,7 @@ class Span(object): return self._diff(self.date1, self.date2) def __getitem__(self, pos): - # Depricated! + # Depricated! return self._diff(self.date1, self.date2)[pos] def __int__(self): @@ -227,10 +227,10 @@ class Span(object): ## def __cmp__(self, other): ## """ ## DEPRECATED - not available in python 3 -## -## Comparing two Spans for SORTING purposes. +## +## Comparing two Spans for SORTING purposes. ## Use cmp(abs(int(span1)), abs(int(span2))) for comparing -## actual spans of times, as spans have directionality +## actual spans of times, as spans have directionality ## as indicated by negative values. ## """ ## raise NotImplementedError @@ -291,7 +291,7 @@ class Span(object): start, stop = self.date2.get_start_stop_range() start = Date(*start) stop = Date(*stop) - _repr = (trans_text("between") + " " + self._format(self._diff(self.date1, stop),dlocale) + + _repr = (trans_text("between") + " " + self._format(self._diff(self.date1, stop),dlocale) + " " + trans_text("and") + " " + self._format(self._diff(self.date1, start),dlocale)) elif self.date1.get_modifier() == Date.MOD_BEFORE: # BEFORE---------------------------- if self.date2.get_modifier() == Date.MOD_NONE: @@ -331,7 +331,7 @@ class Span(object): start, stop = self.date1.get_start_stop_range() start = Date(*start) stop = Date(*stop) - _repr = (trans_text("between") + " " + self._format(self._diff(start, self.date2),dlocale) + + _repr = (trans_text("between") + " " + self._format(self._diff(start, self.date2),dlocale) + " " + trans_text("and") + " " + self._format(self._diff(stop, self.date2),dlocale)) elif self.date2.get_modifier() == Date.MOD_BEFORE: _repr = trans_text("more than") + " " + fdate12 @@ -346,7 +346,7 @@ class Span(object): start2 = Date(*start2) stop1 = Date(*stop1) stop2 = Date(*stop2) - _repr = (trans_text("between") + " " + self._format(self._diff(start1, stop2),dlocale) + + _repr = (trans_text("between") + " " + self._format(self._diff(start1, stop2),dlocale) + " " + trans_text("and") + " " + self._format(self._diff(stop1, start2),dlocale)) return _repr @@ -376,7 +376,7 @@ class Span(object): def format(self, precision=2, as_age=True): """ - Force a string representation at a level of precision. + Force a string representation at a level of precision. == ==================================================== 1 only most significant level (year, month, day) @@ -470,7 +470,7 @@ class Span(object): days = d1[2] - d2[2] months = d1[1] - d2[1] years = d1[0] - d2[0] - if days > 31: + if days > 31: months += days // 31 days = days % 31 if months > 12: @@ -514,8 +514,8 @@ class Span(object): #------------------------------------------------------------------------- class Date(object): """ - The core date handling class for Gramps. - + The core date handling class for Gramps. + Supports partial dates, compound dates and alternate calendars. """ MOD_NONE = 0 # CODE @@ -557,39 +557,39 @@ class Date(object): _POS_RSL = 7 _calendar_convert = [ - gregorian_sdn, - julian_sdn, - hebrew_sdn, - french_sdn, - persian_sdn, - islamic_sdn, - swedish_sdn, + gregorian_sdn, + julian_sdn, + hebrew_sdn, + french_sdn, + persian_sdn, + islamic_sdn, + swedish_sdn, ] _calendar_change = [ - gregorian_ymd, - julian_ymd, - hebrew_ymd, - french_ymd, - persian_ymd, - islamic_ymd, - swedish_ymd, + gregorian_ymd, + julian_ymd, + hebrew_ymd, + french_ymd, + persian_ymd, + islamic_ymd, + swedish_ymd, ] - calendar_names = ["Gregorian", - "Julian", - "Hebrew", - "French Republican", - "Persian", - "Islamic", + calendar_names = ["Gregorian", + "Julian", + "Hebrew", + "French Republican", + "Persian", + "Islamic", "Swedish"] - ui_calendar_names = [_("calendar|Gregorian"), - _("calendar|Julian"), - _("calendar|Hebrew"), - _("calendar|French Republican"), - _("calendar|Persian"), + ui_calendar_names = [_("calendar|Gregorian"), + _("calendar|Julian"), + _("calendar|Hebrew"), + _("calendar|French Republican"), + _("calendar|Persian"), _("calendar|Islamic"), _("calendar|Swedish")] @@ -647,15 +647,15 @@ class Date(object): text = '' else: text = self.text - - return (self.calendar, self.modifier, self.quality, + + return (self.calendar, self.modifier, self.quality, self.dateval, text, self.sortval, self.newyear) def to_struct(self): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -672,12 +672,12 @@ class Date(object): :rtype: dict """ return {"_class": "Date", - "calendar": self.calendar, - "modifier": self.modifier, - "quality": self.quality, - "dateval": self.dateval, - "text": self.text, - "sortval": self.sortval, + "calendar": self.calendar, + "modifier": self.modifier, + "quality": self.quality, + "dateval": self.dateval, + "text": self.text, + "sortval": self.sortval, "newyear": self.newyear} @classmethod @@ -699,21 +699,21 @@ class Date(object): return None else: return retval - + def unserialize(self, data): """ Load from the format created by serialize. """ - #FIXME: work around 3.1.0 error: - #2792: Dates in sourcereferences in person_ref_list not upgraded + #FIXME: work around 3.1.0 error: + #2792: Dates in sourcereferences in person_ref_list not upgraded #Added 2009/03/09 if len(data) == 7: # This is correct: - (self.calendar, self.modifier, self.quality, + (self.calendar, self.modifier, self.quality, self.dateval, self.text, self.sortval, self.newyear) = data elif len(data) == 6: # This is necessary to fix 3.1.0 bug: - (self.calendar, self.modifier, self.quality, + (self.calendar, self.modifier, self.quality, self.dateval, self.text, self.sortval) = data self.newyear = 0 # Remove all except if-part after 3.1.1 @@ -723,7 +723,7 @@ class Date(object): def copy(self, source): """ - Copy all the attributes of the given Date instance to the present + Copy all the attributes of the given Date instance to the present instance, without creating a new object. """ self.calendar = source.calendar @@ -738,7 +738,7 @@ class Date(object): ## def __cmp__(self, other): ## """ ## Compare two dates. -## +## ## Comparison function. Allows the usage of equality tests. ## This allows you do run statements like 'date1 <= date2' ## """ @@ -750,7 +750,7 @@ class Date(object): # Can't use this (as is) as this breaks comparing dates to None #def __eq__(self, other): # return self.sortval == other.sortval - + def __eq__(self, other): """ Equality based on sort value, use is_equal/match instead if needed @@ -856,53 +856,53 @@ class Date(object): def is_equal(self, other): """ Return 1 if the given Date instance is the same as the present - instance IN ALL REGARDS. - - Needed, because the __cmp__ only looks at the sorting value, and + instance IN ALL REGARDS. + + Needed, because the __cmp__ only looks at the sorting value, and ignores the modifiers/comments. """ if self.modifier == other.modifier \ and self.modifier == Date.MOD_TEXTONLY: value = self.text == other.text else: - value = (self.calendar == other.calendar and - self.modifier == other.modifier and - self.quality == other.quality and + value = (self.calendar == other.calendar and + self.modifier == other.modifier and + self.quality == other.quality and self.dateval == other.dateval) return value def get_start_stop_range(self): """ - Return the minimal start_date, and a maximal stop_date corresponding + Return the minimal start_date, and a maximal stop_date corresponding to this date, given in Gregorian calendar. - + Useful in doing range overlap comparisons between different dates. - Note that we stay in (YR,MON,DAY) + Note that we stay in (YR,MON,DAY) """ - + def yr_mon_day(dateval): """ - Local function to swap order for easy comparisons, and correct + Local function to swap order for easy comparisons, and correct year of slash date. - - Slash date is given as year1/year2, where year1 is Julian year, + + Slash date is given as year1/year2, where year1 is Julian year, and year2=year1+1 the Gregorian year. Slash date is already taken care of. """ - return (dateval[Date._POS_YR], dateval[Date._POS_MON], + return (dateval[Date._POS_YR], dateval[Date._POS_MON], dateval[Date._POS_DAY]) def date_offset(dateval, offset): """ - Local function to do date arithmetic: add the offset, return + Local function to do date arithmetic: add the offset, return (year,month,day) in the Gregorian calendar. """ new_date = Date() new_date.set_yr_mon_day(*dateval[:3]) return new_date.offset(offset) - - datecopy = Date(self) + + datecopy = Date(self) #we do all calculation in Gregorian calendar datecopy.convert_calendar(Date.CAL_GREGORIAN) @@ -911,13 +911,13 @@ class Date(object): if stop == (0, 0, 0): stop = start - + stopmax = list(stop) if stopmax[0] == 0: # then use start_year, if one stopmax[0] = start[Date._POS_YR] if stopmax[1] == 0: stopmax[1] = 12 - if stopmax[2] == 0: + if stopmax[2] == 0: stopmax[2] = 31 startmin = list(start) if startmin[1] == 0: @@ -940,7 +940,7 @@ class Date(object): stopmax = (stopmax[0] + fdiff, stopmax[1], stopmax[2]) # return tuples not lists, for comparisons return (tuple(startmin), tuple(stopmax)) - + def match_exact(self, other_date): """ Perform an extact match between two dates. The dates are not treated @@ -962,11 +962,11 @@ class Date(object): def match(self, other_date, comparison="="): """ - Compare two dates using sophisticated techniques looking for any match + Compare two dates using sophisticated techniques looking for any match between two possible dates, date spans and qualities. - - The other comparisons for Date (is_equal() and __cmp() don't actually - look for anything other than a straight match, or a simple comparison + + The other comparisons for Date (is_equal() and __cmp() don't actually + look for anything other than a straight match, or a simple comparison of the sortval. ========== ======================================================= @@ -997,8 +997,8 @@ class Date(object): if comparison == "=": # If some overlap then match is True, otherwise False. return ((self_start <= other_start <= self_stop) or - (self_start <= other_stop <= self_stop) or - (other_start <= self_start <= other_stop) or + (self_start <= other_stop <= self_stop) or + (other_start <= self_start <= other_stop) or (other_start <= self_stop <= other_stop)) elif comparison == "==": # If they match exactly on start and stop @@ -1023,13 +1023,13 @@ class Date(object): # If all > all return self_start > other_stop else: - raise AttributeError("invalid match comparison operator: '%s'" % + raise AttributeError("invalid match comparison operator: '%s'" % comparison) - + def __str__(self): """ - Produce a string representation of the Date object. - + Produce a string representation of the Date object. + If the date is not valid, the text representation is displayed. If the date is a range or a span, a string in the form of 'YYYY-MM-DD - YYYY-MM-DD' is returned. Otherwise, a string in @@ -1052,7 +1052,7 @@ class Date(object): pref = "" ny = self.newyear_to_str() - + if self.calendar != Date.CAL_GREGORIAN: if ny: cal = " (%s,%s)" % (Date.calendar_names[self.calendar], ny) @@ -1068,18 +1068,18 @@ class Date(object): val = self.text elif self.get_slash(): val = "%04d/%d-%02d-%02d" % ( - self.dateval[Date._POS_YR] - 1, - (self.dateval[Date._POS_YR]) % 10, - self.dateval[Date._POS_MON], + self.dateval[Date._POS_YR] - 1, + (self.dateval[Date._POS_YR]) % 10, + self.dateval[Date._POS_MON], self.dateval[Date._POS_DAY]) elif self.is_compound(): val = "%04d-%02d-%02d - %04d-%02d-%02d" % ( - self.dateval[Date._POS_YR], self.dateval[Date._POS_MON], - self.dateval[Date._POS_DAY], self.dateval[Date._POS_RYR], + self.dateval[Date._POS_YR], self.dateval[Date._POS_MON], + self.dateval[Date._POS_DAY], self.dateval[Date._POS_RYR], self.dateval[Date._POS_RMON], self.dateval[Date._POS_RDAY]) else: val = "%04d-%02d-%02d" % ( - self.dateval[Date._POS_YR], self.dateval[Date._POS_MON], + self.dateval[Date._POS_YR], self.dateval[Date._POS_MON], self.dateval[Date._POS_DAY]) return "%s%s%s%s" % (qual, pref, val, cal) @@ -1127,26 +1127,26 @@ class Date(object): def get_sort_value(self): """ - Return the sort value of Date object. - - If the value is a text string, 0 is returned. Otherwise, the - calculated sort date is returned. The sort date is rebuilt on every + Return the sort value of Date object. + + If the value is a text string, 0 is returned. Otherwise, the + calculated sort date is returned. The sort date is rebuilt on every assignment. - The sort value is an integer representing the value. The sortval is - the integer number of days that have elapsed since Monday, January 1, - 4713 BC in the proleptic Julian calendar. - + The sort value is an integer representing the value. The sortval is + the integer number of days that have elapsed since Monday, January 1, + 4713 BC in the proleptic Julian calendar. + .. seealso:: http://en.wikipedia.org/wiki/Julian_day """ return self.sortval def get_modifier(self): """ - Return an integer indicating the calendar selected. - + Return an integer indicating the calendar selected. + The valid values are: - + ============ ===================== MOD_NONE no modifier (default) MOD_BEFORE before @@ -1163,18 +1163,18 @@ class Date(object): """ Set the modifier for the date. """ - if val not in (Date.MOD_NONE, Date.MOD_BEFORE, Date.MOD_AFTER, - Date.MOD_ABOUT, Date.MOD_RANGE, Date.MOD_SPAN, + if val not in (Date.MOD_NONE, Date.MOD_BEFORE, Date.MOD_AFTER, + Date.MOD_ABOUT, Date.MOD_RANGE, Date.MOD_SPAN, Date.MOD_TEXTONLY): raise DateError("Invalid modifier") self.modifier = val def get_quality(self): """ - Return an integer indicating the calendar selected. - + Return an integer indicating the calendar selected. + The valid values are: - + =============== ================ QUAL_NONE normal (default) QUAL_ESTIMATED estimated @@ -1187,15 +1187,15 @@ class Date(object): """ Set the quality selected for the date. """ - if val not in (Date.QUAL_NONE, Date.QUAL_ESTIMATED, + if val not in (Date.QUAL_NONE, Date.QUAL_ESTIMATED, Date.QUAL_CALCULATED): raise DateError("Invalid quality") self.quality = val - + def get_calendar(self): """ - Return an integer indicating the calendar selected. - + Return an integer indicating the calendar selected. + The valid values are: ============= ========================================== @@ -1220,9 +1220,9 @@ class Date(object): def get_start_date(self): """ - Return a tuple representing the start date. - - If the date is a compound date (range or a span), it is the first part + Return a tuple representing the start date. + + If the date is a compound date (range or a span), it is the first part of the compound date. If the date is a text string, a tuple of (0, 0, 0, False) is returned. Otherwise, a date of (DD, MM, YY, slash) is returned. If slash is True, then the date is in the form of 1530/1. @@ -1235,8 +1235,8 @@ class Date(object): def get_stop_date(self): """ - Return a tuple representing the second half of a compound date. - + Return a tuple representing the second half of a compound date. + If the date is not a compound date, (including text strings) a tuple of (0, 0, 0, False) is returned. Otherwise, a date of (DD, MM, YY, slash) is returned. If slash is True, then the date is in the form of 1530/1. @@ -1266,7 +1266,7 @@ class Date(object): else: val = self.dateval[index] != 0 return val - + def _get_high_item(self, index): """ Return the item specified. @@ -1279,16 +1279,16 @@ class Date(object): def get_year(self): """ - Return the year associated with the date. - - If the year is not defined, a zero is returned. If the date is a + Return the year associated with the date. + + If the year is not defined, a zero is returned. If the date is a compound date, the lower date year is returned. """ return self._get_low_item(Date._POS_YR) def get_year_calendar(self, calendar_name=None): """ - Return the year of this date in the calendar name given. + Return the year of this date in the calendar name given. Defaults to self's calendar if one is not given. @@ -1308,13 +1308,13 @@ class Date(object): def get_new_year(self): """ - Return the new year code associated with the date. + Return the new year code associated with the date. """ return self.newyear def set_new_year(self, value): """ - Set the new year code associated with the date. + Set the new year code associated with the date. """ self.newyear = value @@ -1330,30 +1330,30 @@ class Date(object): Set the year, month, and day values. :param remove_stop_date: - Required parameter for a compound date. + Required parameter for a compound date. When True, the stop date is changed to the same date as well. When False, the stop date is not changed. """ if self.is_compound() and remove_stop_date is None: raise DateError("Required parameter remove_stop_date not set!") - self.__set_yr_mon_day(year, month, day, + self.__set_yr_mon_day(year, month, day, Date._POS_YR, Date._POS_MON, Date._POS_DAY) self._calc_sort_value() - if remove_stop_date and self.is_compound(): + if remove_stop_date and self.is_compound(): self.set2_yr_mon_day(year, month, day) def _assert_compound(self): - if not self.is_compound(): + if not self.is_compound(): raise DateError("Operation allowed for compound dates only!") def set2_yr_mon_day(self, year, month, day): """ - Set the year, month, and day values in the 2nd part of + Set the year, month, and day values in the 2nd part of a compound date (range or span). """ self._assert_compound() - self.__set_yr_mon_day(year, month, day, + self.__set_yr_mon_day(year, month, day, Date._POS_RYR, Date._POS_RMON, Date._POS_RDAY) def __set_yr_mon_day_offset(self, year, month, day, pos_yr, pos_mon, pos_day): @@ -1391,12 +1391,12 @@ class Date(object): if self.__set_yr_mon_day_offset(year, month, day, Date._POS_YR, Date._POS_MON, Date._POS_DAY): self.set_yr_mon_day(*self.offset(day), remove_stop_date = False) - if self.is_compound(): + if self.is_compound(): self.set2_yr_mon_day_offset(year, month, day) def set2_yr_mon_day_offset(self, year=0, month=0, day=0): """ - Set the year, month, and day values by offset in the 2nd part + Set the year, month, and day values by offset in the 2nd part of a compound date (range or span). """ self._assert_compound() @@ -1447,9 +1447,9 @@ class Date(object): def get_month(self): """ - Return the month associated with the date. - - If the month is not defined, a zero is returned. If the date is a + Return the month associated with the date. + + If the month is not defined, a zero is returned. If the date is a compound date, the lower date month is returned. """ return self._get_low_item(Date._POS_MON) @@ -1462,9 +1462,9 @@ class Date(object): def get_day(self): """ - Return the day of the month associated with the date. - - If the day is not defined, a zero is returned. If the date is a + Return the day of the month associated with the date. + + If the day is not defined, a zero is returned. If the date is a compound date, the lower date day is returned. """ return self._get_low_item(Date._POS_DAY) @@ -1476,49 +1476,49 @@ class Date(object): return self._get_low_item_valid(Date._POS_DAY) def get_valid(self): - """ + """ Return true if any part of the date is valid. """ return self.modifier != Date.MOD_TEXTONLY def is_valid(self): - """ + """ Return true if any part of the date is valid. """ return self.modifier != Date.MOD_TEXTONLY and self.sortval != 0 def get_stop_year(self): """ - Return the day of the year associated with the second part of a - compound date. - - If the year is not defined, a zero is returned. + Return the day of the year associated with the second part of a + compound date. + + If the year is not defined, a zero is returned. """ return self._get_high_item(Date._POS_RYR) def get_stop_month(self): """ - Return the month of the month associated with the second part of a - compound date. - - If the month is not defined, a zero is returned. + Return the month of the month associated with the second part of a + compound date. + + If the month is not defined, a zero is returned. """ return self._get_high_item(Date._POS_RMON) def get_stop_day(self): """ - Return the day of the month associated with the second part of a - compound date. - - If the day is not defined, a zero is returned. + Return the day of the month associated with the second part of a + compound date. + + If the day is not defined, a zero is returned. """ return self._get_high_item(Date._POS_RDAY) def get_high_year(self): """ - Return the high year estimate. - - For compound dates with non-zero stop year, the stop year is returned. + Return the high year estimate. + + For compound dates with non-zero stop year, the stop year is returned. Otherwise, the start year is returned. """ if self.is_compound(): @@ -1538,7 +1538,7 @@ class Date(object): """ Return an integer representing the day of the week associated with the date (Monday=0). - + If the day is not defined, a None is returned. If the date is a compound date, the lower date day is returned. """ @@ -1554,7 +1554,7 @@ class Date(object): """ Returns year adjustment performed (0 or -1). """ - ny = self.get_new_year() + ny = self.get_new_year() year_delta = 0 if ny: # new year offset? if ny == Date.NEWYEAR_MAR1: @@ -1575,12 +1575,12 @@ class Date(object): self.sortval = d1.sortval return year_delta - def set(self, quality=None, modifier=None, calendar=None, - value=None, + def set(self, quality=None, modifier=None, calendar=None, + value=None, text=None, newyear=0): """ - Set the date to the specified value. - + Set the date to the specified value. + :param quality: The date quality for the date (see :meth:`get_quality` for more information). Defaults to the previous value for the date. @@ -1599,7 +1599,7 @@ class Date(object): or a comment relating to the date. Defaults to the previous value for the date. :param newyear: The newyear code, or tuple representing (month, day) - of newyear day. + of newyear day. Defaults to 0. The sort value is recalculated. @@ -1613,18 +1613,18 @@ class Date(object): calendar = self.calendar if value is None: value = self.dateval - - if modifier in (Date.MOD_NONE, Date.MOD_BEFORE, + + if modifier in (Date.MOD_NONE, Date.MOD_BEFORE, Date.MOD_AFTER, Date.MOD_ABOUT) and len(value) < 4: raise DateError("Invalid value. Should be: (DD, MM, YY, slash)") if modifier in (Date.MOD_RANGE, Date.MOD_SPAN) and len(value) < 8: raise DateError("Invalid value. Should be: (DD, MM, " "YY, slash1, DD, MM, YY, slash2)") - if modifier not in (Date.MOD_NONE, Date.MOD_BEFORE, Date.MOD_AFTER, - Date.MOD_ABOUT, Date.MOD_RANGE, Date.MOD_SPAN, + if modifier not in (Date.MOD_NONE, Date.MOD_BEFORE, Date.MOD_AFTER, + Date.MOD_ABOUT, Date.MOD_RANGE, Date.MOD_SPAN, Date.MOD_TEXTONLY): raise DateError("Invalid modifier") - if quality not in (Date.QUAL_NONE, Date.QUAL_ESTIMATED, + if quality not in (Date.QUAL_NONE, Date.QUAL_ESTIMATED, Date.QUAL_CALCULATED): raise DateError("Invalid quality") if calendar not in Date.CALENDARS: @@ -1731,7 +1731,7 @@ class Date(object): Convert the date from the current calendar to the specified calendar. """ if (known_valid # if not known valid, round-trip convert anyway - and calendar == self.calendar + and calendar == self.calendar and self.newyear == Date.NEWYEAR_JAN1): return (year, month, day) = Date._calendar_change[calendar](self.sortval) @@ -1742,7 +1742,7 @@ class Date(object): self.dateval[Date._POS_RDAY]) sdn = Date._calendar_convert[self.calendar](ryear, rmonth, rday) (nyear, nmonth, nday) = Date._calendar_change[calendar](sdn) - self.dateval = (day, month, year, False, + self.dateval = (day, month, year, False, nday, nmonth, nyear, False) else: self.dateval = (day, month, year, False) @@ -1770,7 +1770,7 @@ class Date(object): return (self.modifier == Date.MOD_TEXTONLY and not self.text) or \ (self.get_start_date()==Date.EMPTY and self.get_stop_date()==Date.EMPTY) - + def is_compound(self): """ Return True if the date is a date range or a date span. @@ -1781,9 +1781,9 @@ class Date(object): def is_regular(self): """ Return True if the date is a regular date. - - The regular date is a single exact date, i.e. not text-only, not - a range or a span, not estimated/calculated, not about/before/after + + The regular date is a single exact date, i.e. not text-only, not + a range or a span, not estimated/calculated, not about/before/after date, and having year, month, and day all non-zero. """ return self.modifier == Date.MOD_NONE \ @@ -1853,9 +1853,9 @@ class Date(object): """ Lookup date modifier keyword, even if translated. """ - mods = ["none", "before", "after", "about", + mods = ["none", "before", "after", "about", "range", "span", "textonly"] - ui_mods = [_("none"), _("before"), _("after"), _("about"), + ui_mods = [_("none"), _("before"), _("after"), _("about"), _("range"), _("span"), _("textonly")] if modifier.lower() in mods: return mods.index(modifier.lower()) @@ -1863,11 +1863,11 @@ class Date(object): return ui_mods.index(modifier.lower()) else: raise AttributeError("invalid modifier: '%s'" % modifier) - + def to_calendar(self, calendar_name): """ Return a new Date object in the calendar calendar_name. - + >>> Date(1591, 1, 1).to_calendar("julian") 1590-12-22 (Julian) """ diff --git a/gramps/gen/lib/datebase.py b/gramps/gen/lib/datebase.py index 440625a47..48adde48f 100644 --- a/gramps/gen/lib/datebase.py +++ b/gramps/gen/lib/datebase.py @@ -42,7 +42,7 @@ class DateBase(object): def __init__(self, source=None): """ Create a new DateBase, copying from source if not None. - + :param source: Object used to initialize the new object :type source: DateBase """ @@ -65,7 +65,7 @@ class DateBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. diff --git a/gramps/gen/lib/event.py b/gramps/gen/lib/event.py index 259d1ef3a..9df0986f9 100644 --- a/gramps/gen/lib/event.py +++ b/gramps/gen/lib/event.py @@ -59,10 +59,10 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, The Event record is used to store information about some type of action that occurred at a particular place at a particular time, such as a birth, death, or marriage. - + A possible definition: Events are things that happen at some point in time - (that we may not know precisely, though), at some place, may involve - several people (witnesses, officers, notaries, priests, etc.) and may + (that we may not know precisely, though), at some place, may involve + several people (witnesses, officers, notaries, priests, etc.) and may of course have sources, notes, media, etc. Compare this with attribute: :class:`~.attribute.Attribute` """ @@ -82,7 +82,7 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, AttributeBase.__init__(self) DateBase.__init__(self, source) PlaceBase.__init__(self, source) - + if source: self.__description = source.__description self.__type = EventType(source.__type) @@ -93,9 +93,9 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, def serialize(self, no_text_date = False): """ Convert the data held in the event to a Python tuple that - represents all the data elements. - - This method is used to convert the object into a form that can easily + represents all the data elements. + + This method is used to convert the object into a form that can easily be saved to a database. These elements may be primitive Python types (string, integers), @@ -110,7 +110,7 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, """ return (self.handle, self.gramps_id, self.__type.serialize(), DateBase.serialize(self, no_text_date), - self.__description, self.place, + self.__description, self.place, CitationBase.serialize(self), NoteBase.serialize(self), MediaBase.serialize(self), @@ -121,7 +121,7 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -138,17 +138,17 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, :rtype: dict """ return {"_class": "Event", - "handle": Handle("Event", self.handle), - "gramps_id": self.gramps_id, + "handle": Handle("Event", self.handle), + "gramps_id": self.gramps_id, "type": self.__type.to_struct(), "date": DateBase.to_struct(self), - "description": self.__description, - "place": Handle("Place", self.place), + "description": self.__description, + "place": Handle("Place", self.place), "citation_list": CitationBase.to_struct(self), "note_list": NoteBase.to_struct(self), "media_list": MediaBase.to_struct(self), "attribute_list": AttributeBase.to_struct(self), - "change": self.change, + "change": self.change, "tag_list": TagBase.to_struct(self), "private": self.private} @@ -184,7 +184,7 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, :type data: tuple """ (self.handle, self.gramps_id, the_type, date, - self.__description, self.place, + self.__description, self.place, citation_list, note_list, media_list, attribute_list, self.change, tag_list, self.private) = data @@ -200,14 +200,14 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, def _has_handle_reference(self, classname, handle): """ - Return True if the object has reference to a given handle of given + Return True if the object has reference to a given handle of given primary object type. - + :param classname: The name of the primary object class. :type classname: str :param handle: The handle to be checked. :type handle: str - :returns: Returns whether the object has reference to this handle of + :returns: Returns whether the object has reference to this handle of this object type. :rtype: bool """ @@ -263,7 +263,7 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, """ Return the list of child secondary objects that may refer citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer citations. :rtype: list """ @@ -273,7 +273,7 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -283,7 +283,7 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -298,7 +298,7 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -316,7 +316,7 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, description = self.__description the_type = self.__type return (the_type == EventType.CUSTOM and date.is_empty() - and not place and not description) + and not place and not description) def are_equal(self, other): """ @@ -386,8 +386,8 @@ class Event(CitationBase, NoteBase, MediaBase, AttributeBase, def set_description(self, description): """ - Set the description of the Event to the passed string. - + Set the description of the Event to the passed string. + The string may contain any information. :param description: Description to assign to the Event diff --git a/gramps/gen/lib/eventref.py b/gramps/gen/lib/eventref.py index a9bf7c7c3..3830c8a89 100644 --- a/gramps/gen/lib/eventref.py +++ b/gramps/gen/lib/eventref.py @@ -83,7 +83,7 @@ class EventRef(PrivacyBase, NoteBase, AttributeBase, RefBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -159,7 +159,7 @@ class EventRef(PrivacyBase, NoteBase, AttributeBase, RefBase, """ Return the list of child secondary objects that may refer citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer citations. :rtype: list """ @@ -169,7 +169,7 @@ class EventRef(PrivacyBase, NoteBase, AttributeBase, RefBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -179,8 +179,8 @@ class EventRef(PrivacyBase, NoteBase, AttributeBase, RefBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - - :returns: Returns the list of (classname, handle) tuples for referenced + + :returns: Returns the list of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -191,9 +191,9 @@ class EventRef(PrivacyBase, NoteBase, AttributeBase, RefBase, def get_handle_referents(self): """ - Return the list of child objects which may, directly or through their + Return the list of child objects which may, directly or through their children, reference primary objects.. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ diff --git a/gramps/gen/lib/eventtype.py b/gramps/gen/lib/eventtype.py index a4871d72d..036af7626 100644 --- a/gramps/gen/lib/eventtype.py +++ b/gramps/gen/lib/eventtype.py @@ -41,7 +41,7 @@ from .grampstype import GrampsType class EventType(GrampsType): """ Event types. - + .. attribute UNKNOWN: Unknown .. attribute CUSTOM: Custom .. attribute ADOPT: Adopted @@ -264,7 +264,7 @@ class EventType(GrampsType): def __init__(self, value=None): GrampsType.__init__(self, value) - + def is_birth(self): """ Returns True if EventType is BIRTH, False @@ -278,14 +278,14 @@ class EventType(GrampsType): otherwise. """ return self.value == self.BAPTISM - + def is_death(self): """ Returns True if EventType is DEATH, False otherwise. """ return self.value == self.DEATH - + def is_burial(self): """ Returns True if EventType is BURIAL, False @@ -298,16 +298,16 @@ class EventType(GrampsType): Returns True if EventType is a birth fallback, False otherwise. """ - return self.value in [self.CHRISTEN, + return self.value in [self.CHRISTEN, self.BAPTISM] - + def is_death_fallback(self): """ Returns True if EventType is a death fallback, False otherwise. """ - return self.value in [self.BURIAL, - self.CREMATION, + return self.value in [self.BURIAL, + self.CREMATION, self.CAUSE_DEATH] def is_marriage(self): """ @@ -320,7 +320,7 @@ class EventType(GrampsType): Returns True if EventType is a marriage fallback, False otherwise. """ - return self.value in [self.ENGAGEMENT, + return self.value in [self.ENGAGEMENT, self.MARR_ALT] def is_divorce(self): @@ -334,7 +334,7 @@ class EventType(GrampsType): Returns True if EventType is a divorce fallback, False otherwise. """ - return self.value in [self.ANNULMENT, + return self.value in [self.ANNULMENT, self.DIV_FILING] def is_relationship_event(self): diff --git a/gramps/gen/lib/family.py b/gramps/gen/lib/family.py index 6cf0aaf0b..956d03b89 100644 --- a/gramps/gen/lib/family.py +++ b/gramps/gen/lib/family.py @@ -63,7 +63,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, The Family record is the Gramps in-memory representation of the relationships between people. It contains all the information related to the relationship. - + Family objects are usually created in one of two ways. 1. Creating a new Family object, which is then initialized and @@ -78,9 +78,9 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, def __init__(self): """ - Create a new Family instance. - - After initialization, most data items have empty or null values, + Create a new Family instance. + + After initialization, most data items have empty or null values, including the database handle. """ PrimaryObject.__init__(self) @@ -99,9 +99,9 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, def serialize(self): """ Convert the data held in the event to a Python tuple that - represents all the data elements. - - This method is used to convert the object into a form that can easily + represents all the data elements. + + This method is used to convert the object into a form that can easily be saved to a database. These elements may be primitive Python types (string, integers), @@ -130,7 +130,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -147,8 +147,8 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, :rtype: dict """ return {"_class": "Family", - "handle": Handle("Family", self.handle), - "gramps_id": self.gramps_id, + "handle": Handle("Family", self.handle), + "gramps_id": self.gramps_id, "father_handle": Handle("Person", self.father_handle), "mother_handle": Handle("Person", self.mother_handle), "child_ref_list": [cr.to_struct() for cr in self.child_ref_list], @@ -159,8 +159,8 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, "lds_ord_list": LdsOrdBase.to_struct(self), "citation_list": CitationBase.to_struct(self), "note_list": NoteBase.to_struct(self), - "change": self.change, - "tag_list": TagBase.to_struct(self), + "change": self.change, + "tag_list": TagBase.to_struct(self), "private": self.private} @classmethod @@ -183,8 +183,8 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, LdsOrdBase.from_struct(struct.get("lds_ord_list", default.lds_ord_list)), CitationBase.from_struct(struct.get("citation_list", default.citation_list)), NoteBase.from_struct(struct.get("note_list", default.note_list)), - struct.get("change", default.change), - TagBase.from_struct(struct.get("tag_list", default.tag_list)), + struct.get("change", default.change), + TagBase.from_struct(struct.get("tag_list", default.tag_list)), struct.get("private", default.private)) def unserialize(self, data): @@ -213,14 +213,14 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, def _has_handle_reference(self, classname, handle): """ - Return True if the object has reference to a given handle of given + Return True if the object has reference to a given handle of given primary object type. - + :param classname: The name of the primary object class. :type classname: str :param handle: The handle to be checked. :type handle: str - :returns: Returns whether the object has reference to this handle of + :returns: Returns whether the object has reference to this handle of this object type. :rtype: bool """ @@ -338,7 +338,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, """ Return the list of child secondary objects that may refer citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer citations. :rtype: list """ @@ -350,7 +350,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -363,7 +363,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -378,9 +378,9 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, def get_handle_referents(self): """ - Return the list of child objects which may, directly or through their + Return the list of child objects which may, directly or through their children, reference primary objects.. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -411,14 +411,14 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, def set_relationship(self, relationship_type): """ Set the relationship type between the people identified as the - father and mother in the relationship. - - The type is a tuple whose first item is an integer constant and whose + father and mother in the relationship. + + The type is a tuple whose first item is an integer constant and whose second item is the string. The valid values are: - ========================= ============================================ + ========================= ============================================ Type Description - ========================= ============================================ + ========================= ============================================ FamilyRelType.MARRIED indicates a legally recognized married relationship between two individuals. This may be either an opposite or a same sex @@ -434,7 +434,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, FamilyRelType.CUSTOM indicates that the type of relationship between the two individuals does not match any of the other types. - ========================= ============================================ + ========================= ============================================ :param relationship_type: (int,str) tuple of the relationship type between the father and mother of the relationship. @@ -451,10 +451,10 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, def set_father_handle(self, person_handle): """ - Set the database handle for :class:`~.person.Person` that corresponds - to male of the relationship. - - For a same sex relationship, this can represent either of people + Set the database handle for :class:`~.person.Person` that corresponds + to male of the relationship. + + For a same sex relationship, this can represent either of people involved in the relationship. :param person_handle: :class:`~.person.Person` database handle @@ -464,7 +464,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, def get_father_handle(self): """ - Return the database handle of the :class:`~.person.Person` identified + Return the database handle of the :class:`~.person.Person` identified as the father of the Family. :returns: :class:`~.person.Person` database handle @@ -474,10 +474,10 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, def set_mother_handle(self, person_handle): """ - Set the database handle for :class:`~.person.Person` that corresponds - to male of the relationship. - - For a same sex relationship, this can represent either of people + Set the database handle for :class:`~.person.Person` that corresponds + to male of the relationship. + + For a same sex relationship, this can represent either of people involved in the relationship. :param person_handle: :class:`~.person.Person` database handle @@ -487,7 +487,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, def get_mother_handle(self): """ - Return the database handle of the :class:`~.person.Person` identified + Return the database handle of the :class:`~.person.Person` identified as the mother of the Family. :returns: :class:`~.person.Person` database handle @@ -506,7 +506,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, if not isinstance(child_ref, ChildRef): raise ValueError("expecting ChildRef instance") self.child_ref_list.append(child_ref) - + def remove_child_ref(self, child_ref): """ Remove the database handle for :class:`~.person.Person` to the Family's @@ -584,10 +584,10 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, """ Add the :class:`~.eventref.EventRef` to the Family instance's :class:`~.eventref.EventRef` list. - + This is accomplished by assigning the :class:`~.eventref.EventRef` for the valid :class:`~.event.Event` in the current database. - + :param event_ref: the :class:`~.eventref.EventRef` to be added to the Person's :class:`~.eventref.EventRef` list. :type event_ref: EventRef @@ -611,7 +611,7 @@ class Family(CitationBase, NoteBase, MediaBase, AttributeBase, LdsOrdBase, Return the list of :class:`~.eventref.EventRef` objects associated with :class:`~.event.Event` instances. - :returns: Returns the list of :class:`~.eventref.EventRef` objects + :returns: Returns the list of :class:`~.eventref.EventRef` objects associated with the Family instance. :rtype: list """ diff --git a/gramps/gen/lib/gcalendar.py b/gramps/gen/lib/gcalendar.py index db4f85d41..4af744751 100644 --- a/gramps/gen/lib/gcalendar.py +++ b/gramps/gen/lib/gcalendar.py @@ -102,36 +102,36 @@ def _tishri1(metonic_year, molad_day, molad_halakim): def _tishri_molad(input_day): """ - Estimate the metonic cycle number. - - Note that this may be an under estimate because there are 6939.6896 days - in a metonic cycle not 6940, but it will never be an over estimate. The - loop below will correct for any error in this estimate. + Estimate the metonic cycle number. + + Note that this may be an under estimate because there are 6939.6896 days + in a metonic cycle not 6940, but it will never be an over estimate. The + loop below will correct for any error in this estimate. """ - + metonic_cycle = (input_day + 310) // 6940 - + # Calculate the time of the starting molad for this metonic cycle. - + (molad_day, molad_halakim) = _molad_of_metonic_cycle(metonic_cycle) - + # If the above was an under estimate, increment the cycle number until # the correct one is found. For modern dates this loop is about 98.6% # likely to not execute, even once, because the above estimate is # really quite close. - - while molad_day < (input_day - 6940 + 310): + + while molad_day < (input_day - 6940 + 310): metonic_cycle += 1 molad_halakim += _HBR_HALAKIM_PER_METONIC_CYCLE molad_day += molad_halakim // _HBR_HALAKIM_PER_DAY molad_halakim = molad_halakim % _HBR_HALAKIM_PER_DAY # Find the molad of Tishri closest to this date. - + for metonic_year in range(0, 20): if molad_day > input_day - 74: break - + molad_halakim += (_HBR_HALAKIM_PER_LUNAR_CYCLE * _HBR_MONTHS_PER_YEAR[metonic_year]) molad_day += molad_halakim // _HBR_HALAKIM_PER_DAY @@ -153,20 +153,20 @@ def _molad_of_metonic_cycle(metonic_cycle): r1 = r1 + (metonic_cycle * (_HBR_HALAKIM_PER_METONIC_CYCLE & 0xFFFF)) r2 = r1 >> 16 r2 = r2 + (metonic_cycle * ((_HBR_HALAKIM_PER_METONIC_CYCLE >> 16)&0xFFFF)) - + # Calculate r2r1 / HALAKIM_PER_DAY. The remainder will be in r1, the # upper 16 bits of the quotient will be in d2 and the lower 16 bits # will be in d1. - + d2 = r2 // _HBR_HALAKIM_PER_DAY r2 -= d2 * _HBR_HALAKIM_PER_DAY r1 = (r2 << 16) | (r1 & 0xFFFF) d1 = r1 // _HBR_HALAKIM_PER_DAY r1 -= d1 * _HBR_HALAKIM_PER_DAY - + molad_day = (d2 << 16) | d1 molad_halakim = r1 - + return (molad_day, molad_halakim) def _start_of_year(year): @@ -181,16 +181,16 @@ def _start_of_year(year): * _HBR_YEAR_OFFSET[metonic_year]) molad_day = molad_day + (molad_halakim // _HBR_HALAKIM_PER_DAY) molad_halakim = molad_halakim % _HBR_HALAKIM_PER_DAY - + pTishri1 = _tishri1(metonic_year, molad_day, molad_halakim) - + return (metonic_cycle, metonic_year, molad_day, molad_halakim, pTishri1) def hebrew_sdn(year, month, day): """Convert a Jewish calendar date to an SDN number.""" - + if month == 1 or month == 2: - # It is Tishri or Heshvan - don't need the year length. + # It is Tishri or Heshvan - don't need the year length. (metonic_cycle, metonic_year, molad_day, molad_halakim, tishri1) = _start_of_year(year) if month == 1: @@ -200,7 +200,7 @@ def hebrew_sdn(year, month, day): elif month == 3: # It is Kislev - must find the year length. - # Find the start of the year. + # Find the start of the year. (metonic_cycle, metonic_year, molad_day, molad_halakim, tishri1) = _start_of_year(year) @@ -211,24 +211,24 @@ def hebrew_sdn(year, month, day): molad_halakim = molad_halakim % _HBR_HALAKIM_PER_DAY tishri1_after = _tishri1((metonic_year + 1) % 19, molad_day, molad_halakim) - + year_length = tishri1_after - tishri1 - + if year_length == 355 or year_length == 385: sdn = tishri1 + day + 59 else: sdn = tishri1 + day + 58 elif month == 4 or month == 5 or month == 6: # It is Tevet, Shevat or Adar I - don't need the year length - + (metonic_cycle, metonic_year, molad_day, molad_halakim, tishri1_after) = _start_of_year(year+1) - + if _HBR_MONTHS_PER_YEAR[(year - 1) % 19] == 12: length_of_adarI_andII = 29 else: length_of_adarI_andII = 59 - + if month == 4: sdn = tishri1_after + day - length_of_adarI_andII - 237 elif month == 5: @@ -239,7 +239,7 @@ def hebrew_sdn(year, month, day): # It is Adar II or later - don't need the year length. (metonic_cycle, metonic_year, molad_day, molad_halakim, tishri1_after) = _start_of_year(year+1) - + if month == 7: sdn = tishri1_after + day - 207 elif month == 8: @@ -260,16 +260,16 @@ def hebrew_sdn(year, month, day): def hebrew_ymd(sdn): """Convert an SDN number to a Hebrew calendar date.""" - + input_day = sdn - _HBR_SDN_OFFSET # TODO if input_day <= 0, the result is a date invalid in Hebrew calendar! (metonic_cycle, metonic_year, day1, halakim) = _tishri_molad(input_day) tishri1 = _tishri1(metonic_year, day1, halakim) - + if input_day >= tishri1: # It found Tishri 1 at the start of the year - + year = (metonic_cycle * 19) + metonic_year + 1 if input_day < tishri1 + 59: if input_day < tishri1 + 30: @@ -290,7 +290,7 @@ def hebrew_ymd(sdn): tishri1_after = _tishri1((metonic_year + 1) % 19, day1, halakim) else: # It found Tishri 1 at the end of the year. - + year = metonic_cycle * 19 + metonic_year if input_day >= tishri1 - 177: # It is one of the last 6 months of the year. @@ -332,7 +332,7 @@ def hebrew_ymd(sdn): return (year, month, day) month -= 1 day += 30 - + if day > 0: return (year, month, day) month -= 1 @@ -349,7 +349,7 @@ def hebrew_ymd(sdn): year_length = tishri1_after - tishri1 day = input_day - tishri1 - 29 if year_length == 355 or year_length == 385 : - # Heshvan has 30 days + # Heshvan has 30 days if day <= 30: month = 2 return (year, month, day) @@ -396,7 +396,7 @@ def julian_ymd(sdn): temp = day_of_year * 5 - 3 month = temp // _JLN_DAYS_PER_5_MONTHS day = (temp % _JLN_DAYS_PER_5_MONTHS) // 5 + 1 - + # Convert to the normal beginning of the year if month < 10: month += 3 @@ -437,24 +437,24 @@ def gregorian_ymd(sdn): # Calculate the century (year/100) century = temp // _GRG_DAYS_PER_400_YEARS - + # Calculate the year and day of year (1 <= day_of_year <= 366) temp = ((temp % _GRG_DAYS_PER_400_YEARS) // 4) * 4 + 3 year = (century * 100) + (temp // _GRG_DAYS_PER_4_YEARS) day_of_year = (temp % _GRG_DAYS_PER_4_YEARS) // 4 + 1 - + # Calculate the month and day of month temp = day_of_year * 5 - 3 month = temp // _GRG_DAYS_PER_5_MONTHS day = (temp % _GRG_DAYS_PER_5_MONTHS) // 5 + 1 - + # Convert to the normal beginning of the year if month < 10 : month = month + 3 else: year = year + 1 month = month - 9 - + # Adjust to the B.C./A.D. type numbering year = year - 4800 if year <= 0: @@ -490,7 +490,7 @@ def persian_sdn(year, month, day): epbase = year - 474 else: epbase = year - 473 - + epyear = 474 + epbase % 2820 if month <= 7: @@ -500,13 +500,13 @@ def persian_sdn(year, month, day): v2 = ((epyear * 682) - 110) // 2816 v3 = (epyear - 1) * 365 + day v4 = (epbase // 2820) * 1029983 - + return int(math.ceil(v1 + v2 + v3 + v4 + _PRS_EPOCH - 1)) def persian_ymd(sdn): """Convert an SDN number to a Persian calendar date.""" sdn = math.floor(sdn) + 0.5 #float - + depoch = sdn - 2121446 #float cycle = math.floor(depoch / 1029983) #int cyear = depoch % 1029983 #int @@ -516,7 +516,7 @@ def persian_ymd(sdn): aux1 = cyear // 366 #int aux2 = cyear % 366 #int ycycle = (((2134*aux1)+(2816*aux2)+2815) // 1028522) + aux1 + 1 - + year = ycycle + (2820 * cycle) + 474 if year <= 0: year = year - 1 diff --git a/gramps/gen/lib/genderstats.py b/gramps/gen/lib/genderstats.py index bfc35c33d..12f62fc0a 100644 --- a/gramps/gen/lib/genderstats.py +++ b/gramps/gen/lib/genderstats.py @@ -32,14 +32,14 @@ from .person import Person #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class GenderStats(object): """ - Class for keeping track of statistics related to Given Name vs. Gender. - - This allows the tracking of the liklihood of a person's given name + Class for keeping track of statistics related to Given Name vs. Gender. + + This allows the tracking of the liklihood of a person's given name indicating the gender of the person. """ def __init__ (self, stats={}): @@ -77,7 +77,7 @@ class GenderStats(object): return self._set_stats(keyname, gender) - + def count_person (self, person, undo = 0): if not person: return diff --git a/gramps/gen/lib/grampstype.py b/gramps/gen/lib/grampstype.py index 2e018ea6f..acb95fc47 100644 --- a/gramps/gen/lib/grampstype.py +++ b/gramps/gen/lib/grampstype.py @@ -41,33 +41,33 @@ _UNKNOWN = _('Unknown') class GrampsTypeMeta(type): """ Metaclass for :class:`~.grampstype.GrampsType`. - + Create the class-specific integer/string maps. """ def __init__(cls, name, bases, namespace): - # Helper function to create the maps + # Helper function to create the maps def init_map(data, key_col, data_col, blacklist=None): """ Initialize the map, building a new map from the specified columns. """ if blacklist: - return dict([(item[key_col], item[data_col]) + return dict([(item[key_col], item[data_col]) for item in data if not item[0] in blacklist]) else: return dict([(item[key_col], item[data_col]) for item in data]) - - # Call superclass initialization + + # Call superclass initialization type.__init__(cls, name, bases, namespace) - + # Build the integer/string maps if hasattr(cls, '_DATAMAP'): cls._I2SMAP = init_map(cls._DATAMAP, 0, 1, cls._BLACKLIST) cls._S2IMAP = init_map(cls._DATAMAP, 1, 0, cls._BLACKLIST) cls._I2EMAP = init_map(cls._DATAMAP, 0, 2, cls._BLACKLIST) - cls._E2IMAP = init_map(cls._DATAMAP, 2, 0, cls._BLACKLIST) - + cls._E2IMAP = init_map(cls._DATAMAP, 2, 0, cls._BLACKLIST) + # Python 2 and 3 metaclass children classes GrampsTypeC = GrampsTypeMeta(str('GrampsTypeC'), (object, ), {}) @@ -80,29 +80,29 @@ GrampsTypeC = GrampsTypeMeta(str('GrampsTypeC'), (object, ), {}) ## python 3: class GrampsType(object, metaclass=GrampsTypeMeta): class GrampsType(GrampsTypeC): """Base class for all Gramps object types. - - :cvar _DATAMAP: + + :cvar _DATAMAP: (list) 3-tuple like (index, localized_string, english_string). - :cvar _BLACKLIST: + :cvar _BLACKLIST: List of indices to ignore (obsolete/retired entries). (gramps policy is never to delete type values, or reuse the name (TOKEN) of any specific type value) - :cvar POS_: (int) + :cvar POS_: (int) Position of attribute in the serialized format of an instance. .. warning:: The POS_ class variables reflect the serialized object, they have to be updated in case the data structure or the :meth:`serialize` method changes! - + :cvar _CUSTOM: (int) a custom type object :cvar _DEFAULT: (int) the default type, used on creation - + :attribute value: (int) Returns or sets integer value :attribute string: (str) Returns or sets string value """ (POS_VALUE, POS_STRING) = list(range(2)) - + _CUSTOM = 0 _DEFAULT = 0 @@ -120,10 +120,10 @@ class GrampsType(GrampsTypeC): self.__string = dict_['__string'] else: self.__string = '' - + def __init__(self, value=None): """ - Create a new type, initialize the value from one of several possible + Create a new type, initialize the value from one of several possible states. """ self.set(value) @@ -175,7 +175,7 @@ class GrampsType(GrampsTypeC): def set_from_xml_str(self, value): """ - This method sets the type instance based on the untranslated string + This method sets the type instance based on the untranslated string (obtained e.g. from XML). """ if value in self._E2IMAP: @@ -191,7 +191,7 @@ class GrampsType(GrampsTypeC): def xml_str(self): """ - Return the untranslated string (e.g. suitable for XML) corresponding + Return the untranslated string (e.g. suitable for XML) corresponding to the type. """ if self.__value == self._CUSTOM: @@ -209,7 +209,7 @@ class GrampsType(GrampsTypeC): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -226,7 +226,7 @@ class GrampsType(GrampsTypeC): :rtype: dict """ return {"_class": self.__class__.__name__, - "value": self.__value, + "value": self.__value, "string": str(self)} @classmethod @@ -279,7 +279,7 @@ class GrampsType(GrampsTypeC): def get_custom(self): return self._CUSTOM - + def get_menu(self): """Return the list of localized names for the menu.""" if self._MENU: @@ -311,7 +311,7 @@ class GrampsType(GrampsTypeC): def __ne__(self, value): return not self.__eq__(value) - + ## Python 3 does not have __cmp__ ## def __cmp__(self, value): ## print ('cmp', type(value), str) diff --git a/gramps/gen/lib/handle.py b/gramps/gen/lib/handle.py index 86842dfab..2fb003a3e 100644 --- a/gramps/gen/lib/handle.py +++ b/gramps/gen/lib/handle.py @@ -21,7 +21,7 @@ class HandleClass(str): def __init__(self, handle): super(HandleClass, self).__init__() - + def Handle(classname, handle): if handle is None: return None diff --git a/gramps/gen/lib/ldsord.py b/gramps/gen/lib/ldsord.py index ac1092d94..e82f43a4a 100644 --- a/gramps/gen/lib/ldsord.py +++ b/gramps/gen/lib/ldsord.py @@ -55,8 +55,8 @@ from .const import IDENTICAL, EQUAL, DIFFERENT class LdsOrd(SecondaryObject, CitationBase, NoteBase, DateBase, PlaceBase, PrivacyBase): """ - Class that contains information about LDS Ordinances. - + Class that contains information about LDS Ordinances. + LDS ordinances are similar to events, but have very specific additional information related to data collected by the Church of Jesus Christ of Latter Day Saints (Mormon church). The LDS church is the largest @@ -68,7 +68,7 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, SEAL_TO_PARENTS = 2 SEAL_TO_SPOUSE = 3 CONFIRMATION = 4 - + DEFAULT_TYPE = BAPTISM @@ -97,7 +97,7 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, (SEAL_TO_PARENTS, _('Sealed to Parents'), 'sealed_to_parents'), (SEAL_TO_SPOUSE, _('Sealed to Spouse'), 'sealed_to_spouse' ), ] - + _STATUS_MAP = [ (STATUS_NONE, _(""), ""), (STATUS_BIC, _("BIC"), "BIC"), @@ -122,7 +122,7 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, DateBase.__init__(self, source) PlaceBase.__init__(self, source) PrivacyBase.__init__(self, source) - + if source: self.type = source.type self.famc = source.famc @@ -148,7 +148,7 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -168,11 +168,11 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, "citation_list": CitationBase.to_struct(self), "note_list": NoteBase.to_struct(self), "date": DateBase.to_struct(self), - "type": self.type, + "type": self.type, "place": self.place, - "famc": self.famc, - "temple": self.temple, - "status": self.status, + "famc": self.famc, + "temple": self.temple, + "status": self.status, "private": self.private} @classmethod @@ -227,7 +227,7 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -237,7 +237,7 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -253,7 +253,7 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -322,8 +322,8 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, def set_status(self, val): """ - Set the status of the LDS ordinance. - + Set the status of the LDS ordinance. + The status is a text string that matches a predefined set of strings. """ self.status = val @@ -342,15 +342,15 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, def is_empty(self): """Return 1 if the ordinance is actually empty.""" - if (self.famc or - (self.date and not self.date.is_empty()) or - self.temple or - self.status or + if (self.famc or + (self.date and not self.date.is_empty()) or + self.temple or + self.status or self.place): return False else: return True - + def are_equal(self, other): """Return 1 if the specified ordinance is the same as the instance.""" warn( "Use is_equal instead are_equal", DeprecationWarning, 2) @@ -377,7 +377,7 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, def set_type_from_xml(self, xml_str): """ Set type based on a given string from XML. - + Return boolean on success. """ for item in LdsOrd._TYPE_MAP: @@ -407,7 +407,7 @@ class LdsOrd(SecondaryObject, CitationBase, NoteBase, def set_status_from_xml(self, xml_str): """ Set status based on a given string from XML. - + Return boolean on success. """ for item in LdsOrd._STATUS_MAP: diff --git a/gramps/gen/lib/ldsordbase.py b/gramps/gen/lib/ldsordbase.py index bfe40bf16..8e2a9b4c5 100644 --- a/gramps/gen/lib/ldsordbase.py +++ b/gramps/gen/lib/ldsordbase.py @@ -43,15 +43,15 @@ class LdsOrdBase(object): def __init__(self, source=None): """ - Initialize a LdsOrdBase. - - If the source is not None, then object is initialized from values of + Initialize a LdsOrdBase. + + If the source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object :type source: LdsOrdBase """ - + if source: self.lds_ord_list = [LdsOrd(lds_ord) for lds_ord in source.lds_ord_list] @@ -68,7 +68,7 @@ class LdsOrdBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -116,7 +116,7 @@ class LdsOrdBase(object): """ Remove the specified :class:`~.ldsord.LdsOrd` instance from the lds_ord list. - + If the instance does not exist in the list, the operation has no effect. :param lds_ord: :class:`~.ldsord.LdsOrd` instance to remove from the @@ -147,7 +147,7 @@ class LdsOrdBase(object): """ Assign the passed list to the object's list of :class:`~.ldsord.LdsOrd` instances. - + :param lds_ord_list: List of :class:`~.ldsord.LdsOrd` instances to be associated with the object :type lds_ord_list: list diff --git a/gramps/gen/lib/location.py b/gramps/gen/lib/location.py index 56834075b..747c39814 100644 --- a/gramps/gen/lib/location.py +++ b/gramps/gen/lib/location.py @@ -46,7 +46,7 @@ class Location(SecondaryObject, LocationBase): Multiple Location objects can represent the same place, since names of cities, counties, states, and even countries can change with time. """ - + def __init__(self, source=None): """ Create a Location object, copying from the source object if it exists. @@ -67,7 +67,7 @@ class Location(SecondaryObject, LocationBase): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -84,13 +84,13 @@ class Location(SecondaryObject, LocationBase): :rtype: dict """ return {"_class": "Location", - "street": self.street, - "locality": self.locality, - "city": self.city, - "county": self.county, + "street": self.street, + "locality": self.locality, + "city": self.city, + "county": self.county, "state": self.state, - "country": self.country, - "postal": self.postal, + "country": self.country, + "postal": self.postal, "phone": self.phone, "parish": self.parish} @@ -109,9 +109,9 @@ class Location(SecondaryObject, LocationBase): struct.get("state", default.state), struct.get("country", default.country), struct.get("postal", default.postal), - struct.get("phone", default.phone)), + struct.get("phone", default.phone)), struct.get("parish", default.parish)) - + def unserialize(self, data): """ Convert a serialized tuple of data to an object. @@ -158,7 +158,7 @@ class Location(SecondaryObject, LocationBase): return not self.street and not self.locality and not self.city and \ not self.county and not self.state and not self.country and \ not self.postal and not self.phone - + def set_parish(self, data): """Set the religious parish name.""" self.parish = data diff --git a/gramps/gen/lib/locationbase.py b/gramps/gen/lib/locationbase.py index 55330dfed..eb0508fb8 100644 --- a/gramps/gen/lib/locationbase.py +++ b/gramps/gen/lib/locationbase.py @@ -32,10 +32,10 @@ class LocationBase(object): """ Base class for all things Address. """ - + def __init__(self, source=None): """ - Create a LocationBase object, copying from the source object if it + Create a LocationBase object, copying from the source object if it exists. """ if source: @@ -68,7 +68,7 @@ class LocationBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -86,13 +86,13 @@ class LocationBase(object): """ return { "_class": "LocationBase", - "street": self.street, - "locality": self.locality, - "city": self.city, - "county": self.county, + "street": self.street, + "locality": self.locality, + "city": self.city, + "county": self.county, "state": self.state, - "country": self.country, - "postal": self.postal, + "country": self.country, + "postal": self.postal, "phone": self.phone } diff --git a/gramps/gen/lib/mediabase.py b/gramps/gen/lib/mediabase.py index dadc83eb3..eebd3fdc3 100644 --- a/gramps/gen/lib/mediabase.py +++ b/gramps/gen/lib/mediabase.py @@ -40,11 +40,11 @@ class MediaBase(object): """ Base class for storing media references. """ - + def __init__(self, source=None): """ Create a new MediaBase, copying from source if not None. - + :param source: Object used to initialize the new object :type source: MediaBase """ @@ -60,7 +60,7 @@ class MediaBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -153,7 +153,7 @@ class MediaBase(object): :param obj_handle: The media handle to be checked. :type obj_handle: str - :returns: Returns whether the object or any of it's child objects has + :returns: Returns whether the object or any of it's child objects has reference to this media handle. :rtype: bool """ diff --git a/gramps/gen/lib/mediaobj.py b/gramps/gen/lib/mediaobj.py index 9fdd3304a..6d4c0cab7 100644 --- a/gramps/gen/lib/mediaobj.py +++ b/gramps/gen/lib/mediaobj.py @@ -59,12 +59,12 @@ class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase, Container for information about an image file, including location, description and privacy. """ - + def __init__(self, source=None): """ - Initialize a MediaObject. - - If source is not None, then object is initialized from values of the + Initialize a MediaObject. + + If source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object @@ -92,9 +92,9 @@ class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase, def serialize(self, no_text_date = False): """ Convert the data held in the event to a Python tuple that - represents all the data elements. - - This method is used to convert the object into a form that can easily + represents all the data elements. + + This method is used to convert the object into a form that can easily be saved to a database. These elements may be primitive Python types (string, integers), @@ -121,7 +121,7 @@ class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -138,10 +138,10 @@ class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase, :rtype: dict """ return {"_class": "MediaObject", - "handle": Handle("Media", self.handle), - "gramps_id": self.gramps_id, - "path": self.path, - "mime": self.mime, + "handle": Handle("Media", self.handle), + "gramps_id": self.gramps_id, + "path": self.path, + "mime": self.mime, "desc": self.desc, "checksum": self.checksum, "attribute_list": AttributeBase.to_struct(self), @@ -215,7 +215,7 @@ class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase, """ Return the list of child secondary objects that may refer to citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer to citations. :rtype: list """ @@ -225,7 +225,7 @@ class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -235,7 +235,7 @@ class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -247,7 +247,7 @@ class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -285,7 +285,7 @@ class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase, :rtype: str """ return self.mime - + def set_path(self, path): """Set the file path to the passed path.""" res = urlparse(path) diff --git a/gramps/gen/lib/mediaref.py b/gramps/gen/lib/mediaref.py index baf151d9c..6a40a27fb 100644 --- a/gramps/gen/lib/mediaref.py +++ b/gramps/gen/lib/mediaref.py @@ -74,7 +74,7 @@ class MediaRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -138,7 +138,7 @@ class MediaRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase, """ Return the list of child secondary objects that may refer Citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer Citations. :rtype: list """ @@ -148,7 +148,7 @@ class MediaRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -158,7 +158,7 @@ class MediaRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -172,7 +172,7 @@ class MediaRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ diff --git a/gramps/gen/lib/name.py b/gramps/gen/lib/name.py index 2bedce453..4bc1ef5ea 100644 --- a/gramps/gen/lib/name.py +++ b/gramps/gen/lib/name.py @@ -60,7 +60,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, FNLN = 2 # first name last name FN = 4 # first name LNFNP= 5 # primary name primconnector rest, given pa/ma suffix, primprefix - + NAMEFORMATS = (DEF, LNFN, FNLN, FN, LNFNP) #deprecated : PTFN = 3 # patronymic first name @@ -70,7 +70,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, We should connect here to 'person-groupname-rebuild' and do something correct when first parameter is the name, and second parameter is different from the group here. However, that would be complicated and - no real errors that cannot be ammended can be done if group is + no real errors that cannot be ammended can be done if group is saved differently. """ PrivacyBase.__init__(self, source) @@ -120,10 +120,10 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, CitationBase.serialize(self), NoteBase.serialize(self), DateBase.serialize(self), - self.first_name, + self.first_name, SurnameBase.serialize(self), self.suffix, self.title, - self.type.serialize(), + self.type.serialize(), self.group_as, self.sort_as, self.display_as, self.call, self.nick, self.famnick) @@ -131,7 +131,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -152,16 +152,16 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, "citation_list": CitationBase.to_struct(self), "note_list": NoteBase.to_struct(self), "date": DateBase.to_struct(self), - "first_name": self.first_name, + "first_name": self.first_name, "surname_list": SurnameBase.to_struct(self), - "suffix": self.suffix, + "suffix": self.suffix, "title": self.title, - "type": self.type.to_struct(), - "group_as": self.group_as, - "sort_as": self.sort_as, - "display_as": self.display_as, + "type": self.type.to_struct(), + "group_as": self.group_as, + "sort_as": self.sort_as, + "display_as": self.display_as, "call": self.call, - "nick": self.nick, + "nick": self.nick, "famnick": self.famnick} @classmethod @@ -175,19 +175,19 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, return (PrivacyBase.from_struct(struct.get("private", default.private)), CitationBase.from_struct(struct.get("citation_list", default.citation_list)), NoteBase.from_struct(struct.get("note_list", default.note_list)), - DateBase.from_struct(struct.get("date", {})), + DateBase.from_struct(struct.get("date", {})), struct.get("first_name", default.first_name), - SurnameBase.from_struct(struct.get("surname_list", default.surname_list)), - struct.get("suffix", default.suffix), - struct.get("title", default.title), - NameType.from_struct(struct.get("type", {})), + SurnameBase.from_struct(struct.get("surname_list", default.surname_list)), + struct.get("suffix", default.suffix), + struct.get("title", default.title), + NameType.from_struct(struct.get("type", {})), struct.get("group_as", default.group_as), struct.get("sort_as", default.sort_as), struct.get("display_as", default.display_as), struct.get("call", default.call), struct.get("nick", default.nick), struct.get("famnick", default.famnick)) - + def is_empty(self): """ Indicate if the name is empty. @@ -195,7 +195,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, namefieldsempty = (self.first_name == "" and self.suffix == "" and self.title == "" and self.nick == "" and self.famnick == "") - surnamefieldsempty = not (False in + surnamefieldsempty = not (False in [surn.is_empty() for surn in self.surname_list]) return namefieldsempty and surnamefieldsempty @@ -205,7 +205,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, """ (privacy, citation_list, note_list, date, self.first_name, surname_list, self.suffix, self.title, name_type, - self.group_as, self.sort_as, self.display_as, self.call, + self.group_as, self.sort_as, self.display_as, self.call, self.nick, self.famnick) = data self.type = NameType(name_type) PrivacyBase.unserialize(self, privacy) @@ -238,7 +238,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -248,7 +248,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -258,7 +258,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -289,7 +289,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, def merge(self, acquisition): """ Merge the content of acquisition into this name. - Normally the person merge code should opt for adding an alternate + Normally the person merge code should opt for adding an alternate name if names are actually different (like not equal surname list) Lost: type, first, call, suffix, title, nick, famnick and date of @@ -306,12 +306,12 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, def set_group_as(self, name): """ - Set the grouping name for a person. - - Normally, this is the person's surname. However, some locales group - equivalent names (e.g. Ivanova and Ivanov in Russian are usually + Set the grouping name for a person. + + Normally, this is the person's surname. However, some locales group + equivalent names (e.g. Ivanova and Ivanov in Russian are usually considered equivalent. - + .. note:: There is also a database wide grouping set_name_group_mapping So one might map a name Smith to SmithNew, and have one person still grouped with name Smith. Hence, group_as can be equal to surname! @@ -335,62 +335,62 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, def set_sort_as(self, value): """ - Specifies the sorting method for the specified name. - - Typically the locale's default should be used. However, there may be - names where a specific sorting structure is desired for a name. + Specifies the sorting method for the specified name. + + Typically the locale's default should be used. However, there may be + names where a specific sorting structure is desired for a name. """ self.sort_as = value def get_sort_as(self): """ - Return the selected sorting method for the name. - - The options are LNFN (last name, first name), FNLN (first name, last + Return the selected sorting method for the name. + + The options are LNFN (last name, first name), FNLN (first name, last name), etc. """ - return self.sort_as + return self.sort_as def set_display_as(self, value): """ - Specifies the display format for the specified name. - - Typically the locale's default should be used. However, there may be - names where a specific display format is desired for a name. + Specifies the display format for the specified name. + + Typically the locale's default should be used. However, there may be + names where a specific display format is desired for a name. """ self.display_as = value def get_display_as(self): """ - Return the selected display format for the name. - - The options are LNFN (last name, first name), FNLN (first name, last + Return the selected display format for the name. + + The options are LNFN (last name, first name), FNLN (first name, last name), etc. """ return self.display_as def get_call_name(self): """ - Return the call name. - - The call name's exact definition is not predetermined, and may be + Return the call name. + + The call name's exact definition is not predetermined, and may be locale specific. """ return self.call def set_call_name(self, val): """ - Set the call name. - - The call name's exact definition is not predetermined, and may be + Set the call name. + + The call name's exact definition is not predetermined, and may be locale specific. """ self.call = val def get_nick_name(self): """ - Return the nick name. - + Return the nick name. + The nick name of the person, a not official name the person is known with. """ @@ -398,8 +398,8 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, def set_nick_name(self, val): """ - Set the nick name. - + Set the nick name. + The nick name of the person, a not official name the person is known with. """ @@ -407,8 +407,8 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, def get_family_nick_name(self): """ - Return the family nick name. - + Return the family nick name. + The family nick name of the family of the person, a not official name use to denote the entire family. """ @@ -416,13 +416,13 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, def set_family_nick_name(self, val): """ - Set the family nick name. - + Set the family nick name. + The family nick name of the family of the person, a not official name use to denote the entire family. """ self.famnick = val - + def set_type(self, the_type): """Set the type of the Name instance.""" self.type.set(the_type) @@ -457,7 +457,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, def get_name(self): """ - Return a name string built from the components of the Name instance, + Return a name string built from the components of the Name instance, in the form of: surname, Firstname. """ first = self.first_name @@ -472,7 +472,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, def get_upper_name(self): """ - Return a name string built from the components of the Name instance, + Return a name string built from the components of the Name instance, in the form of SURNAME, Firstname. """ first = self.first_name @@ -487,7 +487,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, def get_regular_name(self): """ - Return a name string built from the components of the Name instance, + Return a name string built from the components of the Name instance, in the form of Firstname surname. """ first = self.first_name @@ -503,7 +503,7 @@ class Name(SecondaryObject, PrivacyBase, SurnameBase, CitationBase, NoteBase, """ Returns a GEDCOM-formatted name dictionary. - .. note:: Fields patronymic and prefix are deprecated, prefix_list and + .. note:: Fields patronymic and prefix are deprecated, prefix_list and surname list, added. """ retval = {} diff --git a/gramps/gen/lib/nameorigintype.py b/gramps/gen/lib/nameorigintype.py index 1298949a1..969ca6a3a 100644 --- a/gramps/gen/lib/nameorigintype.py +++ b/gramps/gen/lib/nameorigintype.py @@ -40,7 +40,7 @@ from .grampstype import GrampsType class NameOriginType(GrampsType): """ Name Origin Types - + .. attribute UNKNOWN: Unknown origin .. attribute CUSTOM: Custom user defined origin .. attribute NONE: no given origin diff --git a/gramps/gen/lib/note.py b/gramps/gen/lib/note.py index c4cb3b97a..89e7e0dd9 100644 --- a/gramps/gen/lib/note.py +++ b/gramps/gen/lib/note.py @@ -43,20 +43,20 @@ from .handle import Handle #------------------------------------------------------------------------- class Note(BasicPrimaryObject): """Define a text note. - + Starting from Gramps 3.1 Note object stores the text in :class:`~.styledtext.StyledText` instance, thus it can have text formatting information. To get and set only the clear text of the note use the :meth:`get` and :meth:`set` methods. - + To get and set the formatted version of the Note's text use the :meth:`get_styledtext` and :meth:`set_styledtext` methods. - + The note may be 'preformatted' or 'flowed', which indicates that the text string is considered to be in paragraphs, separated by newlines. - + :cvar FLOWED: indicates flowed format :cvar FORMATTED: indicates formatted format (respecting whitespace needed) :cvar POS_: (int) Position of attribute in the serialized format of @@ -67,7 +67,7 @@ class Note(BasicPrimaryObject): :meth:`serialize` method changes! """ (FLOWED, FORMATTED) = list(range(2)) - + (POS_HANDLE, POS_ID, POS_TEXT, @@ -86,10 +86,10 @@ class Note(BasicPrimaryObject): def serialize(self): """Convert the object to a serialized tuple of data. - + :returns: The serialized format of the instance. :rtype: tuple - + """ return (self.handle, self.gramps_id, self.text.serialize(), self.format, self.type.serialize(), self.change, TagBase.serialize(self), @@ -99,7 +99,7 @@ class Note(BasicPrimaryObject): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -116,12 +116,12 @@ class Note(BasicPrimaryObject): :rtype: dict """ return {"_class": "Note", - "handle": Handle("Note", self.handle), - "gramps_id": self.gramps_id, - "text": self.text.to_struct(), + "handle": Handle("Note", self.handle), + "gramps_id": self.gramps_id, + "text": self.text.to_struct(), "format": self.format, - "type": self.type.to_struct(), - "change": self.change, + "type": self.type.to_struct(), + "change": self.change, "tag_list": TagBase.to_struct(self), "private": self.private} @@ -137,14 +137,14 @@ class Note(BasicPrimaryObject): struct.get("gramps_id", default.gramps_id), StyledText.from_struct(struct.get("text", {})), struct.get("format", default.format), - NoteType.from_struct(struct.get("type", {})), + NoteType.from_struct(struct.get("type", {})), struct.get("change", default.change), TagBase.from_struct(struct.get("tag_list", default.tag_list)), struct.get("private", default.private)) def unserialize(self, data): """Convert a serialized tuple of data to an object. - + :param data: The serialized format of a Note. :type: data: tuple """ @@ -170,12 +170,12 @@ class Note(BasicPrimaryObject): """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ return self.get_referenced_tag_handles() - + def merge(self, acquisition): """ Merge the content of acquisition into this note. @@ -211,7 +211,7 @@ class Note(BasicPrimaryObject): :type text: :class:`~.styledtext.StyledText` """ self.text = text - + def get_styledtext(self): """Return the text string associated with the note. @@ -219,7 +219,7 @@ class Note(BasicPrimaryObject): :rtype: :class:`~.styledtext.StyledText` """ return self.text - + def append(self, text): """Append the specified text to the text associated with the note. @@ -229,16 +229,16 @@ class Note(BasicPrimaryObject): self.text = self.text + text def set_format(self, format): - """Set the format of the note to the passed value. - + """Set the format of the note to the passed value. + :param format: The value can either indicate Flowed or Preformatted. :type format: int """ self.format = format def get_format(self): - """Return the format of the note. - + """Return the format of the note. + The value can either indicate Flowed or Preformatted. :returns: 0 indicates Flowed, 1 indicates Preformated @@ -248,7 +248,7 @@ class Note(BasicPrimaryObject): def set_type(self, the_type): """Set descriptive type of the Note. - + :param the_type: descriptive type of the Note :type the_type: str """ @@ -256,7 +256,7 @@ class Note(BasicPrimaryObject): def get_type(self): """Get descriptive type of the Note. - + :returns: the descriptive type of the Note :rtype: str """ diff --git a/gramps/gen/lib/notebase.py b/gramps/gen/lib/notebase.py index c6e4bd6d3..9fa5b1bcc 100644 --- a/gramps/gen/lib/notebase.py +++ b/gramps/gen/lib/notebase.py @@ -41,7 +41,7 @@ class NoteBase(object): def __init__(self, source=None): """ Create a new NoteBase, copying from source if not None. - + :param source: Object used to initialize the new object :type source: NoteBase """ @@ -57,7 +57,7 @@ class NoteBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -83,7 +83,7 @@ class NoteBase(object): :returns: Returns a serialized object """ return [Handle.from_struct(n) for n in struct] - + def unserialize(self, data): """ Convert a serialized tuple of data to an object. @@ -119,16 +119,16 @@ class NoteBase(object): self.note_list.remove(handle) for item in self.get_note_child_list(): item.remove_note(handle) - + def get_note_child_list(self): """ Return the list of child secondary objects that may refer notes. - + All methods which inherit from NoteBase and have other child objects - with notes, should return here a list of child objects which are + with notes, should return here a list of child objects which are NoteBase - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -146,7 +146,7 @@ class NoteBase(object): def has_note_reference(self, note_handle): """ - Return True if the object or any of its child objects has reference + Return True if the object or any of its child objects has reference to this note handle. :param note_handle: The note handle to be checked. @@ -190,10 +190,10 @@ class NoteBase(object): def get_referenced_note_handles(self): """ Return the list of (classname, handle) tuples for all referenced notes. - + This method should be used to get the :class:`~.note.Note` portion of the list by objects that store note lists. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ diff --git a/gramps/gen/lib/notetype.py b/gramps/gen/lib/notetype.py index 2b8463e03..e8b391e12 100644 --- a/gramps/gen/lib/notetype.py +++ b/gramps/gen/lib/notetype.py @@ -72,7 +72,7 @@ class NoteType(GrampsType): _CUSTOM = CUSTOM _DEFAULT = GENERAL - + _DATAMAPREAL = [ (UNKNOWN, _("Unknown"), "Unknown"), @@ -86,7 +86,7 @@ class NoteType(GrampsType): (HTML_CODE, _("Html code"), "Html code"), (TODO, _("notetype|To Do"), "To Do"), ] - + _DATAMAPIGNORE = [ (PERSON, _("Person Note"),"Person Note"), (PERSONNAME, _("Name Note"), "Name Note"), @@ -101,36 +101,36 @@ class NoteType(GrampsType): (SOURCEREF, _("Source Reference Note"), "Source Reference Note"), (PLACE, _("Place Note"), "Place Note"), (REPO, _("Repository Note"), "Repository Note"), - (REPOREF, _("Repository Reference Note"), + (REPOREF, _("Repository Reference Note"), "Repository Reference Note"), (MEDIA, _("Media Note"), "Media Note"), (MEDIAREF, _("Media Reference Note"), "Media Reference Note"), (CHILDREF, _("Child Reference Note"), "Child Reference Note"), ] - + _DATAMAP = _DATAMAPREAL + _DATAMAPIGNORE def __init__(self, value=None): GrampsType.__init__(self, value) - + def get_ignore_list(self, exception): """ Return a list of the types to ignore and not include in default lists. - + Exception is a sublist of types that may not be ignored - + :param exception: list of integer values corresponding with types that have to be excluded from the ignore list :type exception: list - :returns: list of integers corresponding with the types to ignore when + :returns: list of integers corresponding with the types to ignore when showing a list of different types :rtype: list - + """ ignlist = [x[0] for x in self._DATAMAPIGNORE] if exception: for type_ in exception: - try: + try: del ignlist[ignlist.index(type_)] except ValueError: pass diff --git a/gramps/gen/lib/person.py b/gramps/gen/lib/person.py index af4d500f1..787659f08 100644 --- a/gramps/gen/lib/person.py +++ b/gramps/gen/lib/person.py @@ -11,7 +11,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -61,28 +61,28 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, The Person record is the Gramps in-memory representation of an individual person. It contains all the information related to an individual. - + Person objects are usually created in one of two ways. - 1. Creating a new person object, which is then initialized and added to + 1. Creating a new person object, which is then initialized and added to the database. 2. Retrieving an object from the database using the records handle. Once a Person object has been modified, it must be committed - to the database using the database object's commit_person function, + to the database using the database object's commit_person function, or the changes will be lost. """ - + UNKNOWN = 2 MALE = 1 FEMALE = 0 - + def __init__(self, data=None): """ - Create a new Person instance. - - After initialization, most data items have empty or null values, + Create a new Person instance. + + After initialization, most data items have empty or null values, including the database handle. """ PrimaryObject.__init__(self) @@ -104,7 +104,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, self.birth_ref_index = -1 if data: self.unserialize(data) - + # We hold a reference to the GrampsDB so that we can maintain # its genderStats. It doesn't get set here, but from # GenderStats.count_person. @@ -114,16 +114,16 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def __ne__(self, other): return not self == other - + def serialize(self): """ Convert the data held in the Person to a Python tuple that - represents all the data elements. - - This method is used to convert the object into a form that can easily + represents all the data elements. + + This method is used to convert the object into a form that can easily be saved to a database. - These elements may be primitive Python types (string, integers), + These elements may be primitive Python types (string, integers), complex Python types (lists or tuples, or Python objects. If the target database cannot handle complex types (such as objects or lists), the database is responsible for converting the data into @@ -161,7 +161,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -183,15 +183,15 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, "gramps_id": self.gramps_id, # 1 "gender": self.gender, # 2 "primary_name": self.primary_name.to_struct(), # 3 - "alternate_names": [name.to_struct() + "alternate_names": [name.to_struct() for name in self.alternate_names], # 4 "death_ref_index": self.death_ref_index, # 5 "birth_ref_index": self.birth_ref_index, # 6 - "event_ref_list": [er.to_struct() + "event_ref_list": [er.to_struct() for er in self.event_ref_list], # 7 - "family_list": [Handle("Family", f) for f in + "family_list": [Handle("Family", f) for f in self.family_list], # 8 - "parent_family_list": [Handle("Family", f) for f in + "parent_family_list": [Handle("Family", f) for f in self.parent_family_list], # 9 "media_list": MediaBase.to_struct(self), # 10 "address_list": AddressBase.to_struct(self), # 11 @@ -203,7 +203,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, "change": self.change, # 17 "tag_list": TagBase.to_struct(self), # 18 "private": self.private, # 19 - "person_ref_list": [pr.to_struct() + "person_ref_list": [pr.to_struct() for pr in self.person_ref_list] # 20 } @@ -258,7 +258,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, "urls": [Url], "lds_ord_list": [LdsOrd], "citation_list": [Handle("Citation", "CITATION-HANDLE")], - "note_list": [Handle("Note", "NOTE-HANDLE")], + "note_list": [Handle("Note", "NOTE-HANDLE")], "change": int, "tag_list": [Handle("Tag", "TAG-HANDLE")], "private": bool, @@ -314,17 +314,17 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, NoteBase.unserialize(self, note_list) TagBase.unserialize(self, tag_list) return self - + def _has_handle_reference(self, classname, handle): """ - Return True if the object has reference to a given handle of given + Return True if the object has reference to a given handle of given primary object type. - + :param classname: The name of the primary object class. :type classname: str :param handle: The handle to be checked. :type handle: str - :returns: Returns whether the object has reference to this handle of + :returns: Returns whether the object has reference to this handle of this object type. :rtype: bool """ @@ -333,11 +333,11 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, elif classname == 'Person': return any(ref.ref == handle for ref in self.person_ref_list) elif classname == 'Family': - return any(ref == handle + return any(ref == handle for ref in self.family_list + self.parent_family_list + [ordinance.famc for ordinance in self.lds_ord_list]) elif classname == 'Place': - return any(ordinance.place == handle + return any(ordinance.place == handle for ordinance in self.lds_ord_list) return False @@ -480,13 +480,13 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, self.event_ref_list + add_list + self.person_ref_list - ) + ) def get_citation_child_list(self): """ Return the list of child secondary objects that may refer citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer citations. :rtype: list """ @@ -504,7 +504,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -522,13 +522,13 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ return [('Family', handle) for handle in (self.family_list + self.parent_family_list)] + ( - self.get_referenced_note_handles() + + self.get_referenced_note_handles() + self.get_referenced_citation_handles() + self.get_referenced_tag_handles() ) @@ -537,7 +537,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -615,7 +615,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def set_alternate_names(self, alt_name_list): """ Change the list of alternate names to the passed list. - + :param alt_name_list: List of :class:`~.name.Name` instances :type alt_name_list: list """ @@ -682,7 +682,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, Return the gender of the Person. :returns: Returns one of the following constants: - + - Person.MALE - Person.FEMALE - Person.UNKNOWN @@ -692,8 +692,8 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def set_birth_ref(self, event_ref): """ - Assign the birth event to the Person object. - + Assign the birth event to the Person object. + This is accomplished by assigning the :class:`~.eventref.EventRef` of the birth event in the current database. @@ -717,8 +717,8 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def set_death_ref(self, event_ref): """ - Assign the death event to the Person object. - + Assign the death event to the Person object. + This is accomplished by assigning the :class:`~.eventref.EventRef` of the death event in the current database. @@ -731,7 +731,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, if event_ref is None: self.death_ref_index = -1 return - + # check whether we already have this ref in the list for self.death_ref_index, ref in enumerate(self.event_ref_list): if event_ref.is_equal(ref): @@ -742,8 +742,8 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def get_birth_ref(self): """ - Return the :class:`~.eventref.EventRef` for Person's birth event. - + Return the :class:`~.eventref.EventRef` for Person's birth event. + This should correspond to an :class:`~.event.Event` in the database's :class:`~.event.Event` list. @@ -751,7 +751,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, birth :class:`~.event.Event` has been assigned. :rtype: EventRef """ - + if 0 <= self.birth_ref_index < len(self.event_ref_list): return self.event_ref_list[self.birth_ref_index] else: @@ -759,8 +759,8 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def get_death_ref(self): """ - Return the :class:`~.eventref.EventRef` for the Person's death event. - + Return the :class:`~.eventref.EventRef` for the Person's death event. + This should correspond to an :class:`~.event.Event` in the database's :class:`~.event.Event` list. @@ -768,7 +768,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, death :class:`~.event.Event` has been assigned. :rtype: event_ref """ - + if 0 <= self.death_ref_index < len(self.event_ref_list): return self.event_ref_list[self.death_ref_index] else: @@ -778,10 +778,10 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, """ Add the :class:`~.eventref.EventRef` to the Person instance's :class:`~.eventref.EventRef` list. - + This is accomplished by assigning the :class:`~.eventref.EventRef` of a valid :class:`~.event.Event` in the current database. - + :param event_ref: the :class:`~.eventref.EventRef` to be added to the Person's :class:`~.eventref.EventRef` list. :type event_ref: EventRef @@ -798,7 +798,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, Return the list of :class:`~.eventref.EventRef` objects associated with :class:`~.event.Event` instances. - :returns: Returns the list of :class:`~.eventref.EventRef` objects + :returns: Returns the list of :class:`~.eventref.EventRef` objects associated with the Person instance. :rtype: list """ @@ -810,7 +810,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, :class:`~.event.Event` instances that have been marked as primary events. - :returns: Returns generator of :class:`~.eventref.EventRef` objects + :returns: Returns generator of :class:`~.eventref.EventRef` objects associated with the Person instance. :rtype: generator """ @@ -848,7 +848,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, break else: self.event_ref_list.append(addendum) - if (self.birth_ref_index == -1 and + if (self.birth_ref_index == -1 and idx == acquisition.birth_ref_index): self.birth_ref_index = len(self.event_ref_list) - 1 if (self.death_ref_index == -1 and @@ -859,7 +859,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, """ Add the :class:`~.family.Family` handle to the Person instance's :class:`~.family.Family` list. - + This is accomplished by assigning the handle of a valid :class:`~.family.Family` in the current database. @@ -868,7 +868,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, developer is responsible to make sure that when a :class:`~.family.Family` is added to Person, that the Person is assigned to either the father or mother role in the :class:`~.family.Family`. - + :param family_handle: handle of the :class:`~.family.Family` to be added to the Person's :class:`~.family.Family` list. :type family_handle: str @@ -880,12 +880,12 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, """ Set the family_handle specified to be the preferred :class:`~.family.Family`. - + The preferred :class:`~.family.Family` is determined by the first :class:`~.family.Family` in the :class:`~.family.Family` list, and is typically used to indicate the preferred :class:`~.family.Family` for navigation or reporting. - + The family_handle must already be in the list, or the function call has no effect. @@ -909,7 +909,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, is a parent or spouse. :returns: Returns the list of handles corresponding to the - :class:`~.family.Family` records with which the person + :class:`~.family.Family` records with which the person is associated. :rtype: list """ @@ -917,12 +917,12 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def set_family_handle_list(self, family_list) : """ - Assign the passed list to the Person's list of families in which it is + Assign the passed list to the Person's list of families in which it is a parent or spouse. :param family_list: List of :class:`~.family.Family` handles to be associated with the Person - :type family_list: list + :type family_list: list """ self.family_list = family_list @@ -935,9 +935,9 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def remove_family_handle(self, family_handle): """ - Remove the specified :class:`~.family.Family` handle from the list of - marriages/partnerships. - + Remove the specified :class:`~.family.Family` handle from the list of + marriages/partnerships. + If the handle does not exist in the list, the operation has no effect. :param family_handle: :class:`~.family.Family` handle to remove from @@ -981,8 +981,8 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def add_parent_family_handle(self, family_handle): """ Add the :class:`~.family.Family` handle to the Person instance's list of - families in which it is a child. - + families in which it is a child. + This is accomplished by assigning the handle of a valid :class:`~.family.Family` in the current database. @@ -991,7 +991,7 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, developer is responsible to make sure that when a :class:`~.family.Family` is added to Person, that the Person is added to the :class:`~.family.Family` instance's child list. - + :param family_handle: handle of the :class:`~.family.Family` to be added to the Person's :class:`~.family.Family` list. :type family_handle: str @@ -1011,8 +1011,8 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def remove_parent_family_handle(self, family_handle): """ Remove the specified :class:`~.family.Family` handle from the list of - parent families (families in which the parent is a child). - + parent families (families in which the parent is a child). + If the handle does not exist in the list, the operation has no effect. :param family_handle: :class:`~.family.Family` handle to remove from the @@ -1033,8 +1033,8 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def set_main_parent_family_handle(self, family_handle): """ - Set the main :class:`~.family.Family` in which the Person is a child. - + Set the main :class:`~.family.Family` in which the Person is a child. + The main :class:`~.family.Family` is the :class:`~.family.Family` typically used for reports and navigation. This is accomplished by moving the :class:`~.family.Family` to the beginning of the list. The @@ -1052,13 +1052,13 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, return True else: return False - + def get_main_parents_family_handle(self): """ Return the handle of the :class:`~.family.Family` considered to be the main :class:`~.family.Family` in which the Person is a child. - :returns: Returns the family_handle if a family_handle exists, + :returns: Returns the family_handle if a family_handle exists, If no :class:`~.family.Family` is assigned, None is returned :rtype: str """ @@ -1069,9 +1069,9 @@ class Person(CitationBase, NoteBase, AttributeBase, MediaBase, def add_person_ref(self, person_ref): """ - Add the :class:`~.personref.PersonRef` to the Person instance's + Add the :class:`~.personref.PersonRef` to the Person instance's :class:`~.personref.PersonRef` list. - + :param person_ref: the :class:`~.personref.PersonRef` to be added to the Person's :class:`~.personref.PersonRef` list. :type person_ref: PersonRef diff --git a/gramps/gen/lib/personref.py b/gramps/gen/lib/personref.py index b0ade93b9..7f9fdc839 100644 --- a/gramps/gen/lib/personref.py +++ b/gramps/gen/lib/personref.py @@ -76,7 +76,7 @@ class PersonRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -146,7 +146,7 @@ class PersonRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase): """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -156,7 +156,7 @@ class PersonRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase): """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -170,7 +170,7 @@ class PersonRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase): """ Return the list of child objects which may, directly or through their children, reference primary objects.. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -178,7 +178,7 @@ class PersonRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase): def is_equivalent(self, other): """ - Return if this person reference is equivalent, that is agrees in handle + Return if this person reference is equivalent, that is agrees in handle and relation, to other. :param other: The personref to compare this one to. diff --git a/gramps/gen/lib/place.py b/gramps/gen/lib/place.py index 14d81d697..5f609e8bc 100644 --- a/gramps/gen/lib/place.py +++ b/gramps/gen/lib/place.py @@ -53,7 +53,7 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): information (since place names can change with time), longitude, latitude, a collection of images and URLs, a note and a source. """ - + def __init__(self, source=None): """ Create a new Place object, copying from the source if present. @@ -90,9 +90,9 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): def serialize(self): """ Convert the data held in the Place to a Python tuple that - represents all the data elements. - - This method is used to convert the object into a form that can easily + represents all the data elements. + + This method is used to convert the object into a form that can easily be saved to a database. These elements may be primitive Python types (string, integers), @@ -106,7 +106,7 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): :rtype: tuple """ return (self.handle, self.gramps_id, self.title, self.long, self.lat, - [pr.serialize() for pr in self.placeref_list], + [pr.serialize() for pr in self.placeref_list], self.name.serialize(), [an.serialize() for an in self.alt_names], self.place_type.serialize(), self.code, @@ -121,7 +121,7 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -138,22 +138,22 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): :rtype: dict """ return {"_class": "Place", - "handle": Handle("Place", self.handle), - "gramps_id": self.gramps_id, - "title": self.title, - "long": self.long, + "handle": Handle("Place", self.handle), + "gramps_id": self.gramps_id, + "title": self.title, + "long": self.long, "lat": self.lat, "placeref_list": [pr.to_struct() for pr in self.placeref_list], "name": self.name.to_struct(), "alt_names": [an.to_struct() for an in self.alt_names], - "place_type": self.place_type.to_struct(), - "code": self.code, + "place_type": self.place_type.to_struct(), + "code": self.code, "alt_loc": [al.to_struct() for al in self.alt_loc], "urls": UrlBase.to_struct(self), "media_list": MediaBase.to_struct(self), "citation_list": CitationBase.to_struct(self), "note_list": NoteBase.to_struct(self), - "change": self.change, + "change": self.change, "tag_list": TagBase.to_struct(self), "private": self.private} @@ -173,14 +173,14 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): [PlaceRef.from_struct(pr) for pr in struct.get("placeref_list", default.placeref_list)], PlaceName.from_struct(struct.get("name", {})), [PlaceName.from_struct(an) for an in struct.get("alt_names", default.alt_names)], - PlaceType.from_struct(struct.get("place_type", {})), + PlaceType.from_struct(struct.get("place_type", {})), struct.get("code", default.code), [Location.from_struct(al) for al in struct.get("alt_loc", default.alt_loc)], UrlBase.from_struct(struct.get("urls", default.urls)), MediaBase.from_struct(struct.get("media_list", default.media_list)), CitationBase.from_struct(struct.get("citation_list", default.citation_list)), NoteBase.from_struct(struct.get("note_list", default.note_list)), - struct.get("change", default.change), + struct.get("change", default.change), TagBase.from_struct(struct.get("tag_list", default.tag_list)), struct.get("private", default.private)) @@ -245,7 +245,7 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -255,7 +255,7 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -265,7 +265,7 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -454,14 +454,14 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): def _has_handle_reference(self, classname, handle): """ - Return True if the object has reference to a given handle of given + Return True if the object has reference to a given handle of given primary object type. - + :param classname: The name of the primary object class. :type classname: str :param handle: The handle to be checked. :type handle: str - :returns: Returns whether the object has reference to this handle of + :returns: Returns whether the object has reference to this handle of this object type. :rtype: bool """ @@ -519,8 +519,8 @@ class Place(CitationBase, NoteBase, MediaBase, UrlBase, PrimaryObject): def get_alternate_locations(self): """ Return a list of alternate :class:`~.location.Location` objects the - present alternate information about the current Place. - + present alternate information about the current Place. + A Place can have more than one :class:`~.location.Location`, since names and jurisdictions can change over time for the same place. diff --git a/gramps/gen/lib/placebase.py b/gramps/gen/lib/placebase.py index 32cedb680..b84bd4a16 100644 --- a/gramps/gen/lib/placebase.py +++ b/gramps/gen/lib/placebase.py @@ -33,9 +33,9 @@ class PlaceBase(object): """ def __init__(self, source=None): """ - Initialize a PlaceBase. - - If the source is not None, then object is initialized from values of + Initialize a PlaceBase. + + If the source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object @@ -64,4 +64,4 @@ class PlaceBase(object): :returns: :class:`~.place.Place` database handle :rtype: str """ - return self.place + return self.place diff --git a/gramps/gen/lib/placeref.py b/gramps/gen/lib/placeref.py index 94bba0fe4..690c326b4 100644 --- a/gramps/gen/lib/placeref.py +++ b/gramps/gen/lib/placeref.py @@ -67,7 +67,7 @@ class PlaceRef(RefBase, DateBase, SecondaryObject): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -133,7 +133,7 @@ class PlaceRef(RefBase, DateBase, SecondaryObject): """ Return the list of child secondary objects that may refer citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer citations. :rtype: list """ @@ -143,7 +143,7 @@ class PlaceRef(RefBase, DateBase, SecondaryObject): """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -153,8 +153,8 @@ class PlaceRef(RefBase, DateBase, SecondaryObject): """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - - :returns: Returns the list of (classname, handle) tuples for referenced + + :returns: Returns the list of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -162,9 +162,9 @@ class PlaceRef(RefBase, DateBase, SecondaryObject): def get_handle_referents(self): """ - Return the list of child objects which may, directly or through their + Return the list of child objects which may, directly or through their children, reference primary objects.. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ diff --git a/gramps/gen/lib/primaryobj.py b/gramps/gen/lib/primaryobj.py index 388296651..86235b506 100644 --- a/gramps/gen/lib/primaryobj.py +++ b/gramps/gen/lib/primaryobj.py @@ -42,22 +42,22 @@ from .tagbase import TagBase class BasicPrimaryObject(TableObject, PrivacyBase, TagBase): """ The BasicPrimaryObject is the base class for :class:`~.note.Note` objects. - - It is also the base class for the :class:`PrimaryObject` class. - + + It is also the base class for the :class:`PrimaryObject` class. + The :class:`PrimaryObject` is the base class for all other primary objects in the database. Primary objects are the core objects in the database. Each object has a database handle and a Gramps ID value. The database handle is used as the record number for the database, and the Gramps ID is the user visible version. """ - + def __init__(self, source=None): """ - Initialize a PrimaryObject. - - If source is None, both the ID and handle are assigned as empty - strings. If source is not None, then object is initialized from values + Initialize a PrimaryObject. + + If source is None, both the ID and handle are assigned as empty + strings. If source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object @@ -74,7 +74,7 @@ class BasicPrimaryObject(TableObject, PrivacyBase, TagBase): def set_gramps_id(self, gramps_id): """ Set the Gramps ID for the primary object. - + :param gramps_id: Gramps ID :type gramps_id: str """ @@ -91,16 +91,16 @@ class BasicPrimaryObject(TableObject, PrivacyBase, TagBase): def has_handle_reference(self, classname, handle): """ - Return True if the object has reference to a given handle of given + Return True if the object has reference to a given handle of given primary object type. - + :param classname: The name of the primary object class. :type classname: str :param handle: The handle to be checked. :type handle: str - :returns: - Returns whether the object has reference to this handle of + :returns: + Returns whether the object has reference to this handle of this object type. :rtype: bool @@ -133,27 +133,27 @@ class BasicPrimaryObject(TableObject, PrivacyBase, TagBase): def has_media_reference(self, handle): """ - Indicate if the object has a media references. - - In the base class, no such references exist. Derived classes should + Indicate if the object has a media references. + + In the base class, no such references exist. Derived classes should override this if they provide media references. """ return False def remove_citation_references(self, handle_list): """ - Remove the specified source references from the object. - - In the base class no such references exist. Derived classes should + Remove the specified source references from the object. + + In the base class no such references exist. Derived classes should override this if they provide source references. """ pass def remove_media_references(self, handle_list): """ - Remove the specified media references from the object. - - In the base class no such references exist. Derived classes should + Remove the specified media references from the object. + + In the base class no such references exist. Derived classes should override this if they provide media references. """ pass @@ -172,20 +172,20 @@ class BasicPrimaryObject(TableObject, PrivacyBase, TagBase): class PrimaryObject(BasicPrimaryObject): """ The PrimaryObject is the base class for all primary objects in the - database. - + database. + Primary objects are the core objects in the database. Each object has a database handle and a Gramps ID value. The database handle is used as the record number for the database, and the Gramps ID is the user visible version. """ - + def __init__(self, source=None): """ - Initialize a PrimaryObject. - - If source is None, both the ID and handle are assigned as empty - strings. If source is not None, then object is initialized from values + Initialize a PrimaryObject. + + If source is None, both the ID and handle are assigned as empty + strings. If source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object @@ -195,14 +195,14 @@ class PrimaryObject(BasicPrimaryObject): def has_handle_reference(self, classname, handle): """ - Return True if the object has reference to a given handle of given + Return True if the object has reference to a given handle of given primary object type. - + :param classname: The name of the primary object class. :type classname: str :param handle: The handle to be checked. :type handle: str - :returns: Returns whether the object has reference to this handle + :returns: Returns whether the object has reference to this handle of this object type. :rtype: bool """ diff --git a/gramps/gen/lib/privacybase.py b/gramps/gen/lib/privacybase.py index e0a7a07f8..12b2819c2 100644 --- a/gramps/gen/lib/privacybase.py +++ b/gramps/gen/lib/privacybase.py @@ -35,15 +35,15 @@ class PrivacyBase(object): def __init__(self, source=None): """ - Initialize a PrivacyBase. - - If the source is not None, then object is initialized from values of + Initialize a PrivacyBase. + + If the source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object :type source: PrivacyBase """ - + if source: self.private = source.private else: @@ -59,7 +59,7 @@ class PrivacyBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -97,7 +97,7 @@ class PrivacyBase(object): """ Set or clears the privacy flag of the data. - :param val: value to assign to the privacy flag. True indicates that + :param val: value to assign to the privacy flag. True indicates that the record is private, False indicates that it is public. :type val: bool """ @@ -105,7 +105,7 @@ class PrivacyBase(object): def get_privacy(self): """ - Return the privacy level of the data. + Return the privacy level of the data. :returns: True indicates that the record is private :rtype: bool diff --git a/gramps/gen/lib/refbase.py b/gramps/gen/lib/refbase.py index f13701b9c..899c3232b 100644 --- a/gramps/gen/lib/refbase.py +++ b/gramps/gen/lib/refbase.py @@ -66,8 +66,8 @@ class RefBase(object): """ Returns the list of (classname, handle) tuples for all directly referenced primary objects. - - :returns: Returns the list of (classname, handle) tuples for referenced + + :returns: Returns the list of (classname, handle) tuples for referenced objects. :rtype: list """ diff --git a/gramps/gen/lib/repo.py b/gramps/gen/lib/repo.py index cb5ed8ee7..13f52601b 100644 --- a/gramps/gen/lib/repo.py +++ b/gramps/gen/lib/repo.py @@ -46,7 +46,7 @@ from .citationbase import IndirectCitationBase class Repository(NoteBase, AddressBase, UrlBase, IndirectCitationBase, PrimaryObject): """A location where collections of Sources are found.""" - + def __init__(self): """ Create a new Repository instance. @@ -73,7 +73,7 @@ class Repository(NoteBase, AddressBase, UrlBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -90,14 +90,14 @@ class Repository(NoteBase, AddressBase, UrlBase, :rtype: dict """ return {"_class": "Repository", - "handle": Handle("Repository", self.handle), - "gramps_id": self.gramps_id, + "handle": Handle("Repository", self.handle), + "gramps_id": self.gramps_id, "type": self.type.to_struct(), "name": str(self.name), "note_list": NoteBase.to_struct(self), "address_list": AddressBase.to_struct(self), "urls": UrlBase.to_struct(self), - "change": self.change, + "change": self.change, "tag_list": TagBase.to_struct(self), "private": self.private} @@ -135,7 +135,7 @@ class Repository(NoteBase, AddressBase, UrlBase, UrlBase.unserialize(self, urls) TagBase.unserialize(self, tag_list) return self - + def get_text_data_list(self): """ Return the list of all textual attributes of the object. @@ -158,7 +158,7 @@ class Repository(NoteBase, AddressBase, UrlBase, """ Return the list of child secondary objects that may refer citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer citations. :rtype: list """ @@ -168,7 +168,7 @@ class Repository(NoteBase, AddressBase, UrlBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -178,7 +178,7 @@ class Repository(NoteBase, AddressBase, UrlBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -188,7 +188,7 @@ class Repository(NoteBase, AddressBase, UrlBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ diff --git a/gramps/gen/lib/reporef.py b/gramps/gen/lib/reporef.py index d9a08b9c3..65317a58c 100644 --- a/gramps/gen/lib/reporef.py +++ b/gramps/gen/lib/reporef.py @@ -73,7 +73,7 @@ class RepoRef(SecondaryObject, PrivacyBase, NoteBase, RefBase): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -93,7 +93,7 @@ class RepoRef(SecondaryObject, PrivacyBase, NoteBase, RefBase): "_class": "RepositoryRef", "note_list": NoteBase.to_struct(self), "ref": Handle("Repository", self.ref), - "call_number": self.call_number, + "call_number": self.call_number, "media_type": self.media_type.to_struct(), "private": PrivacyBase.serialize(self), } @@ -139,7 +139,7 @@ class RepoRef(SecondaryObject, PrivacyBase, NoteBase, RefBase): """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ diff --git a/gramps/gen/lib/researcher.py b/gramps/gen/lib/researcher.py index 94fdb4380..8baed2bb1 100644 --- a/gramps/gen/lib/researcher.py +++ b/gramps/gen/lib/researcher.py @@ -32,12 +32,12 @@ from .locationbase import LocationBase #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class Researcher(LocationBase): """Contains the information about the owner of the database.""" - + def __init__(self, source=None): """ Initialize the Researcher object, copying from the source if provided. @@ -64,7 +64,7 @@ class Researcher(LocationBase): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -81,16 +81,16 @@ class Researcher(LocationBase): :rtype: dict """ return {"_class": "Researcher", - "street": self.street, - "locality": self.locality, - "city": self.city, - "county": self.county, + "street": self.street, + "locality": self.locality, + "city": self.city, + "county": self.county, "state": self.state, - "country": self.country, - "postal": self.postal, + "country": self.country, + "postal": self.postal, "phone": self.phone, - "name": self.name, - "address": self.addr, + "name": self.name, + "address": self.addr, "email": self.email} @classmethod @@ -112,20 +112,20 @@ class Researcher(LocationBase): struct.get("name", default.name), struct.get("address", default.address), struct.get("email", default.email)) - + def unserialize(self, data): """ Convert a serialized tuple of data to an object. """ (location, self.name, self.addr, self.email) = data LocationBase.unserialize(self, location) - + return self def set_name(self, data): """Set the database owner's name.""" self.name = data - + def get_name(self): """Return the database owner's name.""" return self.name @@ -133,7 +133,7 @@ class Researcher(LocationBase): def set_address(self, data): """Set the database owner's address.""" self.addr = data - + def get_address(self): """Return the database owner's address.""" return self.addr @@ -141,7 +141,7 @@ class Researcher(LocationBase): def set_email(self, data): """ Set the database owner's email.""" self.email = data - + def get_email(self): """Return the database owner's email.""" return self.email @@ -160,10 +160,10 @@ class Researcher(LocationBase): self.name = other_researcher.name self.addr = other_researcher.addr self.email = other_researcher.email - + def get(self): return [getattr(self, value) for value in - ['name', 'addr', 'locality', 'city', 'state', + ['name', 'addr', 'locality', 'city', 'state', 'country', 'postal', 'phone', 'email'] ] diff --git a/gramps/gen/lib/secondaryobj.py b/gramps/gen/lib/secondaryobj.py index 0c6a345e0..821bb8702 100644 --- a/gramps/gen/lib/secondaryobj.py +++ b/gramps/gen/lib/secondaryobj.py @@ -37,9 +37,9 @@ from .baseobj import BaseObject class SecondaryObject(BaseObject): """ The SecondaryObject is the base class for all secondary objects in the - database. + database. """ - + def is_equal(self, source): return self.serialize() == source.serialize() diff --git a/gramps/gen/lib/src.py b/gramps/gen/lib/src.py index 1ae4a8934..6f69cc247 100644 --- a/gramps/gen/lib/src.py +++ b/gramps/gen/lib/src.py @@ -48,7 +48,7 @@ from .citationbase import IndirectCitationBase class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, PrimaryObject): """A record of a source of information.""" - + def __init__(self): """Create a new Source instance.""" PrimaryObject.__init__(self) @@ -60,7 +60,7 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, self.pubinfo = "" self.abbrev = "" self.reporef_list = [] - + def serialize(self): """ Convert the object to a serialized tuple of data. @@ -83,7 +83,7 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -100,13 +100,13 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, :rtype: dict """ return {"_class": "Source", - "handle": Handle("Source", self.handle), - "gramps_id": self.gramps_id, + "handle": Handle("Source", self.handle), + "gramps_id": self.gramps_id, "title": str(self.title), - "author": str(self.author), + "author": str(self.author), "pubinfo": str(self.pubinfo), "note_list": NoteBase.to_struct(self), - "media_list": MediaBase.to_struct(self), + "media_list": MediaBase.to_struct(self), "abbrev": str(self.abbrev), "change": self.change, "srcattr_list": SrcAttributeBase.to_struct(self), @@ -129,7 +129,7 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, struct.get("author", default.author), struct.get("pubinfo", default.pubinfo), NoteBase.from_struct(struct.get("note_list", default.note_list)), - MediaBase.from_struct(struct.get("media_list", default.media_list)), + MediaBase.from_struct(struct.get("media_list", default.media_list)), struct.get("abbrev", default.abbrev), struct.get("change", default.change), SrcAttributeBase.from_struct(struct.get("srcattr_list", {})), @@ -163,17 +163,17 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, SrcAttributeBase.unserialize(self, srcattr_list) self.reporef_list = [RepoRef().unserialize(item) for item in reporef_list] return self - + def _has_handle_reference(self, classname, handle): """ - Return True if the object has reference to a given handle of given + Return True if the object has reference to a given handle of given primary object type. - + :param classname: The name of the primary object class. :type classname: str :param handle: The handle to be checked. :type handle: str - :returns: Returns whether the object has reference to this handle of + :returns: Returns whether the object has reference to this handle of this object type. :rtype: bool """ @@ -222,7 +222,7 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ return [self.title, self.author, self.pubinfo, self.abbrev, self.gramps_id] - + def get_text_data_child_list(self): """ Return the list of child objects that may carry textual data. @@ -236,7 +236,7 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Return the list of child secondary objects that may refer citations. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer citations. :rtype: list """ @@ -246,7 +246,7 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Return the list of child secondary objects that may refer notes. - :returns: Returns the list of child secondary child objects that may + :returns: Returns the list of child secondary child objects that may refer notes. :rtype: list """ @@ -256,7 +256,7 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Return the list of child objects which may, directly or through their children, reference primary objects. - + :returns: Returns the list of objects referencing primary objects. :rtype: list """ @@ -266,7 +266,7 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, """ Return the list of (classname, handle) tuples for all directly referenced primary objects. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ @@ -388,7 +388,7 @@ class Source(MediaBase, NoteBase, SrcAttributeBase, IndirectCitationBase, :param repo_handle: The Repository handle to be checked. :type repo_handle: str - :returns: Returns whether the Source has reference to this Repository + :returns: Returns whether the Source has reference to this Repository handle. :rtype: bool """ diff --git a/gramps/gen/lib/srcattribute.py b/gramps/gen/lib/srcattribute.py index 5e7ef0faf..2a8af131c 100644 --- a/gramps/gen/lib/srcattribute.py +++ b/gramps/gen/lib/srcattribute.py @@ -42,16 +42,16 @@ from .const import IDENTICAL, EQUAL, DIFFERENT #------------------------------------------------------------------------- class SrcAttribute(AttributeRoot): """ - Provide a simple key/value pair for describing properties. + Provide a simple key/value pair for describing properties. Used to store descriptive information. """ - + def __init__(self, source=None): """ Create a new Attribute object, copying from the source if provided. """ AttributeRoot.__init__(self, source) - + if source: self.type = SrcAttributeType(source.type) self.value = source.value diff --git a/gramps/gen/lib/srcattrtype.py b/gramps/gen/lib/srcattrtype.py index bcfc6649b..78b1f67c8 100644 --- a/gramps/gen/lib/srcattrtype.py +++ b/gramps/gen/lib/srcattrtype.py @@ -56,15 +56,15 @@ class SrcAttributeType(GrampsType): def get_ignore_list(self, exception=None): """ Return a list of the types to ignore and not include in default lists. - + Exception is a sublist of types that may not be ignored - + :param exception: list of integer values corresponding with types that have to be excluded from the ignore list :type exception: list - :returns: list of integers corresponding with the types to ignore when + :returns: list of integers corresponding with the types to ignore when showing a list of different types :rtype: list - + """ return [] diff --git a/gramps/gen/lib/styledtext.py b/gramps/gen/lib/styledtext.py index 5a90070d9..30a3c03dc 100644 --- a/gramps/gen/lib/styledtext.py +++ b/gramps/gen/lib/styledtext.py @@ -35,22 +35,22 @@ from .styledtexttag import StyledTextTag #------------------------------------------------------------------------- class StyledText(object): """Helper class to enable character based text formatting. - + :py:class:`StyledText` is a wrapper class binding the clear text string and it's formatting tags together. - + :py:class:`StyledText` provides several string methods in order to - manipulate formatted strings, such as :py:meth:`join`, :py:meth:`replace`, + manipulate formatted strings, such as :py:meth:`join`, :py:meth:`replace`, :py:meth:`split`, and also supports the '+' operation (:py:meth:`__add__`). - + To get the clear text of the :py:class:`StyledText` use the built-in :py:func:`str()` function. To get the list of formatting tags use the :py:meth:`get_tags` method. - + StyledText supports the *creation* of formatted texts too. This feature is intended to replace (or extend) the current report interface. To be continued... FIXME - + :ivar string: (str) The clear text part. :ivar tags: (list of :py:class:`.StyledTextTag`) Text tags holding formatting information for the string. @@ -61,22 +61,22 @@ class StyledText(object): of an instance. .. warning:: The POS_ class variables reflect the serialized object, - they have to be updated in case the data structure or the + they have to be updated in case the data structure or the :py:meth:`serialize` method changes! - + .. note:: 1. There is no sanity check of tags in :py:meth:`__init__`, because when a :py:class:`StyledText` is displayed it is passed to a - :py:class:`.StyledTextBuffer`, which in turn will 'eat' all invalid + :py:class:`.StyledTextBuffer`, which in turn will 'eat' all invalid tags (including out-of-range tags too). 2. After string methods the tags can become fragmented. That means the same tag may appear more than once in the tag list with different ranges. - There could be a 'merge_tags' functionality in :py:meth:`__init__`, + There could be a 'merge_tags' functionality in :py:meth:`__init__`, however :py:class:`StyledTextBuffer` will merge them automatically if the text is displayed. """ (POS_TEXT, POS_TAGS) = list(range(2)) - + def __init__(self, text="", tags=None): """Setup initial instance variable values.""" self._string = text @@ -87,18 +87,18 @@ class StyledText(object): self._tags = [] # special methods - + def __str__(self): return self._string.__str__() def __repr__(self): return self._string.__repr__() def __add__(self, other): """Implement '+' operation on the class. - + :param other: string to concatenate to self :type other: basestring or :py:class:`StyledText` :return: concatenated strings :rtype: :py:class:`StyledText` - + """ offset = len(self._string) @@ -107,7 +107,7 @@ class StyledText(object): for tag in other._tags: tag.ranges = [(start + offset, end + offset) for (start, end) in tag.ranges] - + return self.__class__("".join([self._string, other._string]), self._tags + other._tags) elif isinstance(other, str): @@ -173,40 +173,40 @@ class StyledText(object): return result # private methods - + # string methods in alphabetical order: def join(self, seq): """ Emulate :py:meth:`__builtin__.str.join` method. - + :param seq: list of strings to join :type seq: basestring or :py:class:`StyledText` :return: joined strings :rtype: :py:class:`StyledText` """ new_string = self._string.join([str(string) for string in seq]) - + offset = 0 new_tags = [] self_len = len(self._string) - + for text in seq: if isinstance(text, StyledText): for tag in text._tags: tag.ranges = [(start + offset, end + offset) for (start, end) in tag.ranges] new_tags += [tag] - + offset = offset + len(str(text)) + self_len - + return self.__class__(new_string, new_tags) - + def replace(self, old, new, count=-1): """ Emulate :py:meth:`__builtin__.str.replace` method. - + :param old: substring to be replaced :type old: basestring or :py:class:`StyledText` :param new: substring to replace by @@ -215,18 +215,18 @@ class StyledText(object): :type count: int :return: copy of the string with replaced substring(s) :rtype: :py:class:`StyledText` - + .. warning:: by the correct implementation parameter *new* should be :py:class:`StyledText` or basestring, however only :py:class:`StyledText` is currently supported. """ # quick and dirty solution: works only if new.__class__ == StyledText return new.join(self.split(old, count)) - + def split(self, sep=None, maxsplit=-1): """ Emulate :py:meth:`__builtin__.str.split` method. - + :param sep: the delimiter string :type seq: basestring or :py:class:`StyledText` :param maxsplit: if given, at most maxsplit splits are done @@ -238,17 +238,17 @@ class StyledText(object): if sep is not None: sep = str(sep) string_list = self._string.split(sep, maxsplit) - + # then split the tags too end_string = 0 styledtext_list = [] - + for string in string_list: start_string = self._string.find(string, end_string) end_string = start_string + len(string) new_tags = [] - + for tag in self._tags: new_tag = StyledTextTag(int(tag.name), tag.value) for (start_tag, end_tag) in tag.ranges: @@ -258,20 +258,20 @@ class StyledText(object): if start < end: new_tag.ranges.append((start - start_string, end - start_string)) - + if new_tag.ranges: new_tags.append(new_tag) - + styledtext_list.append(self.__class__(string, new_tags)) - + return styledtext_list # other public methods - + def serialize(self): """ Convert the object to a serialized tuple of data. - + :return: Serialized format of the instance. :rtype: tuple """ @@ -279,14 +279,14 @@ class StyledText(object): the_tags = [tag.serialize() for tag in self._tags] else: the_tags = [] - + return (self._string, the_tags) - + def to_struct(self): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -306,11 +306,11 @@ class StyledText(object): the_tags = [tag.to_struct() for tag in self._tags] else: the_tags = [] - + return {"_class": "StyledText", - "string": self._string, + "string": self._string, "tags": the_tags} - + @classmethod def from_struct(cls, struct): """ @@ -320,18 +320,18 @@ class StyledText(object): """ default = StyledText() return (struct.get("string", default.string), - [StyledTextTag.from_struct(t) + [StyledTextTag.from_struct(t) for t in struct.get("tags", default.tags)]) def unserialize(self, data): """ Convert a serialized tuple of data to an object. - + :param data: Serialized format of instance variables. :type data: tuple """ (self._string, the_tags) = data - + # I really wonder why this doesn't work... it does for all other types #self._tags = [StyledTextTag().unserialize(tag) for tag in the_tags] for tag in the_tags: @@ -339,11 +339,11 @@ class StyledText(object): stt.unserialize(tag) self._tags.append(stt) return self - + def get_tags(self): """ Return the list of formatting tags. - + :return: The formatting tags applied on the text. :rtype: list of 0 or more :py:class:`.StyledTextTag` instances. """ @@ -362,14 +362,14 @@ if __name__ == '__main__': from .styledtexttagtype import StyledTextTagType T1 = StyledTextTag(StyledTextTagType(1), 'v1', [(0, 2), (2, 4), (4, 6)]) T2 = StyledTextTag(StyledTextTagType(2), 'v2', [(1, 3), (3, 5), (0, 7)]) - + A = StyledText('123X456', [T1]) B = StyledText("abcXdef", [T2]) - + C = StyledText('\n') - + S = 'cleartext' - + C = C.join([A, S, B]) L = C.split() C = C.replace('X', StyledText('_')) diff --git a/gramps/gen/lib/styledtexttag.py b/gramps/gen/lib/styledtexttag.py index 9a1f167ba..4e2ed04df 100644 --- a/gramps/gen/lib/styledtexttag.py +++ b/gramps/gen/lib/styledtexttag.py @@ -35,24 +35,24 @@ from .styledtexttagtype import StyledTextTagType #------------------------------------------------------------------------- class StyledTextTag(object): """Hold formatting information for :py:class:`.StyledText`. - + :py:class:`StyledTextTag` is a container class, it's attributes are directly accessed. - + :ivar name: Type (or name) of the tag instance. E.g. 'bold', etc. :type name: :py:class:`.StyledTextTagType` instace :ivar value: Value of the tag. E.g. color hex string for font color, etc. :type value: str or None :ivar ranges: Pointer pairs into the string, where the tag applies. :type ranges: list of (int(start), int(end)) tuples. - + """ def __init__(self, name=None, value=None, ranges=None): """Setup initial instance variable values. - + .. note:: Since :py:class:`.GrampsType` supports the instance initialization with several different base types, please note - that ``name`` parameter can be int, str, unicode, tuple, + that ``name`` parameter can be int, str, unicode, tuple, or even another :py:class:`.StyledTextTagType` instance. """ self.name = StyledTextTagType(name) @@ -65,18 +65,18 @@ class StyledTextTag(object): def serialize(self): """Convert the object to a serialized tuple of data. - + :return: Serialized format of the instance. :rtype: tuple - + """ return (self.name.serialize(), self.value, self.ranges) - + def to_struct(self): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -93,10 +93,10 @@ class StyledTextTag(object): :rtype: dict """ return {"_class": "StyledTextTag", - "name": self.name.to_struct(), - "value": self.value, + "name": self.name.to_struct(), + "value": self.value, "ranges": self.ranges} - + @classmethod def from_struct(cls, struct): """ @@ -111,13 +111,13 @@ class StyledTextTag(object): def unserialize(self, data): """Convert a serialized tuple of data to an object. - + :param data: Serialized format of instance variables. :type data: tuple - + """ (the_name, self.value, self.ranges) = data - + self.name = StyledTextTagType() self.name.unserialize(the_name) return self diff --git a/gramps/gen/lib/styledtexttagtype.py b/gramps/gen/lib/styledtexttagtype.py index 6056520a6..669e87ed3 100644 --- a/gramps/gen/lib/styledtexttagtype.py +++ b/gramps/gen/lib/styledtexttagtype.py @@ -42,9 +42,9 @@ from .grampstype import GrampsType #------------------------------------------------------------------------- class StyledTextTagType(GrampsType): """Text formatting tag type definition. - + Here we only define new class variables. For details see :class:`~gen.lib.grampstype.GrampsType`. - + """ NONE_TYPE = -1 BOLD = 0 @@ -56,10 +56,10 @@ class StyledTextTagType(GrampsType): HIGHLIGHT = 6 SUPERSCRIPT = 7 LINK = 8 - + _CUSTOM = NONE_TYPE _DEFAULT = NONE_TYPE - + _DATAMAP = [ (BOLD, _("Bold"), "bold"), (ITALIC, _("Italic"), "italic"), @@ -83,7 +83,7 @@ class StyledTextTagType(GrampsType): SUPERSCRIPT: bool, LINK: str, } - + STYLE_DEFAULT = { BOLD: False, ITALIC: False, diff --git a/gramps/gen/lib/surname.py b/gramps/gen/lib/surname.py index 7a90ad900..f3d30959b 100644 --- a/gramps/gen/lib/surname.py +++ b/gramps/gen/lib/surname.py @@ -68,14 +68,14 @@ class Surname(SecondaryObject): """ Convert the object to a serialized tuple of data. """ - return (self.surname, self.prefix, self.primary, + return (self.surname, self.prefix, self.primary, self.origintype.serialize(), self.connector) def to_struct(self): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -92,10 +92,10 @@ class Surname(SecondaryObject): :rtype: dict """ return {"_class": "Surname", - "surname": self.surname, - "prefix": self.prefix, - "primary": self.primary, - "origintype": self.origintype.to_struct(), + "surname": self.surname, + "prefix": self.prefix, + "primary": self.primary, + "origintype": self.origintype.to_struct(), "connector": self.connector} @classmethod @@ -111,7 +111,7 @@ class Surname(SecondaryObject): struct.get("primary", default.primary), NameOriginType.from_struct(struct.get("origintype", {})), struct.get("connector", default.connector)) - + def is_empty(self): """ Indicate if the surname is empty. @@ -172,32 +172,32 @@ class Surname(SecondaryObject): def get_surname(self): """ - Return the surname. - + Return the surname. + The surname is one of the not given names coming from the parents """ return self.surname def set_surname(self, val): """ - Set the surname. - + Set the surname. + The surname is one of the not given names coming from the parents """ self.surname = val def get_prefix(self): """ - Return the prefix (or article) of the surname. - + Return the prefix (or article) of the surname. + The prefix is not used for sorting or grouping. """ return self.prefix def set_prefix(self, val): """ - Set the prefix (or article) of the surname. - + Set the prefix (or article) of the surname. + Examples of articles would be 'de' or 'van'. """ self.prefix = val @@ -212,14 +212,14 @@ class Surname(SecondaryObject): def set_connector(self, connector): """ - Set the connector for the Surname instance. This defines how a + Set the connector for the Surname instance. This defines how a surname connects to the next surname (eg in Spanish names). """ self.connector = connector def get_connector(self): """ - Get the connector for the Surname instance. This defines how a + Get the connector for the Surname instance. This defines how a surname connects to the next surname (eg in Spanish names). """ return self.connector diff --git a/gramps/gen/lib/surnamebase.py b/gramps/gen/lib/surnamebase.py index d6b4ffb1a..38f4b25e2 100644 --- a/gramps/gen/lib/surnamebase.py +++ b/gramps/gen/lib/surnamebase.py @@ -45,9 +45,9 @@ class SurnameBase(object): def __init__(self, source=None): """ - Initialize a SurnameBase. - - If the source is not None, then object is initialized from values of + Initialize a SurnameBase. + + If the source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object @@ -65,7 +65,7 @@ class SurnameBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -100,7 +100,7 @@ class SurnameBase(object): def add_surname(self, surname): """ - Add the :class:`~.surname.Surname` instance to the object's + Add the :class:`~.surname.Surname` instance to the object's list of surnames. :param surname: :class:`~.surname.Surname` instance to add to the @@ -113,11 +113,11 @@ class SurnameBase(object): """ Remove the specified :class:`~.surname.Surname` instance from the surname list. - + If the instance does not exist in the list, the operation has no effect. - :param surname: :class:`~.surname.Surname` instance to remove + :param surname: :class:`~.surname.Surname` instance to remove from the list :type surname: :class:`~.surname.Surname` @@ -143,9 +143,9 @@ class SurnameBase(object): def set_surname_list(self, surname_list): """ - Assign the passed list to the object's list of + Assign the passed list to the object's list of :class:`~.surname.Surname` instances. - + :param surname_list: List of :class:`~.surname.Surname` instances to be associated with the object :type surname_list: list @@ -155,7 +155,7 @@ class SurnameBase(object): def get_primary_surname(self): """ Return the surname that is the primary surname - + :returns: Returns the surname instance that is the primary surname. If primary not set, and there is a surname, the first surname is given, if no surnames, None is returned @@ -187,7 +187,7 @@ class SurnameBase(object): """ Merge the list of surname from acquisition with our own. This method is normally only called when surnames are equal, if they - are different, the merge code should fall back to storing an + are different, the merge code should fall back to storing an alternate name. For completeness, the code is present nevertheless. :param acquisition: the surname list of this object will be merged with @@ -226,14 +226,14 @@ class SurnameBase(object): 'second': surn.get_connector()} fsurn = fsurn.strip() totalsurn = _('%(first)s %(second)s') % {'first': totalsurn, - 'second': fsurn} + 'second': fsurn} return totalsurn.strip() - + def get_upper_surname(self): """Return a fully formatted surname capitalized""" return self.get_surname().upper() - + def get_surnames(self): """ Return a list of surnames (no prefix or connectors) @@ -255,7 +255,7 @@ class SurnameBase(object): if prefix: prefixl.append(prefix) return prefixl - + def get_connectors(self): """ Return a list of surnames (no prefix or connectors) diff --git a/gramps/gen/lib/tableobj.py b/gramps/gen/lib/tableobj.py index 3d4f0594d..70b3ca91d 100644 --- a/gramps/gen/lib/tableobj.py +++ b/gramps/gen/lib/tableobj.py @@ -56,14 +56,14 @@ class TableObject(BaseObject): changed time. The database handle is used as the unique key for a record in the database. This is not the same as the Gramps ID, which is a user visible identifier for a record. - - It is the base class for the BasicPrimaryObject class and Tag class. + + It is the base class for the BasicPrimaryObject class and Tag class. """ - + def __init__(self, source=None): """ - Initialize a TableObject. - + Initialize a TableObject. + If source is None, the handle is assigned as an empty string. If source is not None, then the handle is initialized from the value in the source object. @@ -80,11 +80,11 @@ class TableObject(BaseObject): def get_change_time(self): """ - Return the time that the data was last changed. - + Return the time that the data was last changed. + The value in the format returned by the :meth:`time.time()` command. - - :returns: Time that the data was last changed. The value in the format + + :returns: Time that the data was last changed. The value in the format returned by the :meth:`time.time()` command. :rtype: int """ @@ -92,8 +92,8 @@ class TableObject(BaseObject): def set_change_time(self, change): """ - Modify the time that the data was last changed. - + Modify the time that the data was last changed. + The value must be in the format returned by the :meth:`time.time()` command. @@ -108,7 +108,7 @@ class TableObject(BaseObject): :returns: string representation of the last change time. :rtype: str - + """ if self.change: return str(time.strftime('%x %X', time.localtime(self.change)), diff --git a/gramps/gen/lib/tag.py b/gramps/gen/lib/tag.py index 05843fd1f..d9d4a18da 100644 --- a/gramps/gen/lib/tag.py +++ b/gramps/gen/lib/tag.py @@ -51,7 +51,7 @@ class Tag(TableObject): """ TableObject.__init__(self, source) - + if source: self.__name = source.__name self.__color = source.__color @@ -64,9 +64,9 @@ class Tag(TableObject): def serialize(self): """ Convert the data held in the event to a Python tuple that - represents all the data elements. - - This method is used to convert the object into a form that can easily + represents all the data elements. + + This method is used to convert the object into a form that can easily be saved to a database. These elements may be primitive Python types (string, integers), @@ -159,8 +159,8 @@ class Tag(TableObject): def set_color(self, color): """ - Set the color of the Tag to the passed string. - + Set the color of the Tag to the passed string. + The string is of the format #rrrrggggbbbb. :param color: Color to assign to the Tag @@ -181,8 +181,8 @@ class Tag(TableObject): def set_priority(self, priority): """ - Set the priority of the Tag to the passed integer. - + Set the priority of the Tag to the passed integer. + The lower the value the higher the priority. :param priority: Priority to assign to the Tag @@ -203,7 +203,7 @@ class Tag(TableObject): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -239,6 +239,6 @@ class Tag(TableObject): struct.get("color", default.color), struct.get("priority", default.priority), struct.get("change", default.change)) - + priority = property(get_priority, set_priority, None, 'Returns or sets priority of the tag') diff --git a/gramps/gen/lib/tagbase.py b/gramps/gen/lib/tagbase.py index d7f49dd1f..20ca269ef 100644 --- a/gramps/gen/lib/tagbase.py +++ b/gramps/gen/lib/tagbase.py @@ -36,9 +36,9 @@ class TagBase(object): def __init__(self, source=None): """ - Initialize a TagBase. - - If the source is not None, then object is initialized from values of + Initialize a TagBase. + + If the source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object @@ -59,7 +59,7 @@ class TagBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -106,7 +106,7 @@ class TagBase(object): def remove_tag(self, tag): """ Remove the specified tag from the tag list. - + If the tag does not exist in the list, the operation has no effect. :param tag: tag to remove from the list. @@ -124,7 +124,7 @@ class TagBase(object): def get_tag_list(self): """ Return the list of tags associated with the object. - + :returns: Returns the list of tags. :rtype: list """ @@ -142,10 +142,10 @@ class TagBase(object): def get_referenced_tag_handles(self): """ Return the list of (classname, handle) tuples for all referenced tags. - + This method should be used to get the :class:`~.tag.Tag` portion of the list by objects that store tag lists. - + :returns: List of (classname, handle) tuples for referenced objects. :rtype: list """ diff --git a/gramps/gen/lib/test/date_test.py b/gramps/gen/lib/test/date_test.py index b1ea4992b..96912921f 100644 --- a/gramps/gen/lib/test/date_test.py +++ b/gramps/gen/lib/test/date_test.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -145,11 +145,11 @@ date_tests[testset] = dates # test for all other different calendars testset = "Non-gregorian" dates = [] -for calendar in (Date.CAL_JULIAN, - Date.CAL_HEBREW, - Date.CAL_ISLAMIC, - Date.CAL_FRENCH, - Date.CAL_PERSIAN, +for calendar in (Date.CAL_JULIAN, + Date.CAL_HEBREW, + Date.CAL_ISLAMIC, + Date.CAL_FRENCH, + Date.CAL_PERSIAN, ): for quality in (Date.QUAL_NONE, Date.QUAL_ESTIMATED, Date.QUAL_CALCULATED): for modifier in (Date.MOD_NONE, Date.MOD_BEFORE, Date.MOD_AFTER, Date.MOD_ABOUT): @@ -184,9 +184,9 @@ with Context(Date.CAL_SWEDISH) as calendar: quality = Date.QUAL_NONE modifier = Date.MOD_NONE -for calendar in (Date.CAL_JULIAN, - Date.CAL_ISLAMIC, - Date.CAL_PERSIAN, +for calendar in (Date.CAL_JULIAN, + Date.CAL_ISLAMIC, + Date.CAL_PERSIAN, ): for month in range(1,13): d = Date() @@ -238,13 +238,13 @@ class ParserDateTest(BaseDateTest): for date_format in range(len(get_date_formats())): set_format(date_format) - for dateval in date_tests[testset]: + for dateval in date_tests[testset]: datestr = _dd.display(dateval) ndate = _dp.parse(datestr) self.assertTrue(dateval.is_equal(ndate), "dateval fails is_equal in format %d:\n" " '%s' != '%s'\n" - " '%s' != '%s'\n" % + " '%s' != '%s'\n" % (date_format, dateval, ndate, dateval.to_struct(), ndate.to_struct())) def test_basic(self): @@ -280,7 +280,7 @@ class MatchDateTest(BaseDateTest): ("before 1961", "before 1961", True), ("jan 1, 1960", "jan 1, 1960", True), ("dec 31, 1959", "dec 31, 1959", True), - ("before 1960", "jan 1, 1960", False), + ("before 1960", "jan 1, 1960", False), ("before 1960", "dec 31, 1959", True), ("abt 1960", "1960", True), ("abt 1960", "before 1960", True), @@ -329,24 +329,24 @@ class MatchDateTest(BaseDateTest): ("jan 1, 2000/1", "jan 14, 2001", True), ("jan 1, 2000/1", "jan 1, 2001 (julian)", True), ("about 1984", "about 2005", False), - ("about 1990", "about 2005", True), - ("about 2007", "about 2006", True), - ("about 1995", "after 2000", True), + ("about 1990", "about 2005", True), + ("about 2007", "about 2006", True), + ("about 1995", "after 2000", True), ("about 1995", "after 2005", False), - ("about 2007", "about 2003", True), - ("before 2007", "2000", True), + ("about 2007", "about 2003", True), + ("before 2007", "2000", True), # offsets # different calendar, same date - ("1800-8-3", "15 Thermidor 8 (French Republican)", True), - ("after 1800-8-3", "before 15 Thermidor 8 (French Republican)", False), + ("1800-8-3", "15 Thermidor 8 (French Republican)", True), + ("after 1800-8-3", "before 15 Thermidor 8 (French Republican)", False), ("ab cd", "54 ab cd 2000", True, False), - ("1700-02-29 (Julian)", "1700-03-01 (Swedish)", True), - ("1706-12-31 (Julian)", "1707-01-01 (Swedish)", True), - ("1712-02-28 (Julian)", "1712-02-29 (Swedish)", True), - ("1712-02-29 (Julian)", "1712-02-30 (Swedish)", True), + ("1700-02-29 (Julian)", "1700-03-01 (Swedish)", True), + ("1706-12-31 (Julian)", "1707-01-01 (Swedish)", True), + ("1712-02-28 (Julian)", "1712-02-29 (Swedish)", True), + ("1712-02-29 (Julian)", "1712-02-30 (Swedish)", True), # See bug# 7100 - ("1233-12-01", "1234-12-01 (Mar25)", True), - ("1234-01-04", "1234-01-04 (Mar25)", True), + ("1233-12-01", "1234-12-01 (Mar25)", True), + ("1234-01-04", "1234-01-04 (Mar25)", True), # See bug# 7158 # Some issues passing Travis close to midnight; not sure why: # ("today", Today(), True), @@ -354,8 +354,8 @@ class MatchDateTest(BaseDateTest): ("today", "today", True), (Today(), Today(), True), # See bug# 7197 - ("1788-03-27", "1789-03-27 (Mar25)", True), - ("1788-03-27 (Julian)", "1789-03-27 (Julian, Mar25)", True), + ("1788-03-27", "1789-03-27 (Mar25)", True), + ("1788-03-27 (Julian)", "1789-03-27 (Julian, Mar25)", True), ] def convert_to_date(self, d): @@ -370,14 +370,14 @@ class MatchDateTest(BaseDateTest): self.assertMatch(d1, d2, expected1) self.assertMatch(d2, d1, expected2) - + def assertMatch(self, d1, d2, expected): date1 = self.convert_to_date(d1) date2 = self.convert_to_date(d2) result = date2.match(date1) - self.assertEqual(result, expected, + self.assertEqual(result, expected, "'{}' {} '{}'\n({} vs {})".format( - d1, + d1, ("did not match" if expected else "matched"), d2, date1.to_struct(), date2.to_struct())) @@ -428,7 +428,7 @@ class ArithmeticDateTest(BaseDateTest): for exp1, exp2 in self.tests: val1 = eval(exp1) val2 = eval(exp2) - self.assertEqual(val1, val2, + self.assertEqual(val1, val2, "'%s' should be '%s' but was '%s'" % (exp1, val2, val1)) #------------------------------------------------------------------------- @@ -442,7 +442,7 @@ class SwedishDateTest(BaseDateTest): """ def test_swedish(self): for date in swedish_dates: - self.assertEqual(date.sortval, + self.assertEqual(date.sortval, date.to_calendar('gregorian').sortval) class Test_set2(BaseDateTest): @@ -493,7 +493,7 @@ class Test_set2(BaseDateTest): self.assertEqual(stop, (2009, 1, 1)) def test_copy_ymd_preserves_orig(self): - copied = self.date.copy_ymd(year=1000, month=10, day=10, + copied = self.date.copy_ymd(year=1000, month=10, day=10, remove_stop_date=True) self.testStartStopSanity() start,stop = copied.get_start_stop_range() @@ -501,7 +501,7 @@ class Test_set2(BaseDateTest): self.assertEqual(stop, (1000, 10, 10)) def _test_set2_function_raises_error_unless_compound(self, function): - for mod in (Date.MOD_NONE, Date.MOD_BEFORE, Date.MOD_AFTER, + for mod in (Date.MOD_NONE, Date.MOD_BEFORE, Date.MOD_AFTER, Date.MOD_ABOUT, Date.MOD_TEXTONLY): self.date.set_modifier(mod) diff --git a/gramps/gen/lib/test/grampstype_test.py b/gramps/gen/lib/test/grampstype_test.py index 0ac4769db..47ad36f5d 100644 --- a/gramps/gen/lib/test/grampstype_test.py +++ b/gramps/gen/lib/test/grampstype_test.py @@ -36,7 +36,7 @@ class GT0(GrampsType): _DATAMAP = MAP # NOTE: this type of code might be used in a migration utility -# to allow conversions or other handling of retired type-values +# to allow conversions or other handling of retired type-values # A migration utility might instantiate several of these with # varying blacklist-specs class GT1(GT0): @@ -55,22 +55,22 @@ class Test1(unittest.TestCase): g = len(self.gt._E2IMAP) self.assertEqual(g, e) - # init sets values for int, str, tuple + # init sets values for int, str, tuple # (we ignore instance here -- maybe SB tested, too?) # this test depends on having _DEFAULT=1, _CUSTOM=3 # NB: tuple tests w/ lengths < 2 fail before release 10403 def test_init_value(self): - for i, v, u in ( + for i, v, u in ( (None, 1, 'abab'), # all DEFAULT - (0, 0, 'zzzz'), - (1, 1, 'abab'), + (0, 0, 'zzzz'), + (1, 1, 'abab'), ('efef', 3, 'efef'), # matches CUSTOM ('zzzz', 0, 'zzzz'), - ('x', 3, 'x'), # nomatch gives CUSTOM - ('', 3, ''), # nomatch gives CUSTOM + ('x', 3, 'x'), # nomatch gives CUSTOM + ('', 3, ''), # nomatch gives CUSTOM ((0,'zero'), 0, 'zzzz'), # normal behavior - ((2,), 2, 'cdcd'), # DEFAULT-string, just like int - ((), 1, 'abab'), # DEFAULT-pair + ((2,), 2, 'cdcd'), # DEFAULT-string, just like int + ((), 1, 'abab'), # DEFAULT-pair ): self.gt = GT0(i) g = self.gt.value @@ -82,14 +82,14 @@ class Test1(unittest.TestCase): class Test2(unittest.TestCase): def test_blacklist(self): self.gt = GT1() - # check that MAPs have lengths reduced by blacklist - e = len(keys) - len(BLIST) + # check that MAPs have lengths reduced by blacklist + e = len(keys) - len(BLIST) g = len(self.gt._E2IMAP) self.assertEqual(g, e) self.ub=GT2() # check that these MAPS are now un-blacklisted - e = len(keys) + e = len(keys) g = len(self.ub._E2IMAP) self.assertEqual(g, e) diff --git a/gramps/gen/lib/test/merge_test.py b/gramps/gen/lib/test/merge_test.py index 98c969f44..cddaf9030 100644 --- a/gramps/gen/lib/test/merge_test.py +++ b/gramps/gen/lib/test/merge_test.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -1725,7 +1725,7 @@ class CitationBaseCheck(unittest.TestCase): self.obj_list.add_citation(citation.handle) self.phoenix._merge_citation_list(self.titanic) self.assertEqual(self.phoenix.serialize(), self.obj_list.serialize()) - + def test_merge_different(self): citation = Citation() citation.set_reference_handle('234567') diff --git a/gramps/gen/lib/test/struct_test.py b/gramps/gen/lib/test/struct_test.py index 2546601c5..779c17bab 100644 --- a/gramps/gen/lib/test/struct_test.py +++ b/gramps/gen/lib/test/struct_test.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -22,7 +22,7 @@ import unittest -from .. import (Person, Family, Event, Source, Place, Citation, +from .. import (Person, Family, Event, Source, Place, Citation, Repository, MediaObject, Note, Tag) from gramps.gen.merge.diff import import_as_dict, from_struct from gramps.cli.user import User @@ -120,10 +120,10 @@ class StructTest(unittest.TestCase): self.assertEqual(s["gramps_id"], "F0001") s["gramps_id"] = "TEST" self.assertEqual(s["gramps_id"], "TEST") - self.assertEqual(s.father_handle.primary_name.first_name, + self.assertEqual(s.father_handle.primary_name.first_name, "Allen Carl") s["father_handle.primary_name.first_name"] = "Edward" - self.assertEqual(s["father_handle.primary_name.first_name"], + self.assertEqual(s["father_handle.primary_name.first_name"], "Edward") if __name__ == "__main__": diff --git a/gramps/gen/lib/url.py b/gramps/gen/lib/url.py index 9dee07a4d..34017f727 100644 --- a/gramps/gen/lib/url.py +++ b/gramps/gen/lib/url.py @@ -71,7 +71,7 @@ class Url(SecondaryObject, PrivacyBase): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -88,9 +88,9 @@ class Url(SecondaryObject, PrivacyBase): :rtype: dict """ return {"_class": "Url", - "private": self.private, - "path": self.path, - "desc": self.desc, + "private": self.private, + "path": self.path, + "desc": self.desc, "type": self.type.to_struct()} @classmethod @@ -101,11 +101,11 @@ class Url(SecondaryObject, PrivacyBase): :returns: Returns a serialized object """ default = Url() - return (struct.get("private", default.private), - struct.get("path", default.path), - struct.get("desc", default.desc), + return (struct.get("private", default.private), + struct.get("path", default.path), + struct.get("desc", default.desc), UrlType.from_struct(struct.get("type", {}))) - + def unserialize(self, data): (self.private, self.path, self.desc, type_value) = data self.type.unserialize(type_value) @@ -196,7 +196,7 @@ class Url(SecondaryObject, PrivacyBase): netloc 1 Network location part path 2 Hierarchical path params 3 Parameters for last path element - query 4 Query component + query 4 Query component fragment 5 Fragment identifier ======== === ================================= """ diff --git a/gramps/gen/lib/urlbase.py b/gramps/gen/lib/urlbase.py index ab2411976..f4caded90 100644 --- a/gramps/gen/lib/urlbase.py +++ b/gramps/gen/lib/urlbase.py @@ -42,9 +42,9 @@ class UrlBase(object): def __init__(self, source=None): """ - Initialize an UrlBase. - - If the source is not None, then object is initialized from values of + Initialize an UrlBase. + + If the source is not None, then object is initialized from values of the source object. :param source: Object used to initialize the new object @@ -62,7 +62,7 @@ class UrlBase(object): """ Convert the data held in this object to a structure (eg, struct) that represents all the data elements. - + This method is used to recursively convert the object into a self-documenting form that can easily be used for various purposes, including diffs and queries. @@ -144,11 +144,11 @@ class UrlBase(object): :type url: :class:`~.url.Url` """ self.urls.append(url) - + def remove_url(self, url): """ Remove the specified :class:`~.url.Url` instance from the url list. - + If the instance does not exist in the list, the operation has no effect. :param url: :class:`~.url.Url` instance to remove from the list diff --git a/gramps/gen/lib/urltype.py b/gramps/gen/lib/urltype.py index b6c6e25e8..f04f26cf2 100644 --- a/gramps/gen/lib/urltype.py +++ b/gramps/gen/lib/urltype.py @@ -62,4 +62,4 @@ class UrlType(GrampsType): GrampsType.__init__(self, value) - + diff --git a/gramps/gen/merge/diff.py b/gramps/gen/merge/diff.py index eaeac1439..2e453abc4 100644 --- a/gramps/gen/merge/diff.py +++ b/gramps/gen/merge/diff.py @@ -80,7 +80,7 @@ def get_schema(cls): "urls": [Url], "lds_ord_list": [LdsOrd], "citation_list": [Handle("Citation", "CITATION-HANDLE")], - "note_list": [Handle("Note", "NOTE-HANDLE")], + "note_list": [Handle("Note", "NOTE-HANDLE")], "change": int, "tag_list": [Handle("Tag", "TAG-HANDLE")], "private": bool, @@ -118,7 +118,7 @@ def get_schema(cls): if isinstance(schema, type): schema = get_schema(schema) return schema - + def parse(string): """ Break a string up into a struct-path. Used by get_schema() and setitem(). @@ -135,7 +135,7 @@ def parse(string): for p in range(len(string)): c = string[p] if c == "]": - if stack and stack[-1] == "[": # end + if stack and stack[-1] == "[": # end stack.pop(-1) current += c retval.append(current) @@ -146,7 +146,7 @@ def parse(string): current = "" current += c elif c in ["'", '"']: - if stack and stack[-1] == c: # end + if stack and stack[-1] == c: # end stack.pop(-1) current += c if stack and stack[-1] in ["'", '"', '[']: # in quote or args @@ -259,10 +259,10 @@ def diff_items(path, json1, json2): def diff_dbs(db1, db2, user=None): """ - 1. new objects => mark for insert + 1. new objects => mark for insert 2. deleted objects, no change locally after delete date => mark for deletion - 3. deleted objects, change locally => mark for user confirm for + 3. deleted objects, change locally => mark for user confirm for deletion 4. updated objects => do a diff on differences, mark origin values as new data @@ -272,7 +272,7 @@ def diff_dbs(db1, db2, user=None): missing_from_old = [] missing_from_new = [] diffs = [] - with user.progress(_('Family Tree Differences'), + with user.progress(_('Family Tree Differences'), _('Searching...'), 10) as step: for item in ['Person', 'Family', 'Source', 'Citation', 'Event', 'Media', 'Place', 'Repository', 'Note', 'Tag']: @@ -307,7 +307,7 @@ def diff_dbs(db1, db2, user=None): item2 = db2._tables[item]["handle_func"](handles2[p2]) missing_from_old += [(item, item2)] p2 += 1 - return diffs, missing_from_old, missing_from_new + return diffs, missing_from_old, missing_from_new def diff_db_to_file(old_db, filename, user=None): if user is None: @@ -318,12 +318,12 @@ def diff_db_to_file(old_db, filename, user=None): # Next get differences: diffs, m_old, m_new = diff_dbs(old_db, new_db, user) return diffs, m_old, m_new - + def from_struct(struct): """ Given a struct with metadata, create a Gramps object. """ - from gramps.gen.lib import (Person, Family, Event, Source, Place, Citation, + from gramps.gen.lib import (Person, Family, Event, Source, Place, Citation, Repository, MediaObject, Note, Tag) if isinstance(struct, dict): if "_class" in struct.keys(): @@ -437,7 +437,7 @@ class Struct(object): return len(self.struct) def __contains__(self, item): - return item in self.struct + return item in self.struct def __call__(self, *args, **kwargs): """ @@ -494,14 +494,14 @@ class Struct(object): def __getattr__(self, attr): """ Called when getattr fails. Lookup attr in struct; returns Struct - if more struct. + if more struct. >>> Struct({}, db).primary_name returns: Struct([], db) or value struct can be list/tuple, dict with _class, or value (including dict). - self.setitem_from_path(path, v) should be used to set value of + self.setitem_from_path(path, v) should be used to set value of item. """ if isinstance(self.struct, dict) and "_class" in self.struct.keys(): @@ -524,7 +524,7 @@ class Struct(object): def __getitem__(self, item): """ Called when getitem fails. Lookup item in struct; returns Struct - if more struct. + if more struct. >>> Struct({}, db)[12] returns: Struct([], db) or value @@ -558,7 +558,7 @@ class Struct(object): """ If the item is a handle, look up reference object. """ - if isinstance(item, HandleClass) and self.db: + if isinstance(item, HandleClass) and self.db: obj = self.get_object_from_handle(item) if obj: return Struct(obj.to_struct(), self.db) diff --git a/gramps/gen/merge/mergecitationquery.py b/gramps/gen/merge/mergecitationquery.py index cf8e6cd24..d0d7702ca 100644 --- a/gramps/gen/merge/mergecitationquery.py +++ b/gramps/gen/merge/mergecitationquery.py @@ -90,19 +90,19 @@ class MergeCitationQuery(object): elif class_name == Repository.__name__: repository = self.database.get_repository_from_handle(handle) assert(repository.has_citation_reference(old_handle)) - repository.replace_citation_references(old_handle, + repository.replace_citation_references(old_handle, new_handle) self.database.commit_repository(repository, trans) elif class_name == Citation.__name__: citation = self.database.get_citation_from_handle(handle) assert(citation.has_citation_reference(old_handle)) - citation.replace_citation_references(old_handle, + citation.replace_citation_references(old_handle, new_handle) self.database.commit_citation(citation, trans) elif class_name == Source.__name__: source = self.database.get_source_from_handle(handle) assert(source.has_citation_reference(old_handle)) - source.replace_citation_references(old_handle, + source.replace_citation_references(old_handle, new_handle) self.database.commit_source(source, trans) else: diff --git a/gramps/gen/merge/mergepersonquery.py b/gramps/gen/merge/mergepersonquery.py index aa71d0c56..3da91ef74 100644 --- a/gramps/gen/merge/mergepersonquery.py +++ b/gramps/gen/merge/mergepersonquery.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -84,7 +84,7 @@ class MergePersonQuery(object): if main_family_handle in child.parent_family_list: child.remove_handle_references('Family', [family_handle]) else: - child.replace_handle_reference('Family', family_handle, + child.replace_handle_reference('Family', family_handle, main_family_handle) self.database.commit_person(child, trans) if self.phoenix: diff --git a/gramps/gen/merge/test/merge_ref_test.py b/gramps/gen/merge/test/merge_ref_test.py index 717d6f350..1eaf7570e 100644 --- a/gramps/gen/merge/test/merge_ref_test.py +++ b/gramps/gen/merge/test/merge_ref_test.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -1503,7 +1503,7 @@ class FamilyPersonCheck(BaseMergeCheck): test_error_str=_("A person with multiple relations " "with the same spouse is about to be merged. This is " "beyond the capabilities of the merge routine. The " - "merge is aborted.")) + "merge is aborted.")) def test_merge_fam(self): """Merge two persons such that also the families in which they are diff --git a/gramps/gen/mime/_pythonmime.py b/gramps/gen/mime/_pythonmime.py index aefa229e9..d9dd7f5f6 100644 --- a/gramps/gen/mime/_pythonmime.py +++ b/gramps/gen/mime/_pythonmime.py @@ -54,7 +54,7 @@ def get_type(filename): return value[0] else: return _('unknown') - + def mime_type_is_defined(mime_type): """ Return True if a description for a mime type exists. diff --git a/gramps/gen/mime/_winmime.py b/gramps/gen/mime/_winmime.py index 34d87aae9..545d37ba3 100644 --- a/gramps/gen/mime/_winmime.py +++ b/gramps/gen/mime/_winmime.py @@ -44,7 +44,7 @@ def get_description(mime_type): desc = None extension = _get_extension(mime_type) progid = _get_prog_id(extension) - + if progid: try: hcr = ConnectRegistry(None, HKEY_CLASSES_ROOT) @@ -71,7 +71,7 @@ def mime_type_is_defined(mime_type): return True else: return _pythonmime.mime_type_is_defined(mime_type) - + #------------------------------------------------------------------------- # # private functions @@ -93,7 +93,7 @@ def _get_extension(mime_type): CloseKey(hcr) except WindowsError: extension = None - + if not extension: # Work around for Windows mime problems extmap = { @@ -102,9 +102,9 @@ def _get_extension(mime_type): } if mime_type in extmap: extension = extmap[mime_type] - + return extension - + def _get_prog_id(extension): """ Return the program ID associated with this extension @@ -112,7 +112,7 @@ def _get_prog_id(extension): """ if not extension: return None - + try: hcr = ConnectRegistry(None, HKEY_CLASSES_ROOT) progid = QueryValue(hcr, extension) @@ -120,4 +120,4 @@ def _get_prog_id(extension): return progid except WindowsError: return None - + diff --git a/gramps/gen/plug/__init__.py b/gramps/gen/plug/__init__.py index 044fd3878..1a344f7a0 100644 --- a/gramps/gen/plug/__init__.py +++ b/gramps/gen/plug/__init__.py @@ -25,11 +25,11 @@ The "plug" package for handling plugins in Gramps. """ from ._plugin import Plugin -from ._pluginreg import (PluginData, PluginRegister, REPORT, TOOL, - CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_CODE, +from ._pluginreg import (PluginData, PluginRegister, REPORT, TOOL, + CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_CODE, CATEGORY_WEB, CATEGORY_BOOK, CATEGORY_GRAPHVIZ, TOOL_DEBUG, TOOL_ANAL, TOOL_DBPROC, TOOL_DBFIX, TOOL_REVCTL, - TOOL_UTILS, CATEGORY_QR_MISC, CATEGORY_QR_PERSON, + TOOL_UTILS, CATEGORY_QR_MISC, CATEGORY_QR_PERSON, CATEGORY_QR_FAMILY, CATEGORY_QR_EVENT, CATEGORY_QR_SOURCE, CATEGORY_QR_PLACE, CATEGORY_QR_REPOSITORY, CATEGORY_QR_NOTE, CATEGORY_QR_DATE, PTYPE_STR, CATEGORY_QR_MEDIA, @@ -46,12 +46,12 @@ from ._options import (Options, OptionListCollection, OptionList, OptionHandler, MenuOptions) __all__ = [ "docbackend", "docgen", "menu", Plugin, PluginData, - PluginRegister, BasePluginManager, + PluginRegister, BasePluginManager, ImportPlugin, ExportPlugin, DocGenPlugin, - REPORT, TOOL, CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_CODE, + REPORT, TOOL, CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_CODE, CATEGORY_WEB, CATEGORY_BOOK, CATEGORY_GRAPHVIZ, TOOL_DEBUG, TOOL_ANAL, TOOL_DBPROC, TOOL_DBFIX, TOOL_REVCTL, - TOOL_UTILS, CATEGORY_QR_MISC, CATEGORY_QR_PERSON, + TOOL_UTILS, CATEGORY_QR_MISC, CATEGORY_QR_PERSON, CATEGORY_QR_FAMILY, CATEGORY_QR_EVENT, CATEGORY_QR_SOURCE, CATEGORY_QR_PLACE, CATEGORY_QR_REPOSITORY, CATEGORY_QR_NOTE, CATEGORY_QR_DATE, PTYPE_STR, CATEGORY_QR_MEDIA, diff --git a/gramps/gen/plug/_docgenplugin.py b/gramps/gen/plug/_docgenplugin.py index 441acfbf0..0b8bad334 100644 --- a/gramps/gen/plug/_docgenplugin.py +++ b/gramps/gen/plug/_docgenplugin.py @@ -39,7 +39,7 @@ class DocGenPlugin(Plugin): :param description: A short description of the plugin. Example: "This plugin will generate text documents in plain text." :type description: string - :param basedoc: A class that implements the BaseDoc + :param basedoc: A class that implements the BaseDoc interface. :type basedoc: BaseDoc :param paper: Indicates whether the plugin uses paper or not. @@ -65,35 +65,35 @@ class DocGenPlugin(Plugin): self.__extension = extension self.__docoptclass = docoptclass self.__basedocname = basedocname - + def get_basedoc(self): """ Get the :class:`.BaseDoc` class for this plugin. - + :return: the :class:`.BaseDoc` class passed into :meth:`__init__` """ return self.__basedoc - + def get_paper_used(self): """ Get the paper flag for this plugin. - + :return: bool - True = use paper; False = do not use paper """ return self.__paper - + def get_style_support(self): """ Get the style flag for this plugin. - + :return: bool - True = use styles; False = do not use styles """ return self.__style - + def get_extension(self): """ Get the file extension for the output file. - + :return: str """ return self.__extension @@ -101,7 +101,7 @@ class DocGenPlugin(Plugin): def get_doc_option_class(self): """ Get the :class:`.DocOptions` subclass for this plugin, if any - + :return: the :class:`.DocOptions` subclass passed into :meth:`__init__` """ return self.__docoptclass @@ -109,15 +109,15 @@ class DocGenPlugin(Plugin): def get_basedocname(self): """ Get the :class:`.BaseDoc` name for this plugin. - - :return: the :class:`.BaseDoc` name passed into :meth:`__init__` + + :return: the :class:`.BaseDoc` name passed into :meth:`__init__` """ return self.__basedocname - + def get_text_support(self): """ Check if the plugin supports the :class:`.TextDoc` interface. - + :return: bool: True if :class:`.TextDoc` is supported; False if :class:`.TextDoc` is not supported. """ @@ -126,7 +126,7 @@ class DocGenPlugin(Plugin): def get_draw_support(self): """ Check if the plugin supports the :class:`.DrawDoc` interface. - + :return: bool: True if :class:`.DrawDoc` is supported; False if :class:`.DrawDoc` is not supported. """ diff --git a/gramps/gen/plug/_export.py b/gramps/gen/plug/_export.py index c01c8b434..922b4a597 100644 --- a/gramps/gen/plug/_export.py +++ b/gramps/gen/plug/_export.py @@ -28,7 +28,7 @@ class ExportPlugin(Plugin): """ This class represents a plugin for exporting data from Gramps """ - def __init__(self, name, description, export_function, + def __init__(self, name, description, export_function, extension, config=None): """ :param name: A friendly name to call this plugin. @@ -56,19 +56,19 @@ class ExportPlugin(Plugin): self.__export_func = export_function self.__extension = extension self.__config = config - + def get_export_function(self): """ Get the export function for this plugin. - + :return: the callable export_function passed into :meth:`__init__` """ return self.__export_func - + def get_extension(self): """ Get the file extension for the export file. - + :return: str """ return self.__extension @@ -76,7 +76,7 @@ class ExportPlugin(Plugin): def get_config(self): """ Get the config. - + :return: (??,??) """ return self.__config diff --git a/gramps/gen/plug/_gramplet.py b/gramps/gen/plug/_gramplet.py index 0159a8d03..5afcc23ff 100644 --- a/gramps/gen/plug/_gramplet.py +++ b/gramps/gen/plug/_gramplet.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -65,9 +65,9 @@ class Gramplet(object): self.on_load() self.build_options() self.connect(self.dbstate, "database-changed", self._db_changed) - self.connect(self.gui.textview, "button-press-event", - self.gui.on_button_press) - self.connect(self.gui.textview, "motion-notify-event", + self.connect(self.gui.textview, "button-press-event", + self.gui.on_button_press) + self.connect(self.gui.textview, "motion-notify-event", self.gui.on_motion) self.connect_signal('Person', self._active_changed) self._db_changed(self.dbstate.db) @@ -79,7 +79,7 @@ class Gramplet(object): def connect_signal(self, nav_type, method): """ Connect the given method to the active-changed signal for the - navigation type requested. + navigation type requested. """ self.uistate.register(self.dbstate, nav_type, self.nav_group) history = self.uistate.get_history(nav_type, self.nav_group) @@ -160,7 +160,7 @@ class Gramplet(object): def db_changed(self): """ - Method executed when the database is changed. + Method executed when the database is changed. """ pass @@ -183,7 +183,7 @@ class Gramplet(object): Returns the current text of the textview. """ return self.gui.get_text() - + def insert_text(self, text): """ Insert the given text in the textview at the cursor. @@ -201,11 +201,11 @@ class Gramplet(object): Clear all of the text from the textview. """ self.gui.clear_text() - + def set_text(self, text, scroll_to='start'): """ Clear and set the text to the given text. Additionally, move the - cursor to the position given. Positions are: + cursor to the position given. Positions are: ======== ======================================= Position Description @@ -220,7 +220,7 @@ class Gramplet(object): def append_text(self, text, scroll_to="end"): """ Append the text to the textview. Additionally, move the - cursor to the position given. Positions are: + cursor to the position given. Positions are: ======== ======================================= Position Description @@ -290,10 +290,10 @@ class Gramplet(object): The main interface for running the :meth:`main` method. """ from gi.repository import GObject, GLib - if ((not self.active or - self.gui.gstate in ["closed", "minimized"] or - not self.dbstate.open) and - not self.gui.force_update): + if ((not self.active or + self.gui.gstate in ["closed", "minimized"] or + not self.dbstate.open) and + not self.gui.force_update): self.dirty = True if self.dbstate.open: #print " %s is not active" % self.gui.gname @@ -308,7 +308,7 @@ class Gramplet(object): self.interrupt() self._generator = self.main() self._pause = False - self._idle_id = GLib.idle_add(self._updater, + self._idle_id = GLib.idle_add(self._updater, priority=GObject.PRIORITY_LOW - 10) def _updater(self): @@ -327,7 +327,7 @@ class Gramplet(object): if self._pause: LOG.debug("gramplet updater: %s: return False" % self.gui.title) return False - LOG.debug("gramplet updater: %s: return %s" % + LOG.debug("gramplet updater: %s: return %s" % (self.gui.title, retval)) return retval except StopIteration: @@ -357,7 +357,7 @@ class Gramplet(object): """ from gi.repository import GObject, GLib self._pause = False - self._idle_id = GLib.idle_add(self._updater, + self._idle_id = GLib.idle_add(self._updater, priority=GObject.PRIORITY_LOW - 10) def update_all(self, *args): @@ -434,7 +434,7 @@ class Gramplet(object): signal_obj.disconnect(id) else: raise AttributeError("unknown signal: '%s'" % signal) - + def hidden_widgets(self): """ A list of widgets to keep hidden. Needed because Gramps uses diff --git a/gramps/gen/plug/_import.py b/gramps/gen/plug/_import.py index 833485bf8..d07a00fea 100644 --- a/gramps/gen/plug/_import.py +++ b/gramps/gen/plug/_import.py @@ -53,19 +53,19 @@ class ImportPlugin(Plugin): Plugin.__init__(self, name, description, import_function.__module__ ) self.__import_func = import_function self.__extension = extension - + def get_import_function(self): """ Get the import function for this plugins. - - :return: the callable import_function passed into :meth:`__init__` + + :return: the callable import_function passed into :meth:`__init__` """ return self.__import_func - + def get_extension(self): """ Get the extension for the files imported by this plugin. - + :return: str """ return self.__extension diff --git a/gramps/gen/plug/_manager.py b/gramps/gen/plug/_manager.py index e30a089ae..988613a19 100644 --- a/gramps/gen/plug/_manager.py +++ b/gramps/gen/plug/_manager.py @@ -69,7 +69,7 @@ class BasePluginManager(object): """ unique singleton storage class for a :class:`.PluginManager`. """ __instance = None - + def get_instance(): """ Use this function to get the instance of the :class:`.PluginManager` @@ -79,7 +79,7 @@ class BasePluginManager(object): BasePluginManager.__instance = BasePluginManager() return BasePluginManager.__instance get_instance = staticmethod(get_instance) - + def __init__(self): """ This function should only be run once by get_instance() """ if BasePluginManager.__instance is not 1: @@ -98,34 +98,34 @@ class BasePluginManager(object): self.__mod2text = {} self.__modules = {} - + self.__pgr = PluginRegister.get_instance() self.__registereddir_set = set() self.__loaded_plugins = {} - def reg_plugins(self, direct, dbstate=None, uistate=None, + def reg_plugins(self, direct, dbstate=None, uistate=None, load_on_reg=False): """ Searches the specified directory, and registers python plugin that - are being defined in gpr.py files. - - If a relationship calculator for env var LANG is present, it is + are being defined in gpr.py files. + + If a relationship calculator for env var LANG is present, it is immediately loaded so it is available for all. """ # if the directory does not exist, do nothing if not os.path.isdir(direct): return False # return value is True for error - + for (dirpath, dirnames, filenames) in os.walk(direct): root, subdir = os.path.split(dirpath) - if subdir.startswith("."): + if subdir.startswith("."): dirnames[:] = [] continue for dirname in dirnames: # Skip hidden and system directories: if dirname.startswith(".") or dirname in ["po", "locale"]: dirnames.remove(dirname) - # if the path has not already been loaded, save it in the + # if the path has not already been loaded, save it in the # registereddir_list list for use on reloading. self.__registereddir_set.add(dirpath) self.__pgr.scan_dir(dirpath) @@ -192,7 +192,7 @@ class BasePluginManager(object): def load_plugin(self, pdata): """ - Load a :class:`.PluginData` object. This means import of the python + Load a :class:`.PluginData` object. This means import of the python module. Plugin directories are added to sys path, so files are found """ if pdata.id in self.__loaded_plugins: @@ -219,7 +219,7 @@ class BasePluginManager(object): del self.__failmsg_list[index] else: self.__attempt_list.append(filename) - try: + try: _module = self.import_plugin(pdata) if need_reload: # For some strange reason second importing of a failed plugin @@ -285,25 +285,25 @@ class BasePluginManager(object): return module def empty_managed_plugins(self): - """ For some plugins, managed Plugin are used. These are only + """ For some plugins, managed Plugin are used. These are only reobtained from the registry if this method is called """ # TODO: do other lists need to be reset here, too? self.__import_plugins = [] self.__export_plugins = [] self.__docgen_plugins = [] - + def reload_plugins(self): """ Reload previously loaded plugins """ pymod = re.compile(r"^(.*)\.py$") - + oldfailmsg = self.__failmsg_list[:] self.__failmsg_list = [] - + # attempt to reload all plugins that have succeeded in the past self.empty_managed_plugins() self.__loaded_plugins = {} - + oldmodules = self.__modules self.__modules = {} dellist = [] @@ -316,7 +316,7 @@ class BasePluginManager(object): if filename in self.__modules: #module already reloaded, a second plugin in same module continue - try: + try: self.reload(plugin[1], pdata) self.__modules[filename] = plugin[1] self.__loaded_plugins[pdata.id] = plugin[1] @@ -327,11 +327,11 @@ class BasePluginManager(object): dellist.reverse() for index in dellist: del self.__success_list[index] - + # Remove previously good plugins that are now bad # from the registered lists self.__purge_failed() - + # attempt to load the plugins that have failed in the past for (filename, message, pdata) in oldfailmsg: self.load_plugin(pdata) @@ -357,13 +357,13 @@ class BasePluginManager(object): def get_fail_list(self): """ Return the list of failed plugins. """ return self.__failmsg_list - + def get_success_list(self): """ Return the list of succeeded plugins. """ return self.__success_list def get_plugin(self, id): - """ + """ Returns a plugin object from :class:`.PluginRegister` by id. """ return self.__pgr.get_plugin(id) @@ -374,24 +374,24 @@ class BasePluginManager(object): returned """ return self.__pgr.report_plugins(gui) - + def get_reg_tools(self, gui=True): """ Return list of registered tools :aram gui: bool indicating if GUI reports or CLI reports must be returned """ return self.__pgr.tool_plugins(gui) - + def get_reg_quick_reports(self): """ Return list of registered quick reports """ return self.__pgr.quickreport_plugins() - + def get_reg_views(self): """ Return list of registered views """ return self.__pgr.view_plugins() - + def get_reg_mapservices(self): """ Return list of registered mapservices """ @@ -401,45 +401,45 @@ class BasePluginManager(object): """ Return list of reports registered as bookitem """ return self.__pgr.bookitem_plugins() - + def get_reg_gramplets(self): """ Return list of non hidden gramplets. """ return self.__pgr.gramplet_plugins() - + def get_reg_sidebars(self): """ Return list of registered sidebars. """ return self.__pgr.sidebar_plugins() - + def get_reg_databases(self): """ Return list of registered database backends """ return self.__pgr.database_plugins() - + def get_external_opt_dict(self): """ Return the dictionary of external options. """ return self.__external_opt_dict - + def get_module_description(self, module): """ Given a module name, return the module description. """ return self.__mod2text.get(module, '') - + def get_reg_importers(self): """ Return list of registered importers """ return self.__pgr.import_plugins() - + def get_reg_exporters(self): """ Return list of registered exporters """ return self.__pgr.export_plugins() - + def get_reg_docgens(self): """ Return list of registered docgen """ return self.__pgr.docgen_plugins() - + def get_reg_general(self, category=None): """ Return list of registered general libs """ @@ -471,7 +471,7 @@ class BasePluginManager(object): except: retval.append(data) return retval - + def process_plugin_data(self, category): """ Gathers all of the data from general plugins of type category, @@ -499,11 +499,11 @@ class BasePluginManager(object): if process: return process(retval) return retval - + def get_import_plugins(self): """ Get the list of import plugins. - + :return: :class:`.ImportPlugin` (a list of ImportPlugin instances) """ ## TODO: would it not be better to remove ImportPlugin and use @@ -515,18 +515,18 @@ class BasePluginManager(object): continue mod = self.load_plugin(pdata) if mod: - imp = ImportPlugin(name=pdata.name, + imp = ImportPlugin(name=pdata.name, description = pdata.description, import_function = getattr(mod, pdata.import_function), extension = pdata.extension) self.__import_plugins.append(imp) return self.__import_plugins - + def get_export_plugins(self): """ Get the list of export plugins. - + :return: :class:`.ExportPlugin` (a list of ExportPlugin instances) """ ## TODO: would it not be better to remove ExportPlugin and use @@ -539,26 +539,26 @@ class BasePluginManager(object): mod = self.load_plugin(pdata) if mod: options = None - if (pdata.export_options and + if (pdata.export_options and hasattr(mod, pdata.export_options)): options = getattr(mod, pdata.export_options) - exp = ExportPlugin(name=pdata.name_accell, + exp = ExportPlugin(name=pdata.name_accell, description = pdata.description, export_function = getattr(mod, pdata.export_function), extension = pdata.extension, config = (pdata.export_options_title, options)) self.__export_plugins.append(exp) - + return self.__export_plugins - + def get_docgen_plugins(self): """ Get the list of docgen plugins. - + :return: :class:`.DocGenPlugin` (a list of DocGenPlugin instances) """ ## TODO: would it not be better to return list of plugindata, and only - ## import those docgen that will then actuallly be needed? + ## import those docgen that will then actuallly be needed? ## So, only do import when docgen.get_basedoc() is requested if self.__docgen_plugins == []: #The modules still need to be imported @@ -571,22 +571,22 @@ class BasePluginManager(object): oclass = None if pdata.optionclass: oclass = getattr(mod, pdata.optionclass) - dgp = DocGenPlugin(name=pdata.name, + dgp = DocGenPlugin(name=pdata.name, description = pdata.description, basedoc = getattr(mod, pdata.docclass), paper = pdata.paper, - style = pdata.style, + style = pdata.style, extension = pdata.extension, docoptclass = oclass, basedocname = pdata.docclass ) self.__docgen_plugins.append(dgp) - + return self.__docgen_plugins def get_docgen_names(self): """ Get the list of docgen plugin names. - + :return: a list of :class:`.DocGenPlugin` names """ if self.__docgen_names == []: diff --git a/gramps/gen/plug/_options.py b/gramps/gen/plug/_options.py index 67fd19c37..f30a7d671 100644 --- a/gramps/gen/plug/_options.py +++ b/gramps/gen/plug/_options.py @@ -69,7 +69,7 @@ class OptionList(object): def __init__(self): self.options = {} - + def set_options(self, options): """ Set the whole bunch of options for the OptionList. @@ -147,7 +147,7 @@ class OptionListCollection(object): def init_common(self): pass - + def get_option_list_map(self): """ Return the map of module names to option lists. @@ -180,7 +180,7 @@ class OptionListCollection(object): def set_option_list(self, name, option_list): """ - Add or replaces an option_list in the OptionListCollection. + Add or replaces an option_list in the OptionListCollection. :param name: name associated with the module to add or replace. :type name: str @@ -253,7 +253,7 @@ class OptionListCollection(object): f.write('\n') f.close() - + def parse(self): """ Loads the OptionList from the associated file, if it exists. @@ -275,7 +275,7 @@ class OptionParser(handler.ContentHandler): """ SAX parsing class for the OptionListCollection XML file. """ - + def __init__(self,collection): """ Create a OptionParser class that populates the passed collection. @@ -284,7 +284,7 @@ class OptionParser(handler.ContentHandler): """ handler.ContentHandler.__init__(self) self.collection = collection - + self.mname = None self.option_list = None self.oname = None @@ -319,7 +319,7 @@ class OptionParser(handler.ContentHandler): #------------------------------------------------------------------------- # -# Class handling options for plugins +# Class handling options for plugins # #------------------------------------------------------------------------- class OptionHandler(object): @@ -343,7 +343,7 @@ class OptionHandler(object): if self.saved_option_list: self.set_options() else: - # If nothing was found, set up the option list + # If nothing was found, set up the option list self.saved_option_list = self.list_class() self.option_list_collection.set_option_list(module_name, self.saved_option_list) @@ -360,7 +360,7 @@ class OptionHandler(object): """ Set options to be used in this plugin according to the passed options dictionary. - + Dictionary values are all strings, since they were read from XML. Here we need to convert them to the needed types. We use default values to determine the type. @@ -384,7 +384,7 @@ class OptionHandler(object): for option_name in bad_opts: option_data = options[option_name] if not ( isinstance(option_data, list) and - option_data and + option_data and option_data[0] in docgen_names ): print(_("Option '%(opt_name)s' is present in %(file)s\n" " but is not known to the module. Ignoring...") % @@ -402,7 +402,7 @@ class OptionHandler(object): def save_options(self): """ Saves options to file. - + We need to only store non-default options. Therefore, we remove all options whose values are the defaults prior to saving. """ @@ -438,7 +438,7 @@ class Options(object): """ Defines options and provides handling interface. - + This is a base Options class for the modules. All modules, options classes should derive from it. """ @@ -447,9 +447,9 @@ class Options(object): """ Initialize the class, performing usual house-keeping tasks. Subclasses MUST call this in their __init__() method. - + Modules that need custom options need to override this method. - Two dictionaries allow the addition of custom options: + Two dictionaries allow the addition of custom options: self.options_dict This is a dictionary whose keys are option names @@ -472,7 +472,7 @@ class Options(object): self.options_dict = {} self.options_help = {} self.handler = None - + def load_previous_values(self): """ Modifies all options to have the value they were last used as. @@ -485,7 +485,7 @@ class Options(object): Set up UI controls (widgets) for the options specific for this module. This method MUST be overridden by modules that define new options. - + .. note:: To really have any effect besides looking pretty, each widget set up here must be also parsed in the :meth:`parse_user_options` method below. @@ -497,11 +497,11 @@ class Options(object): Parses UI controls (widgets) for the options specific for this module. This method MUST be overridden by modules that define new options. - + After obtaining values from the widgets, they MUST be used to set the appropriate options_dict values. Otherwise the values will not have any user-visible effect. - + .. note:: Any widget parsed here MUST be defined and added to the dialog in the :meth:`add_user_options` method above. """ @@ -521,7 +521,7 @@ class MenuOptions(object): """ def __init__(self): self.menu = Menu() - + # Fill options_dict with report/tool defaults: self.options_dict = {} self.options_help = {} @@ -540,13 +540,13 @@ class MenuOptions(object): def add_menu_options(self, menu): """ Add the user defined options to the menu. - + :param menu: A menu class for the options to belong to. :type menu: Menu :return: nothing """ raise NotImplementedError - + def add_menu_option(self, category, name, option): """ Add a single option to the menu. @@ -562,7 +562,7 @@ class MenuOptions(object): for category in self.menu.get_categories(): for name in self.menu.get_option_names(category): option = self.menu.get_option(category, name) - + # override option default with xml-saved value: if name in self.options_dict: option.set_value(self.options_dict[name]) diff --git a/gramps/gen/plug/_plugin.py b/gramps/gen/plug/_plugin.py index 43f18b132..e55568f60 100644 --- a/gramps/gen/plug/_plugin.py +++ b/gramps/gen/plug/_plugin.py @@ -21,8 +21,8 @@ """ This module provides the base class for plugins. -""" - +""" + class Plugin(object): """ This class serves as a base class for all plugins that can be registered @@ -44,28 +44,28 @@ class Plugin(object): self.__name = name self.__desc = description self.__mod_name = module_name - + def get_name(self): """ Get the name of this plugin. - + :return: a string representing the name of the plugin """ return self.__name - + def get_description(self): """ Get the description of this plugin. - + :return: a string that describes the plugin """ return self.__desc - + def get_module_name(self): """ Get the name of the module that this plugin lives in. - + :return: a string representing the name of the module for this plugin """ return self.__mod_name - + diff --git a/gramps/gen/plug/_pluginreg.py b/gramps/gen/plug/_pluginreg.py index 70a93f0f2..c846f23d2 100644 --- a/gramps/gen/plug/_pluginreg.py +++ b/gramps/gen/plug/_pluginreg.py @@ -20,7 +20,7 @@ # """ -This module provides the base class for plugin registration. +This module provides the base class for plugin registration. It provides an object containing data about the plugin (version, filename, ...) and a register for the data of all plugins . """ @@ -74,16 +74,16 @@ DATABASE = 12 PTYPE = [REPORT , QUICKREPORT, TOOL, IMPORT, EXPORT, DOCGEN, GENERAL, MAPSERVICE, VIEW, RELCALC, GRAMPLET, SIDEBAR, DATABASE] PTYPE_STR = { - REPORT: _('Report') , - QUICKREPORT: _('Quickreport'), - TOOL: _('Tool'), + REPORT: _('Report') , + QUICKREPORT: _('Quickreport'), + TOOL: _('Tool'), IMPORT: _('Importer'), - EXPORT: _('Exporter'), - DOCGEN: _('Doc creator'), - GENERAL: _('Plugin lib'), - MAPSERVICE: _('Map service'), - VIEW: _('Gramps View'), - RELCALC: _('Relationships'), + EXPORT: _('Exporter'), + DOCGEN: _('Doc creator'), + GENERAL: _('Plugin lib'), + MAPSERVICE: _('Map service'), + VIEW: _('Gramps View'), + RELCALC: _('Relationships'), GRAMPLET: _('Gramplet'), SIDEBAR: _('Sidebar'), DATABASE: _('Database'), @@ -127,7 +127,7 @@ REPORT_MODE_GUI = 1 # Standalone report using GUI REPORT_MODE_BKI = 2 # Book Item interface using GUI REPORT_MODE_CLI = 4 # Command line interface (CLI) REPORT_MODES = [REPORT_MODE_GUI, REPORT_MODE_BKI, REPORT_MODE_CLI] - + # Modes for running tools TOOL_MODE_GUI = 1 # Standard tool using GUI TOOL_MODE_CLI = 2 # Command line interface (CLI) @@ -170,20 +170,20 @@ def valid_plugin_version(plugin_version_string): return plugin_version == VERSION_TUPLE[:2] elif dots == 2: plugin_version = tuple(map(int, plugin_version_string.split(".", 2))) - return (plugin_version[:2] == VERSION_TUPLE[:2] and + return (plugin_version[:2] == VERSION_TUPLE[:2] and plugin_version <= VERSION_TUPLE) return False - + class PluginData(object): """ This is the base class for all plugin data objects. - The workflow is: + The workflow is: 1. plugin manager reads all register files, and stores plugin data objects in a plugin register - 2. when plugin is needed, the plugin register creates the plugin, and + 2. when plugin is needed, the plugin register creates the plugin, and the manager stores this, after which it can be executed. - + Attributes present for all plugins .. attribute:: id @@ -192,7 +192,7 @@ class PluginData(object): .. attribute:: name A friendly name to call this plugin (normally translated) .. attribute:: name_accell - A friendly name to call this plugin (normally translated), with an + A friendly name to call this plugin (normally translated), with an accellerator present (eg '_Descendant report', with D to be accellerator key .. attribute:: description @@ -216,13 +216,13 @@ class PluginData(object): .. attribute:: supported Bool value indicating if the plugin is still supported, default=True .. attribute:: load_on_reg - bool value, if True, the plugin is loaded on GRAMPS startup. Some + bool value, if True, the plugin is loaded on GRAMPS startup. Some plugins. Only set this value if for testing you want the plugin to be loaded immediately on startup. default=False .. attribute: icons - New stock icons to register. A list of tuples (stock_id, icon_label), - eg: - [('gramps_myplugin', _('My Plugin')), + New stock icons to register. A list of tuples (stock_id, icon_label), + eg: + [('gramps_myplugin', _('My Plugin')), ('gramps_myplugin_open', _('Open Plugin')] The icon directory must contain the directories scalable, 48x48, 22x22 and 16x16 with the icons, eg: @@ -231,15 +231,15 @@ class PluginData(object): 22x22/gramps_myplugin.png .. attribute: icondir The directory to use for the icons. If icondir is not set or None, it - reverts to the plugindirectory itself. - + reverts to the plugindirectory itself. + Attributes for RELCALC plugins: - .. attribute:: relcalcclass - The class in the module that is the relationcalc class + .. attribute:: relcalcclass + The class in the module that is the relationcalc class .. attribute:: lang_list List of languages this plugin handles - + Attributes for REPORT plugins: .. attribute:: require_active @@ -248,28 +248,28 @@ class PluginData(object): The class in the module that is the report class .. attribute:: report_modes The report modes: list of REPORT_MODE_GUI ,REPORT_MODE_BKI,REPORT_MODE_CLI - + Attributes for REPORT and TOOL and QUICKREPORT and VIEW plugins .. attribute:: category Or the report category the plugin belongs to, default=CATEGORY_TEXT or the tool category a plugin belongs to, default=TOOL_UTILS or the quickreport category a plugin belongs to, default=CATEGORY_QR_PERSON - or the view category a plugin belongs to, + or the view category a plugin belongs to, default=("Miscellaneous", _("Miscellaneous")) - + Attributes for REPORT and TOOL and DOCGEN plugins .. attribute:: optionclass The class in the module that is the option class - + Attributes for TOOL plugins .. attribute:: toolclass The class in the module that is the tool class .. attribute:: tool_modes The tool modes: list of TOOL_MODE_GUI, TOOL_MODE_CLI - + Attributes for DOCGEN plugins .. attribute :: docclass @@ -278,23 +278,23 @@ class PluginData(object): bool, Indicates whether the plugin uses paper or not, default=True .. attribute :: style bool, Indicates whether the plugin uses styles or not, default=True - + Attribute for DOCGEN, EXPORT plugins .. attribute :: extension str, The file extension to use for output produced by the docgen/export, default='' - + Attributes for QUICKREPORT plugins .. attribute:: runfunc The function that executes the quick report - + Attributes for MAPSERVICE plugins .. attribute:: mapservice The class in the module that is a mapservice - + Attributes for EXPORT plugins .. attribute:: export_function @@ -303,18 +303,18 @@ class PluginData(object): Class to set options .. attribute:: export_options_title Title for the option page - + Attributes for IMPORT plugins .. attribute:: import_function Function that starts an import - + Attributes for GRAMPLET plugins .. attribute:: gramplet The function or class that defines the gramplet. .. attribute:: height - The height the gramplet should have in a column on GrampletView, + The height the gramplet should have in a column on GrampletView, default = 200 .. attribute:: detached_height The height the gramplet should have detached, default 300 @@ -343,11 +343,11 @@ class PluginData(object): The class that defines the sidebar. .. attribute:: menu_label A label to use on the seltion menu. - + Attributes for VIEW and SIDEBAR plugins .. attribute:: order - order can be START or END. Default is END. For END, on registering, + order can be START or END. Default is END. For END, on registering, the plugin is appended to the list of plugins. If START, then the plugin is prepended. Only set START if you want a plugin to be the first in the order of plugins @@ -401,7 +401,7 @@ class PluginData(object): self._tool_modes = [TOOL_MODE_GUI] #DOCGEN attr self._paper = True - self._style = True + self._style = True self._extension = '' #QUICKREPORT attr self._runfunc = None @@ -437,7 +437,7 @@ class PluginData(object): #GENERAL attr self._data = [] self._process = None - + def _set_id(self, id): self._id = id @@ -449,7 +449,7 @@ class PluginData(object): def _get_name(self): return self._name - + def _set_name_accell(self, name): self._name_accell = name @@ -484,19 +484,19 @@ class PluginData(object): def _get_status(self): return self._status - + def _set_fname(self, fname): self._fname = fname def _get_fname(self): return self._fname - + def _set_fpath(self, fpath): self._fpath = fpath def _get_fpath(self): return self._fpath - + def _set_ptype(self, ptype): if ptype not in PTYPE: raise ValueError('Plugin type cannot be %s' % str(ptype)) @@ -532,12 +532,12 @@ class PluginData(object): def _get_authors_email(self): return self._authors_email - + def _set_supported(self, supported): if not isinstance(supported, bool): raise ValueError('Plugin must have supported=True or False') self._supported = supported - + def _get_supported(self): return self._supported @@ -582,10 +582,10 @@ class PluginData(object): id = property(_get_id, _set_id) name = property(_get_name, _set_name) name_accell = property(_get_name_accell, _set_name_accell) - description = property(_get_description, _set_description) - version = property(_get_version, _set_version) - gramps_target_version = property(_get_gramps_target_version, - _set_gramps_target_version) + description = property(_get_description, _set_description) + version = property(_get_version, _set_version) + gramps_target_version = property(_get_gramps_target_version, + _set_gramps_target_version) status = property(_get_status, _set_status) fname = property(_get_fname, _set_fname) fpath = property(_get_fpath, _set_fpath) @@ -598,12 +598,12 @@ class PluginData(object): icondir = property(_get_icondir, _set_icondir) depends_on = property(_get_depends_on, _set_depends_on) include_in_listing = property(_get_include_in_listing, _set_include_in_listing) - + def statustext(self): return STATUSTEXT[self.status] - + #type specific plugin attributes - + #RELCALC attributes def _set_relcalcclass(self, relcalcclass): if not self._ptype == RELCALC: @@ -612,7 +612,7 @@ class PluginData(object): def _get_relcalcclass(self): return self._relcalcclass - + def _set_lang_list(self, lang_list): if not self._ptype == RELCALC: raise ValueError('relcalcclass may only be set for RELCALC plugins') @@ -623,7 +623,7 @@ class PluginData(object): relcalcclass = property(_get_relcalcclass, _set_relcalcclass) lang_list = property(_get_lang_list, _set_lang_list) - + #REPORT attributes def _set_require_active(self, require_active): if not self._ptype == REPORT: @@ -679,7 +679,7 @@ class PluginData(object): if not self._ptype == TOOL: raise ValueError('toolclass may only be set for TOOL plugins') self._toolclass = toolclass - + def _get_toolclass(self): return self._toolclass @@ -694,7 +694,7 @@ class PluginData(object): def _get_tool_modes(self): return self._tool_modes - + require_active = property(_get_require_active, _set_require_active) reportclass = property(_get_reportclass, _set_reportclass) report_modes = property(_get_report_modes, _set_report_modes) @@ -710,54 +710,54 @@ class PluginData(object): if not isinstance(paper, bool): raise ValueError('Plugin must have paper=True or False') self._paper = paper - + def _get_paper(self): return self._paper - + def _set_style(self, style): if not self._ptype == DOCGEN: raise ValueError('style may only be set for DOCGEN plugins') if not isinstance(style, bool): raise ValueError('Plugin must have style=True or False') self._style = style - + def _get_style(self): return self._style - + def _set_extension(self, extension): - if not (self._ptype == DOCGEN or self._ptype == EXPORT + if not (self._ptype == DOCGEN or self._ptype == EXPORT or self._ptype == IMPORT): raise ValueError('extension may only be set for DOCGEN/EXPORT/'\ 'IMPORT plugins') self._extension = extension - + def _get_extension(self): return self._extension - + paper = property(_get_paper, _set_paper) - style = property(_get_style, _set_style) + style = property(_get_style, _set_style) extension = property(_get_extension, _set_extension) - + #QUICKREPORT attributes def _set_runfunc(self, runfunc): if not self._ptype == QUICKREPORT: raise ValueError('runfunc may only be set for QUICKREPORT plugins') self._runfunc = runfunc - + def _get_runfunc(self): return self._runfunc - + runfunc = property(_get_runfunc, _set_runfunc) - + #MAPSERVICE attributes def _set_mapservice(self, mapservice): if not self._ptype == MAPSERVICE: raise ValueError('mapservice may only be set for MAPSERVICE plugins') self._mapservice = mapservice - + def _get_mapservice(self): return self._mapservice - + mapservice = property(_get_mapservice, _set_mapservice) #EXPORT attributes @@ -765,40 +765,40 @@ class PluginData(object): if not self._ptype == EXPORT: raise ValueError('export_function may only be set for EXPORT plugins') self._export_function = export_function - + def _get_export_function(self): return self._export_function - + def _set_export_options(self, export_options): if not self._ptype == EXPORT: raise ValueError('export_options may only be set for EXPORT plugins') self._export_options = export_options - + def _get_export_options(self): return self._export_options - + def _set_export_options_title(self, export_options_title): if not self._ptype == EXPORT: raise ValueError('export_options_title may only be set for EXPORT plugins') self._export_options_title = export_options_title - + def _get_export_options_title(self): return self._export_options_title export_function = property(_get_export_function, _set_export_function) export_options = property(_get_export_options, _set_export_options) - export_options_title = property(_get_export_options_title, + export_options_title = property(_get_export_options_title, _set_export_options_title) - + #IMPORT attributes def _set_import_function(self, import_function): if not self._ptype == IMPORT: raise ValueError('import_function may only be set for IMPORT plugins') self._import_function = import_function - + def _get_import_function(self): return self._import_function - + import_function = property(_get_import_function, _set_import_function) #GRAMPLET attributes @@ -806,37 +806,37 @@ class PluginData(object): if not self._ptype == GRAMPLET: raise ValueError('gramplet may only be set for GRAMPLET plugins') self._gramplet = gramplet - + def _get_gramplet(self): return self._gramplet - + def _set_height(self, height): if not self._ptype == GRAMPLET: raise ValueError('height may only be set for GRAMPLET plugins') if not isinstance(height, int): raise ValueError('Plugin must have height an integer') self._height = height - + def _get_height(self): return self._height - + def _set_detached_height(self, detached_height): if not self._ptype == GRAMPLET: raise ValueError('detached_height may only be set for GRAMPLET plugins') if not isinstance(detached_height, int): raise ValueError('Plugin must have detached_height an integer') self._detached_height = detached_height - + def _get_detached_height(self): return self._detached_height - + def _set_detached_width(self, detached_width): if not self._ptype == GRAMPLET: raise ValueError('detached_width may only be set for GRAMPLET plugins') if not isinstance(detached_width, int): raise ValueError('Plugin must have detached_width an integer') self._detached_width = detached_width - + def _get_detached_width(self): return self._detached_width @@ -846,17 +846,17 @@ class PluginData(object): if not isinstance(expand, bool): raise ValueError('Plugin must have expand as a bool') self._expand = expand - + def _get_expand(self): return self._expand - + def _set_gramplet_title(self, gramplet_title): if not self._ptype == GRAMPLET: raise ValueError('gramplet_title may only be set for GRAMPLET plugins') if not isinstance(gramplet_title, str): raise ValueError('gramplet_title is type %s, string or unicode required' % type(gramplet_title)) self._gramplet_title = gramplet_title - + def _get_gramplet_title(self): return self._gramplet_title @@ -875,7 +875,7 @@ class PluginData(object): def _get_navtypes(self): return self._navtypes - + def _set_orientation(self, orientation): if not self._ptype == GRAMPLET: raise ValueError('orientation may only be set for GRAMPLET plugins') @@ -883,7 +883,7 @@ class PluginData(object): def _get_orientation(self): return self._orientation - + gramplet = property(_get_gramplet, _set_gramplet) height = property(_get_height, _set_height) detached_height = property(_get_detached_height, _set_detached_height) @@ -901,7 +901,7 @@ class PluginData(object): def _get_viewclass(self): return self._viewclass - + def _set_stock_icon(self, stock_icon): if not self._ptype == VIEW: raise ValueError('stock_icon may only be set for VIEW plugins') @@ -909,7 +909,7 @@ class PluginData(object): def _get_stock_icon(self): return self._stock_icon - + viewclass = property(_get_viewclass, _set_viewclass) stock_icon = property(_get_stock_icon, _set_stock_icon) @@ -921,7 +921,7 @@ class PluginData(object): def _get_sidebarclass(self): return self._sidebarclass - + def _set_menu_label(self, menu_label): if not self._ptype == SIDEBAR: raise ValueError('menu_label may only be set for SIDEBAR plugins') @@ -943,7 +943,7 @@ class PluginData(object): return self._order order = property(_get_order, _set_order) - + #DATABASE attributes def _set_databaseclass(self, databaseclass): if not self._ptype == DATABASE: @@ -986,7 +986,7 @@ class PluginData(object): def newplugin(): """ - Function to create a new plugindata object, add it to list of + Function to create a new plugindata object, add it to list of registered plugins :returns: a newly created PluginData which is already part of the register @@ -999,12 +999,12 @@ def newplugin(): def register(ptype, **kwargs): """ Convenience function to register a new plugin using a dictionary as input. - The register functions will call newplugin() function, and use the - dictionary kwargs to assign data to the PluginData newplugin() created, + The register functions will call newplugin() function, and use the + dictionary kwargs to assign data to the PluginData newplugin() created, as in: plugindata.key = data :param ptype: the plugin type, one of REPORT, TOOL, ... - :param kwargs: dictionary with keys attributes of the plugin, and data + :param kwargs: dictionary with keys attributes of the plugin, and data the value :returns: a newly created PluginData which is already part of the register and which has kwargs assigned as attributes @@ -1060,10 +1060,10 @@ def make_environment(**kwargs): 'CATEGORY_QR_REPOSITORY': CATEGORY_QR_REPOSITORY, 'CATEGORY_QR_NOTE': CATEGORY_QR_NOTE, 'CATEGORY_QR_DATE': CATEGORY_QR_DATE, - 'REPORT_MODE_GUI': REPORT_MODE_GUI, - 'REPORT_MODE_BKI': REPORT_MODE_BKI, + 'REPORT_MODE_GUI': REPORT_MODE_GUI, + 'REPORT_MODE_BKI': REPORT_MODE_BKI, 'REPORT_MODE_CLI': REPORT_MODE_CLI, - 'TOOL_MODE_GUI': TOOL_MODE_GUI, + 'TOOL_MODE_GUI': TOOL_MODE_GUI, 'TOOL_MODE_CLI': TOOL_MODE_CLI, 'DATABASE': DATABASE, 'GRAMPSVERSION': GRAMPSVERSION, @@ -1087,7 +1087,7 @@ class PluginRegister(object): Bool, include stable plugins only or not. Default True """ __instance = None - + def get_instance(): """ Use this function to get the instance of the PluginRegister """ if PluginRegister.__instance is None: @@ -1095,7 +1095,7 @@ class PluginRegister(object): PluginRegister.__instance = PluginRegister() return PluginRegister.__instance get_instance = staticmethod(get_instance) - + def __init__(self): """ This function should only be run once by get_instance() """ if PluginRegister.__instance is not 1: @@ -1108,22 +1108,22 @@ class PluginRegister(object): def add_plugindata(self, plugindata): self.__plugindata.append(plugindata) - + def scan_dir(self, dir): """ The dir name will be scanned for plugin registration code, which will be loaded in :class:`PluginData` objects if they satisfy some checks. - + :returns: A list with :class:`PluginData` objects """ # if the directory does not exist, do nothing if not (os.path.isdir(dir) or os.path.islink(dir)): return [] - + ext = r".gpr.py" extlen = -len(ext) pymod = re.compile(r"^(.*)\.py$") - + for filename in os.listdir(dir): name = os.path.split(filename)[1] if not name[extlen:] == ext: @@ -1165,7 +1165,7 @@ class PluginRegister(object): {'filename' : filename}) print("".join(traceback.format_exception(*sys.exc_info()))) self.__plugindata = self.__plugindata[:lenpd] - #check if: + #check if: # 1. plugin exists, if not remove, otherwise set module name # 2. plugin not stable, if stable_only=True, remove # 3. TOOL_DEBUG only if __debug__ True @@ -1177,7 +1177,7 @@ class PluginRegister(object): if not valid_plugin_version(plugin.gramps_target_version): print(_('ERROR: Plugin file %(filename)s has a version of ' '"%(gramps_target_version)s" which is invalid for Gramps ' - '"%(gramps_version)s".' % + '"%(gramps_version)s".' % {'filename': os.path.join(dir, plugin.fname), 'gramps_version': GRAMPSVERSION, 'gramps_target_version': plugin.gramps_target_version,} @@ -1231,7 +1231,7 @@ class PluginRegister(object): """ Return a list of :class:`PluginData` that are of type ptype """ - return [self.get_plugin(id) for id in + return [self.get_plugin(id) for id in set([x.id for x in self.__plugindata if x.ptype == ptype])] def report_plugins(self, gui=True): @@ -1258,7 +1258,7 @@ class PluginRegister(object): return [x for x in self.type_plugins(TOOL) if TOOL_MODE_CLI in x.tool_modes] - + def bookitem_plugins(self): """ Return a list of REPORT :class:`PluginData` that are can be used as @@ -1297,7 +1297,7 @@ class PluginRegister(object): """ plugins = self.type_plugins(GENERAL) if category: - return [plugin for plugin in plugins + return [plugin for plugin in plugins if plugin.category == category] return plugins @@ -1324,7 +1324,7 @@ class PluginRegister(object): Return a list of :class:`PluginData` that are of type GRAMPLET """ return self.type_plugins(GRAMPLET) - + def sidebar_plugins(self): """ Return a list of :class:`PluginData` that are of type SIDEBAR @@ -1341,6 +1341,6 @@ class PluginRegister(object): """ Return a list of :class:`PluginData` that have load_on_reg == True """ - return [self.get_plugin(id) for id in - set([x.id for x in self.__plugindata + return [self.get_plugin(id) for id in + set([x.id for x in self.__plugindata if x.load_on_reg == True])] diff --git a/gramps/gen/plug/docbackend/cairobackend.py b/gramps/gen/plug/docbackend/cairobackend.py index 44baaf65a..9fc217271 100644 --- a/gramps/gen/plug/docbackend/cairobackend.py +++ b/gramps/gen/plug/docbackend/cairobackend.py @@ -59,7 +59,7 @@ class CairoBackend(DocBackend): """ Implementation for cairo docs """ - + STYLETAG_TO_PROPERTY = { DocBackend.FONTCOLOR : 'foreground', DocBackend.HIGHLIGHT : 'background', @@ -84,7 +84,7 @@ class CairoBackend(DocBackend): DocBackend.UNDERLINE : ("", ""), DocBackend.SUPERSCRIPT : ("", ""), } - + ESCAPE_FUNC = lambda x: escape def _create_xmltag(self, tagtype, value): @@ -97,7 +97,7 @@ class CairoBackend(DocBackend): if tagtype == DocBackend.FONTSIZE: #size is in thousandths of a point in pango value = str(1000 * value) - - return ('' % (self.STYLETAG_TO_PROPERTY[tagtype], - self.ESCAPE_FUNC()(value)), + + return ('' % (self.STYLETAG_TO_PROPERTY[tagtype], + self.ESCAPE_FUNC()(value)), '') diff --git a/gramps/gen/plug/docbackend/docbackend.py b/gramps/gen/plug/docbackend/docbackend.py index f10a4068f..4ea3e76fb 100644 --- a/gramps/gen/plug/docbackend/docbackend.py +++ b/gramps/gen/plug/docbackend/docbackend.py @@ -63,7 +63,7 @@ class DocBackendError(Exception): def __str__(self): return self.value - + #------------------------------------------------------------------------ # # Document Backend class @@ -72,10 +72,10 @@ class DocBackendError(Exception): class DocBackend(object): """ - Base class for text document backends. - The DocBackend manages a file to which it writes. It further knowns - enough of the file format to be able to translate between the BaseDoc API - and the file format. + Base class for text document backends. + The DocBackend manages a file to which it writes. It further knowns + enough of the file format to be able to translate between the BaseDoc API + and the file format. Specifically for text reports a translation of styled notes to the file format usage is done. """ @@ -88,7 +88,7 @@ class DocBackend(object): HIGHLIGHT = 6 SUPERSCRIPT = 7 LINK = 8 - + SUPPORTED_MARKUP = [] ESCAPE_FUNC = lambda: noescape @@ -97,7 +97,7 @@ class DocBackend(object): STYLETYPE_MAP = { } CLASSMAP = None - + #STYLETAGTABLE to store markup for write_markup associated with style tags STYLETAG_MARKUP = { BOLD : ("", ""), @@ -113,16 +113,16 @@ class DocBackend(object): """ self.__file = None self._filename = filename - + def getf(self): """ Obtain the filename on which backend writes """ return self._filename - + def setf(self, value): """ - Set the filename on which the backend writes, changing the value + Set the filename on which the backend writes, changing the value passed on initialization. Can only be done if the previous filename is not open. """ @@ -155,7 +155,7 @@ class DocBackend(object): Check to make sure filename satisfies the standards for this filetype """ pass - + def close(self): """ Closes the file that is written on. @@ -163,23 +163,23 @@ class DocBackend(object): if self.__file is None: raise IOError('No file open') self.__file.close() - self.__file = None + self.__file = None def write(self, string): """ - Write a string to the file. There is no return value. - Due to buffering, the string may not actually show up until the + Write a string to the file. There is no return value. + Due to buffering, the string may not actually show up until the :meth:`close` method is called. """ self.__file.write(string) def writelines(self, sequence): """ - Write a sequence of strings to the file. The sequence can be any - iterable object producing strings, typically a list of strings. + Write a sequence of strings to the file. The sequence can be any + iterable object producing strings, typically a list of strings. """ self.__file.writelines(sequence) - + def escape(self, preformatted=False): """ The escape func on text for this file format. @@ -189,22 +189,22 @@ class DocBackend(object): :type preformatted: bool """ return self.ESCAPE_FUNC() - - + + def find_tag_by_stag(self, s_tag): """ :param s_tag: object: assumed styledtexttag :param s_tagvalue: None/int/str: value associated with the tag - + A styled tag is type with a value. Every styled tag must be converted - to the tags used in the corresponding markup for the backend, - eg text for bold in html. These markups are stored in + to the tags used in the corresponding markup for the backend, + eg text for bold in html. These markups are stored in STYLETAG_MARKUP. They are tuples for begin and end tag. If a markup is not present yet, it is created, using the :meth:`_create_xmltag` method you can overwrite. """ tagtype = s_tag.name - + if not self.STYLETYPE_MAP or \ self.CLASSMAP != tagtype.__class__.__name__ : self.CLASSMAP == tagtype.__class__.__name__ @@ -233,7 +233,7 @@ class DocBackend(object): tag_name = "%d %d" % (typeval, int(s_tagvalue)) if not tag_name: return None - + tags = self.STYLETAG_MARKUP.get(tag_name) if tags is not None: return tags @@ -250,30 +250,30 @@ class DocBackend(object): if tagtype not in self.SUPPORTED_MARKUP: return None return ('', '') - + def add_markup_from_styled(self, text, s_tags, split='', escape=True): """ Input is plain text, output is text with markup added according to the s_tags which are assumed to be styledtexttags. - When split is given the text will be split over the value given, and + When split is given the text will be split over the value given, and tags applied in such a way that it the text can be safely splitted in pieces along split. - + :param text: str, a piece of text :param s_tags: styledtexttags that must be applied to the text - :param split: str, optional. A string along which the output can + :param split: str, optional. A string along which the output can be safely split without breaking the styling. - - As adding markup means original text must be escaped, ESCAPE_FUNC is - used. This can be used to convert the text of a styledtext to the format + + As adding markup means original text must be escaped, ESCAPE_FUNC is + used. This can be used to convert the text of a styledtext to the format needed for a document backend. Do not call this method in a report, use the :meth:`write_markup` method. - + .. note:: the algorithm is complex as it assumes mixing of tags is not allowed: eg text here not is assumed invalid as markup. If the s_tags require such a setup, what is returned is text here not - overwrite this method if this complexity is not needed. + overwrite this method if this complexity is not needed. """ if not escape: escape_func = self.ESCAPE_FUNC @@ -322,7 +322,7 @@ class DocBackend(object): #obtain new values start = start + splitpos + lensplit splitpos = text[start:pos].find(split) - + otext += self.ESCAPE_FUNC()(text[start:pos]) #write out tags for tag in tagspos[pos]: @@ -363,7 +363,7 @@ class DocBackend(object): #obtain new values start = start + splitpos + lensplit splitpos = text[start:pos].find(split) - + otext += self.ESCAPE_FUNC()(text[start:pos]) for opentag in reversed(opentags): otext += opentag[1] diff --git a/gramps/gen/plug/docgen/basedoc.py b/gramps/gen/plug/docgen/basedoc.py index ab57739f1..a3349a730 100644 --- a/gramps/gen/plug/docgen/basedoc.py +++ b/gramps/gen/plug/docgen/basedoc.py @@ -81,17 +81,17 @@ class BaseDoc(object): def set_creator(self, name): "Set the owner name" self._creator = name - + def get_creator(self): "Return the owner name" return self._creator - + def get_style_sheet(self): """ Return the :class:`.StyleSheet` of the document. """ return StyleSheet(self._style_sheet) - + def set_style_sheet(self, style_sheet): """ Set the :class:`.StyleSheet` of the document. diff --git a/gramps/gen/plug/docgen/drawdoc.py b/gramps/gen/plug/docgen/drawdoc.py index 42a59205b..6202830c9 100644 --- a/gramps/gen/plug/docgen/drawdoc.py +++ b/gramps/gen/plug/docgen/drawdoc.py @@ -93,7 +93,7 @@ class DrawDoc(object): def draw_path(self, style, path): raise NotImplementedError - + def draw_box(self, style, text, x, y, w, h, mark=None): """ :param mark: :class:`.IndexMark` to use for indexing (if supported) @@ -117,6 +117,6 @@ class DrawDoc(object): :param mark: :class:`.IndexMark` to use for indexing (if supported) """ raise NotImplementedError - + def draw_line(self, style, x1, y1, x2, y2): raise NotImplementedError diff --git a/gramps/gen/plug/docgen/fontscale.py b/gramps/gen/plug/docgen/fontscale.py index df262fd91..acb969108 100644 --- a/gramps/gen/plug/docgen/fontscale.py +++ b/gramps/gen/plug/docgen/fontscale.py @@ -279,7 +279,7 @@ def string_multiline_width(font, text): width = string_width(font, line) if width > max: max = width - return max + return max def string_trim(font, text, width, ellipses = "..."): """ diff --git a/gramps/gen/plug/docgen/fontstyle.py b/gramps/gen/plug/docgen/fontstyle.py index b81ea45c7..ebd7c7f02 100644 --- a/gramps/gen/plug/docgen/fontstyle.py +++ b/gramps/gen/plug/docgen/fontstyle.py @@ -69,7 +69,7 @@ class FontStyle(object): guarentees that the document format generator will be able implement all or any of the characteristics. """ - + def __init__(self, style=None): """ Create a new FontStyle object, accepting the default values. @@ -91,7 +91,7 @@ class FontStyle(object): self.bold = 0 self.color = (0, 0, 0) self.under = 0 - + def set(self, face=None, size=None, italic=None, bold=None, underline=None, color=None): """ diff --git a/gramps/gen/plug/docgen/graphdoc.py b/gramps/gen/plug/docgen/graphdoc.py index 09f143203..97c4b846c 100644 --- a/gramps/gen/plug/docgen/graphdoc.py +++ b/gramps/gen/plug/docgen/graphdoc.py @@ -88,7 +88,7 @@ _NOTELOC = [ { 'name' : _("Top"), 'value' : "t" }, if win(): _DOT_FOUND = search_for("dot.exe") - + if search_for("gswin32c.exe") == 1: _GS_CMD = "gswin32c.exe" elif search_for("gswin32.exe") == 1: @@ -97,12 +97,12 @@ if win(): _GS_CMD = "" else: _DOT_FOUND = search_for("dot") - + if search_for("gs") == 1: _GS_CMD = "gs" else: _GS_CMD = "" - + #------------------------------------------------------------------------------- # # GVOptions @@ -122,7 +122,7 @@ class GVOptions(): def add_menu_options(self, menu): """ Add all graph related options to the menu. - + :param menu: The menu the options should be added to. :type menu: :class:`.Menu` :return: nothing @@ -142,7 +142,7 @@ class GVOptions(): font_size = NumberOption(_("Font size"), 14, 8, 128) font_size.set_help(_("The font size, in points.")) menu.add_option(category, "font_size", font_size) - + rank_dir = EnumeratedListOption(_("Graph Direction"), "TB") for item in _RANKDIR: rank_dir.add_item(item["value"], item["name"]) @@ -157,7 +157,7 @@ class GVOptions(): "pages in the array horizontally. " "Only valid for dot and pdf via Ghostscript.")) menu.add_option(category, "h_pages", h_pages) - + v_pages = NumberOption(_("Number of Vertical Pages"), 1, 1, 25) v_pages.set_help(_("Graphviz can create very large graphs by " "spreading the graph across a rectangular " @@ -189,7 +189,7 @@ class GVOptions(): ################################ category = _("Graphviz Options") ################################ - + aspect_ratio = EnumeratedListOption(_("Aspect ratio"), "fill") for item in _RATIO: aspect_ratio.add_item(item["value"], item["name"]) @@ -243,19 +243,19 @@ class GVOptions(): ################################ category = _("Note") ################################ - - note = TextOption(_("Note to add to the graph"), + + note = TextOption(_("Note to add to the graph"), [""] ) note.set_help(_("This text will be added to the graph.")) menu.add_option(category, "note", note) - + noteloc = EnumeratedListOption(_("Note location"), 't') for i in range( 0, len(_NOTELOC) ): noteloc.add_item(_NOTELOC[i]["value"], _NOTELOC[i]["name"]) noteloc.set_help(_("Whether note will appear on top " "or bottom of the page.")) menu.add_option(category, "noteloc", noteloc) - + notesize = NumberOption(_("Note size"), 32, 8, 128) notesize.set_help(_("The size of note text, in points.")) menu.add_option(category, "notesize", notesize) @@ -284,12 +284,12 @@ class GVDoc(object): for Graphviz reports must implement this interface to be used by the report system. """ - def add_node(self, node_id, label, shape="", color="", + def add_node(self, node_id, label, shape="", color="", style="", fillcolor="", url="", htmloutput=False): """ Add a node to this graph. Nodes can be different shapes like boxes and circles. - + :param node_id: A unique identification value for this node. Example: "p55" :type node_id: string @@ -318,7 +318,7 @@ class GVDoc(object): def add_link(self, id1, id2, style="", head="", tail="", comment=""): """ Add a link between two nodes. - + :param id1: The unique identifier of the starting node. Example: "p55" :type id1: string @@ -346,7 +346,7 @@ class GVDoc(object): def start_subgraph(self, graph_id): """ Start a subgraph in this graph. - + :param id: The unique identifier of the subgraph. Example: "p55" :type id1: string @@ -379,7 +379,7 @@ class GVDocBase(BaseDoc, GVDoc): self._filename = None self._dot = BytesIO() self._paper = paper_style - + get_option_by_name = options.menu.get_option_by_name get_value = lambda name: get_option_by_name(name).get_value() @@ -403,22 +403,22 @@ class GVDocBase(BaseDoc, GVDoc): # Subtract 0.01" from the drawing area to make some room between # this area and the margin in order to compensate for different # rounding errors internally in dot - sizew = ( paper_size.get_width() - - self._paper.get_left_margin() - + sizew = ( paper_size.get_width() - + self._paper.get_left_margin() - self._paper.get_right_margin() ) / 2.54 - 0.01 - sizeh = ( paper_size.get_height() - + sizeh = ( paper_size.get_height() - self._paper.get_top_margin() - self._paper.get_bottom_margin() ) / 2.54 - 0.01 - + pheight = paper_size.get_height_inches() pwidth = paper_size.get_width_inches() - + xmargin = self._paper.get_left_margin() / 2.54 ymargin = self._paper.get_top_margin() / 2.54 - sizew *= self.hpages + sizew *= self.hpages sizeh *= self.vpages - + self.write( 'digraph GRAMPS_graph\n' '{\n' @@ -446,10 +446,10 @@ class GVDocBase(BaseDoc, GVDoc): ' edge [len=0.5 style=solid fontsize=%d];\n' % self.fontsize ) if self.fontfamily: - self.write( ' node [style=filled fontname="%s" fontsize=%d];\n' + self.write( ' node [style=filled fontname="%s" fontsize=%d];\n' % ( self.fontfamily, self.fontsize ) ) else: - self.write( ' node [style=filled fontsize=%d];\n' + self.write( ' node [style=filled fontsize=%d];\n' % self.fontsize ) self.write( '\n' ) @@ -487,22 +487,22 @@ class GVDocBase(BaseDoc, GVDoc): self.write( '}\n\n' ) - def add_node(self, node_id, label, shape="", color="", + def add_node(self, node_id, label, shape="", color="", style="", fillcolor="", url="", htmloutput=False): """ Add a node to this graph. Nodes can be different shapes like boxes and circles. - + Implements GVDocBase.add_node(). """ text = '[' if shape: text += ' shape="%s"' % shape - + if color: text += ' color="%s"' % color - + if fillcolor: text += ' fillcolor="%s"' % fillcolor @@ -526,11 +526,11 @@ class GVDocBase(BaseDoc, GVDoc): def add_link(self, id1, id2, style="", head="", tail="", comment=""): """ Add a link between two nodes. - + Implements GVDocBase.add_link(). """ self.write(' %s -> %s' % (id1, id2)) - + if style or head or tail: self.write(' [') @@ -549,7 +549,7 @@ class GVDocBase(BaseDoc, GVDoc): if tail: self.write(' dir=back') else: - self.write(' dir=none') + self.write(' dir=none') self.write(' ]') self.write(';') @@ -562,7 +562,7 @@ class GVDocBase(BaseDoc, GVDoc): def add_comment(self, comment): """ Add a comment. - + Implements GVDocBase.add_comment(). """ tmp = comment.split('\n') @@ -582,7 +582,7 @@ class GVDocBase(BaseDoc, GVDoc): ' {\n' + ' style="invis";\n' # no border around subgraph (#0002176) ) - + def end_subgraph(self): """ Implement GVDocBase.end_subgraph() """ self.write(' }\n') @@ -594,11 +594,11 @@ class GVDocBase(BaseDoc, GVDoc): #------------------------------------------------------------------------------- class GVDotDoc(GVDocBase): """ GVDoc implementation that generates a .gv text file. """ - + def close(self): """ Implements GVDotDoc.close() """ GVDocBase.close(self) - + # Make sure the extension is correct if self._filename[-3:] != ".gv": self._filename += ".gv" @@ -614,9 +614,9 @@ class GVDotDoc(GVDocBase): #------------------------------------------------------------------------------- class GVPsDoc(GVDocBase): """ GVDoc implementation that generates a .ps file using Graphviz. """ - + def __init__(self, options, paper_style): - # DPI must always be 72 for PDF. + # DPI must always be 72 for PDF. # GV documentation says dpi is only for image formats. options.menu.get_option_by_name('dpi').set_value(72) GVDocBase.__init__(self, options, paper_style) @@ -627,11 +627,11 @@ class GVPsDoc(GVDocBase): options.menu.get_option_by_name('v_pages').set_value(1) options.menu.get_option_by_name('h_pages').set_value(1) GVDocBase.__init__(self, options, paper_style) - + def close(self): """ Implements GVPsDoc.close() """ GVDocBase.close(self) - + # Make sure the extension is correct if self._filename[-3:] != ".ps": self._filename += ".ps" @@ -641,7 +641,7 @@ class GVPsDoc(GVDocBase): dotfile = os.fdopen(handle, "wb") dotfile.write(self._dot.getvalue()) dotfile.close() - + # Generate the PS file. # Reason for using -Tps:cairo. Needed for Non Latin-1 letters # Some testing with Tps:cairo. Non Latin-1 letters are OK i all cases: @@ -649,8 +649,8 @@ class GVPsDoc(GVDocBase): # Single page OK OK OK # Multip page 1 page, OK 1 page, # corrupted set by gramps - # If I take a correct multip page PDF and convert it with pdf2ps I get - # multip pages, but the output is clipped, some margins have + # If I take a correct multip page PDF and convert it with pdf2ps I get + # multip pages, but the output is clipped, some margins have # disappeared. I used 1 inch margins always. # See bug tracker issue 2815 # :cairo does not work with Graphviz 2.26.3 and later See issue 4164 @@ -680,11 +680,11 @@ class GVSvgDoc(GVDocBase): options.menu.get_option_by_name('v_pages').set_value(1) options.menu.get_option_by_name('h_pages').set_value(1) GVDocBase.__init__(self, options, paper_style) - + def close(self): """ Implements GVSvgDoc.close() """ GVDocBase.close(self) - + # Make sure the extension is correct if self._filename[-4:] != ".svg": self._filename += ".svg" @@ -696,10 +696,10 @@ class GVSvgDoc(GVDocBase): dotfile.close() # Generate the SVG file. os.system( 'dot -Tsvg:cairo -o"%s" "%s"' % (self._filename, tmp_dot) ) - + # Delete the temporary dot file os.remove(tmp_dot) - + #------------------------------------------------------------------------------- # # GVSvgzDoc @@ -714,11 +714,11 @@ class GVSvgzDoc(GVDocBase): options.menu.get_option_by_name('v_pages').set_value(1) options.menu.get_option_by_name('h_pages').set_value(1) GVDocBase.__init__(self, options, paper_style) - + def close(self): """ Implements GVSvgzDoc.close() """ GVDocBase.close(self) - + # Make sure the extension is correct if self._filename[-5:] != ".svgz": self._filename += ".svgz" @@ -730,7 +730,7 @@ class GVSvgzDoc(GVDocBase): dotfile.close() # Generate the SVGZ file. os.system( 'dot -Tsvgz -o"%s" "%s"' % (self._filename, tmp_dot) ) - + # Delete the temporary dot file os.remove(tmp_dot) @@ -748,11 +748,11 @@ class GVPngDoc(GVDocBase): options.menu.get_option_by_name('v_pages').set_value(1) options.menu.get_option_by_name('h_pages').set_value(1) GVDocBase.__init__(self, options, paper_style) - + def close(self): """ Implements GVPngDoc.close() """ GVDocBase.close(self) - + # Make sure the extension is correct if self._filename[-4:] != ".png": self._filename += ".png" @@ -764,7 +764,7 @@ class GVPngDoc(GVDocBase): dotfile.close() # Generate the PNG file. os.system( 'dot -Tpng -o"%s" "%s"' % (self._filename, tmp_dot) ) - + # Delete the temporary dot file os.remove(tmp_dot) @@ -782,11 +782,11 @@ class GVJpegDoc(GVDocBase): options.menu.get_option_by_name('v_pages').set_value(1) options.menu.get_option_by_name('h_pages').set_value(1) GVDocBase.__init__(self, options, paper_style) - + def close(self): """ Implements GVJpegDoc.close() """ GVDocBase.close(self) - + # Make sure the extension is correct if self._filename[-4:] != ".jpg": self._filename += ".jpg" @@ -816,11 +816,11 @@ class GVGifDoc(GVDocBase): options.menu.get_option_by_name('v_pages').set_value(1) options.menu.get_option_by_name('h_pages').set_value(1) GVDocBase.__init__(self, options, paper_style) - + def close(self): """ Implements GVGifDoc.close() """ GVDocBase.close(self) - + # Make sure the extension is correct if self._filename[-4:] != ".gif": self._filename += ".gif" @@ -832,7 +832,7 @@ class GVGifDoc(GVDocBase): dotfile.close() # Generate the GIF file. os.system( 'dot -Tgif -o"%s" "%s"' % (self._filename, tmp_dot) ) - + # Delete the temporary dot file os.remove(tmp_dot) @@ -843,9 +843,9 @@ class GVGifDoc(GVDocBase): #------------------------------------------------------------------------------- class GVPdfGvDoc(GVDocBase): """ GVDoc implementation that generates a .pdf file using Graphviz. """ - + def __init__(self, options, paper_style): - # DPI must always be 72 for PDF. + # DPI must always be 72 for PDF. # GV documentation says dpi is only for image formats. options.menu.get_option_by_name('dpi').set_value(72) # GV documentation allow multiple pages only for ps format, @@ -853,11 +853,11 @@ class GVPdfGvDoc(GVDocBase): options.menu.get_option_by_name('v_pages').set_value(1) options.menu.get_option_by_name('h_pages').set_value(1) GVDocBase.__init__(self, options, paper_style) - + def close(self): """ Implements GVPdfGvDoc.close() """ GVDocBase.close(self) - + # Make sure the extension is correct if self._filename[-4:] != ".pdf": self._filename += ".pdf" @@ -871,7 +871,7 @@ class GVPdfGvDoc(GVDocBase): # Generate the PDF file. os.system( 'dot -Tpdf -o"%s" "%s"' % (fname, tmp_dot) ) - + # Delete the temporary dot file os.remove(tmp_dot) @@ -883,15 +883,15 @@ class GVPdfGvDoc(GVDocBase): class GVPdfGsDoc(GVDocBase): """ GVDoc implementation that generates a .pdf file using Ghostscript. """ def __init__(self, options, paper_style): - # DPI must always be 72 for PDF. + # DPI must always be 72 for PDF. # GV documentation says dpi is only for image formats. options.menu.get_option_by_name('dpi').set_value(72) GVDocBase.__init__(self, options, paper_style) - + def close(self): """ Implements GVPdfGsDoc.close() """ GVDocBase.close(self) - + # Make sure the extension is correct if self._filename[-4:] != ".pdf": self._filename += ".pdf" @@ -901,36 +901,36 @@ class GVPdfGsDoc(GVDocBase): dotfile = os.fdopen(handle, "wb") dotfile.write(self._dot.getvalue()) dotfile.close() - + # Create a temporary PostScript file (handle, tmp_ps) = tempfile.mkstemp(".ps" ) os.close( handle ) - + # Generate PostScript using dot # Reason for using -Tps:cairo. Needed for Non Latin-1 letters # See bug tracker issue 2815 # :cairo does not work with Graphviz 2.26.3 and later See issue 4164 - + command = 'dot -Tps:cairo -o"%s" "%s"' % ( tmp_ps, tmp_dot ) dotversion = str(Popen(['dot', '-V'], stderr=PIPE).communicate(input=None)[1]) - # Problem with dot 2.26.3 and later and multiple pages, which gives "cairo: out - # of memory". If the :cairo is skipped for these cases it gives + # Problem with dot 2.26.3 and later and multiple pages, which gives "cairo: out + # of memory". If the :cairo is skipped for these cases it gives # acceptable result. if (dotversion.find('2.26.3') or dotversion.find('2.28.0') != -1) and (self.vpages * self.hpages) > 1: command = command.replace(':cairo','') os.system(command) - + # Add .5 to remove rounding errors. paper_size = self._paper.get_size() width_pt = int( (paper_size.get_width_inches() * 72) + 0.5 ) height_pt = int( (paper_size.get_height_inches() * 72) + 0.5 ) - + # Convert to PDF using ghostscript command = '%s -q -sDEVICE=pdfwrite -dNOPAUSE -dDEVICEWIDTHPOINTS=%d' \ ' -dDEVICEHEIGHTPOINTS=%d -sOutputFile="%s" "%s" -c quit' \ % ( _GS_CMD, width_pt, height_pt, self._filename, tmp_ps ) os.system(command) - + os.remove(tmp_ps) os.remove(tmp_dot) @@ -942,58 +942,58 @@ class GVPdfGsDoc(GVDocBase): FORMATS = [] if _DOT_FOUND: - + if _GS_CMD != "": FORMATS += [{ 'type' : "gspdf", 'ext' : "pdf", - 'descr': _("PDF (Ghostscript)"), - 'mime' : "application/pdf", + 'descr': _("PDF (Ghostscript)"), + 'mime' : "application/pdf", 'class': GVPdfGsDoc }] - + FORMATS += [{ 'type' : "gvpdf", 'ext' : "pdf", - 'descr': _("PDF (Graphviz)"), - 'mime' : "application/pdf", + 'descr': _("PDF (Graphviz)"), + 'mime' : "application/pdf", 'class': GVPdfGvDoc }] - + FORMATS += [{ 'type' : "ps", 'ext' : "ps", - 'descr': _("PostScript"), - 'mime' : "application/postscript", + 'descr': _("PostScript"), + 'mime' : "application/postscript", 'class': GVPsDoc }] - + FORMATS += [{ 'type' : "svg", 'ext' : "svg", - 'descr': _("Structured Vector Graphics (SVG)"), - 'mime' : "image/svg", + 'descr': _("Structured Vector Graphics (SVG)"), + 'mime' : "image/svg", 'class': GVSvgDoc }] - + FORMATS += [{ 'type' : "svgz", 'ext' : "svgz", - 'descr': _("Compressed Structured Vector Graphs (SVGZ)"), - 'mime' : "image/svgz", + 'descr': _("Compressed Structured Vector Graphs (SVGZ)"), + 'mime' : "image/svgz", 'class': GVSvgzDoc }] - + FORMATS += [{ 'type' : "jpg", 'ext' : "jpg", - 'descr': _("JPEG image"), - 'mime' : "image/jpeg", + 'descr': _("JPEG image"), + 'mime' : "image/jpeg", 'class': GVJpegDoc }] - + FORMATS += [{ 'type' : "gif", 'ext' : "gif", - 'descr': _("GIF image"), - 'mime' : "image/gif", + 'descr': _("GIF image"), + 'mime' : "image/gif", 'class': GVGifDoc }] - + FORMATS += [{ 'type' : "png", 'ext' : "png", - 'descr': _("PNG image"), - 'mime' : "image/png", + 'descr': _("PNG image"), + 'mime' : "image/png", 'class': GVPngDoc }] FORMATS += [{ 'type' : "dot", 'ext' : "gv", - 'descr': _("Graphviz File"), - 'mime' : "text/x-graphviz", + 'descr': _("Graphviz File"), + 'mime' : "text/x-graphviz", 'class': GVDotDoc }] diff --git a/gramps/gen/plug/docgen/graphicstyle.py b/gramps/gen/plug/docgen/graphicstyle.py index bc795e100..5dc35dfba 100644 --- a/gramps/gen/plug/docgen/graphicstyle.py +++ b/gramps/gen/plug/docgen/graphicstyle.py @@ -137,7 +137,7 @@ class GraphicsStyle(object): return line_style_names[val] else: return line_style_names[0] - + def set_paragraph_style(self, val): self.para_name = val diff --git a/gramps/gen/plug/docgen/paperstyle.py b/gramps/gen/plug/docgen/paperstyle.py index 952273c35..23c162e29 100644 --- a/gramps/gen/plug/docgen/paperstyle.py +++ b/gramps/gen/plug/docgen/paperstyle.py @@ -145,42 +145,42 @@ class PaperStyle(object): self.__rmargin = rmargin self.__tmargin = tmargin self.__bmargin = bmargin - + def get_size(self): """ Return the size of the paper. :returns: object indicating the paper size :rtype: :class:`.PaperSize` - + """ return self.__size - + def get_orientation(self): """ Return the orientation of the page. :returns: PAPER_PORTRIAT or PAPER_LANDSCAPE :rtype: int - + """ return self.__orientation - + def get_usable_width(self): """ Return the width of the page area in centimeters. - + The value is the page width less the margins. - + """ return self.__size.get_width() - (self.__rmargin + self.__lmargin) def get_usable_height(self): """ Return the height of the page area in centimeters. - + The value is the page height less the margins. - + """ return self.__size.get_height() - (self.__tmargin + self.__bmargin) @@ -190,7 +190,7 @@ class PaperStyle(object): :returns: Right margin in centimeters :rtype: float - + """ return self.__rmargin @@ -200,7 +200,7 @@ class PaperStyle(object): :returns: Left margin in centimeters :rtype: float - + """ return self.__lmargin @@ -210,7 +210,7 @@ class PaperStyle(object): :returns: Top margin in centimeters :rtype: float - + """ return self.__tmargin @@ -220,6 +220,6 @@ class PaperStyle(object): :returns: Bottom margin in centimeters :rtype: float - + """ return self.__bmargin diff --git a/gramps/gen/plug/docgen/paragraphstyle.py b/gramps/gen/plug/docgen/paragraphstyle.py index 2a4952597..7e767777e 100644 --- a/gramps/gen/plug/docgen/paragraphstyle.py +++ b/gramps/gen/plug/docgen/paragraphstyle.py @@ -49,7 +49,7 @@ log = logging.getLogger(".paragraphstyle") # #------------------------------------------------------------------------- PARA_ALIGN_CENTER = 0 -PARA_ALIGN_LEFT = 1 +PARA_ALIGN_LEFT = 1 PARA_ALIGN_RIGHT = 2 PARA_ALIGN_JUSTIFY = 3 @@ -165,7 +165,7 @@ class ParagraphStyle(object): self.set_top_margin(tmargin) if bmargin is not None: self.set_bottom_margin(bmargin) - + def set_header_level(self, level): """ Set the header level for the paragraph. This is useful for diff --git a/gramps/gen/plug/docgen/stylesheet.py b/gramps/gen/plug/docgen/stylesheet.py index eaf282adf..754a7b8af 100644 --- a/gramps/gen/plug/docgen/stylesheet.py +++ b/gramps/gen/plug/docgen/stylesheet.py @@ -89,7 +89,7 @@ class StyleSheetList(object): has a predefined default style specified by the report. Additional styles are loaded from a specified XML file if it exists. """ - + def __init__(self, filename, defstyle): """ Create a new StyleSheetList from the specified default style and @@ -149,7 +149,7 @@ class StyleSheetList(object): xml_file = open(self.__file, "w") xml_file.write('\n') xml_file.write('\n') - + for name in sorted(self.map.keys()): # enable diff of archived copies if name == "default": continue @@ -214,7 +214,7 @@ class StyleSheetList(object): '/>\n' + '\n' ) - + def write_table_style(self, xml_file, sheet, t_name): t_style = sheet.get_table_style(t_name) @@ -280,7 +280,7 @@ class StyleSheetList(object): the_file.close() except (IOError, OSError, SAXParseException): pass - + #------------------------------------------------------------------------ # # StyleSheet @@ -290,7 +290,7 @@ class StyleSheet(object): """ A collection of named paragraph styles. """ - + def __init__(self, obj=None): """ Create a new empty StyleSheet. @@ -316,7 +316,7 @@ class StyleSheet(object): def set_name(self, name): """ Set the name of the StyleSheet - + :param name: The name to be given to the StyleSheet """ self.name = name @@ -333,7 +333,7 @@ class StyleSheet(object): self.draw_styles = {} self.table_styles = {} self.cell_styles = {} - + def is_empty(self): "Checks if any styles are defined" style_count = len(self.para_styles) + \ @@ -343,7 +343,7 @@ class StyleSheet(object): if style_count > 0: return False else: - return True + return True def add_paragraph_style(self, name, style): """ @@ -353,7 +353,7 @@ class StyleSheet(object): :param style: :class:`.ParagraphStyle` instance to be added. """ self.para_styles[name] = ParagraphStyle(style) - + def get_paragraph_style(self, name): """ Return the :class:`.ParagraphStyle` associated with the name @@ -374,7 +374,7 @@ class StyleSheet(object): :param style: :class:`.GraphicsStyle` instance to be added. """ self.draw_styles[name] = GraphicsStyle(style) - + def get_draw_style(self, name): """ Return the :class:`.GraphicsStyle` associated with the name @@ -386,7 +386,7 @@ class StyleSheet(object): def get_draw_style_names(self): "Return the list of draw style names in the StyleSheet" return list(self.draw_styles.keys()) - + def add_table_style(self, name, style): """ Add a table style to the style sheet. @@ -395,7 +395,7 @@ class StyleSheet(object): :param style: :class:`.TableStyle` instance to be added. """ self.table_styles[name] = TableStyle(style) - + def get_table_style(self, name): """ Return the :class:`.TableStyle` associated with the name @@ -407,7 +407,7 @@ class StyleSheet(object): def get_table_style_names(self): "Return the list of table style names in the StyleSheet" return list(self.table_styles.keys()) - + def add_cell_style(self, name, style): """ Add a cell style to the style sheet. @@ -416,7 +416,7 @@ class StyleSheet(object): :param style: :class:`.TableCellStyle` instance to be added. """ self.cell_styles[name] = TableCellStyle(style) - + def get_cell_style(self, name): """ Return the :class:`.TableCellStyle` associated with the name @@ -438,7 +438,7 @@ class SheetParser(handler.ContentHandler): """ SAX parsing class for the StyleSheetList XML file. """ - + def __init__(self, sheetlist): """ Create a SheetParser class that populates the passed StyleSheetList @@ -455,7 +455,7 @@ class SheetParser(handler.ContentHandler): self.columns_widths = [] self.sheet_name = None self.style_name = None - + def startElement(self, tag, attrs): """ Overridden class that handles the start of a XML element diff --git a/gramps/gen/plug/docgen/tablestyle.py b/gramps/gen/plug/docgen/tablestyle.py index 47643ea91..1d836b061 100644 --- a/gramps/gen/plug/docgen/tablestyle.py +++ b/gramps/gen/plug/docgen/tablestyle.py @@ -97,7 +97,7 @@ class TableStyle(object): """ Return the number of columns """ - return self.columns + return self.columns def set_column_widths(self, clist): """ @@ -158,7 +158,7 @@ class TableCellStyle(object): self.bborder = 0 self.padding = 0 self.longlist = 0 - + def set_padding(self, val): "Return the cell padding in centimeters" self.padding = val diff --git a/gramps/gen/plug/docgen/textdoc.py b/gramps/gen/plug/docgen/textdoc.py index 9f0f85ee9..cd8ade456 100644 --- a/gramps/gen/plug/docgen/textdoc.py +++ b/gramps/gen/plug/docgen/textdoc.py @@ -86,11 +86,11 @@ class IndexMark(object): # TextDoc # #------------------------------------------------------------------------ - + class TextDoc(object): """ Abstract Interface for text document generators. Output formats for - text reports must implement this interface to be used by the report + text reports must implement this interface to be used by the report system. """ def page_break(self): @@ -178,14 +178,14 @@ class TextDoc(object): :param links: make URLs in the text clickable (if supported) """ raise NotImplementedError - + def write_markup(self, text, s_tags, mark=None): """ Writes the text in the current paragraph. Should only be used after a start_paragraph and before an end_paragraph. Not all backends support s_tags, then the same happens as with write_text. Backends supporting - write_markup will overwrite this method - + write_markup will overwrite this method + :param text: text to write. The text is assumed to be _not_ escaped :param s_tags: assumed to be list of styledtexttags to apply to the text @@ -195,11 +195,11 @@ class TextDoc(object): def write_note(self, text, format, style_name): """ - Writes the note's text and take care of paragraphs, - depending on the format. + Writes the note's text and take care of paragraphs, + depending on the format. :param text: text to write. - :param format: format to use for writing. True for flowed text, + :param format: format to use for writing. True for flowed text, 1 for preformatted text. """ raise NotImplementedError @@ -207,23 +207,23 @@ class TextDoc(object): def write_styled_note(self, styledtext, format, style_name, contains_html=False, links=False): """ - Convenience function to write a styledtext to the cairo doc. + Convenience function to write a styledtext to the cairo doc. :param styledtext: assumed a :class:`.StyledText` object to write :param format: 0 = Flowed, 1 = Preformatted :param style_name: name of the style to use for default presentation :param contains_html: - bool, the backend should not check if html is present. - If contains_html=True, then the textdoc is free to handle that in + bool, the backend should not check if html is present. + If contains_html=True, then the textdoc is free to handle that in some way. Eg, a textdoc could remove all tags, or could make sure - a link is clickable. + a link is clickable. :param links: bool, make URLs in the text clickable (if supported) - + overwrite this method if the backend supports styled notes """ text = str(styledtext) self.write_note(text, format, style_name) - + def write_text_citation(self, text, mark=None, links=None): """ Method to write text with Gramps citation marks. @@ -270,7 +270,7 @@ class TextDoc(object): :param crop: image cropping parameters """ raise NotImplementedError - + def start_link(self, link): """ Start a link section. This defaults to underlining. @@ -303,14 +303,14 @@ class TextDoc(object): def insert_toc(self): """ - Insert a Table of Contents at this point in the document. This passes + Insert a Table of Contents at this point in the document. This passes without error so that docgen types are not required to have this. """ pass def insert_index(self): """ - Insert an Alphabetical Index at this point in the document. This passes + Insert an Alphabetical Index at this point in the document. This passes without error so that docgen types are not required to have this. """ pass diff --git a/gramps/gen/plug/menu/_booleanlist.py b/gramps/gen/plug/menu/_booleanlist.py index 90f338cd7..5b25aa29a 100644 --- a/gramps/gen/plug/menu/_booleanlist.py +++ b/gramps/gen/plug/menu/_booleanlist.py @@ -51,7 +51,7 @@ class BooleanListOption(Option): def add_button(self, description, default): """ Add a check button to the list. - + :param description: A description for this check button. Example: "Census" :type description: string @@ -67,22 +67,22 @@ class BooleanListOption(Option): else: value = value + ',' + str(default) self.set_value(value) - + def get_descriptions(self): """ Get a list of check button descriptions for this option. - + :return: a list of check button descriptions. """ return self.__descriptions - + def get_selected(self): """ Get a list of descriptions where the check button is selected. - + :return: a list of check button descriptions. """ descriptions = self.__descriptions values = self.get_value().split(',') return [x[0] for x in zip(descriptions, values) if x[1] == 'True'] - + diff --git a/gramps/gen/plug/menu/_destination.py b/gramps/gen/plug/menu/_destination.py index 710a1483a..200632d84 100644 --- a/gramps/gen/plug/menu/_destination.py +++ b/gramps/gen/plug/menu/_destination.py @@ -41,9 +41,9 @@ class DestinationOption(StringOption): The destination can be a directory or a file. If the destination is a file, the extension can be specified. """ - + __signals__ = { 'options-changed' : None } - + def __init__(self, label, value): """ :param label: A friendly label to be applied to this option. @@ -53,7 +53,7 @@ class DestinationOption(StringOption): Example: "/home/username/Desktop/" Example: "/home/username/Desktop/report.pdf" :type value: string - :param is_directory: Specifies whether the destination is a directory + :param is_directory: Specifies whether the destination is a directory or a file. :type is_directory: bool :return: nothing @@ -61,10 +61,10 @@ class DestinationOption(StringOption): StringOption.__init__(self, label, value) self.__is_directory = False self.__extension = "" - + def set_directory_entry(self, is_directory): """ - :param is_directory: Specifies whether the destination is a directory + :param is_directory: Specifies whether the destination is a directory or a file. :type is_directory: bool :return: nothing @@ -82,12 +82,12 @@ class DestinationOption(StringOption): def set_extension(self, extension): """ - :param extension: Specifies the extension for the destination file. + :param extension: Specifies the extension for the destination file. :type extension: str :return: nothing """ self.__extension = extension - + def get_extension(self): """ :return: The extension for the destination file. diff --git a/gramps/gen/plug/menu/_enumeratedlist.py b/gramps/gen/plug/menu/_enumeratedlist.py index 4a5e6621c..7798a84c8 100644 --- a/gramps/gen/plug/menu/_enumeratedlist.py +++ b/gramps/gen/plug/menu/_enumeratedlist.py @@ -49,9 +49,9 @@ class EnumeratedListOption(Option): This class describes an option that provides a finite number of values. Each possible value is assigned a value and a description. """ - + __signals__ = { 'options-changed' : None } - + def __init__(self, label, value): """ :param label: A friendly label to be applied to this option. @@ -68,7 +68,7 @@ class EnumeratedListOption(Option): def add_item(self, value, description): """ Add an item to the list of possible values. - + :param value: The value that corresponds to this item. Example: 5 :type value: int @@ -79,11 +79,11 @@ class EnumeratedListOption(Option): """ self.__items.append((value, description)) self.emit('options-changed') - + def set_items(self, items): """ Add a list of items to the list of possible values. - + :param items: A list of tuples containing value, description pairs. Example: [ (5,"8.5 x 11"), (6,"11 x 17")] :type items: array @@ -91,28 +91,28 @@ class EnumeratedListOption(Option): """ self.__items = items self.emit('options-changed') - + def get_items(self): """ Get all the possible values for this option. - + :return: an array of tuples containing (value,description) pairs. """ return self.__items - + def clear(self): """ Clear all possible values from this option. - + :return: nothing. """ self.__items = [] self.emit('options-changed') - + def set_value(self, value): """ Set the value of this option. - + :param value: A value for this option. Example: True :type value: The type will depend on the type of option. diff --git a/gramps/gen/plug/menu/_family.py b/gramps/gen/plug/menu/_family.py index 0dc1c4780..96f96130d 100644 --- a/gramps/gen/plug/menu/_family.py +++ b/gramps/gen/plug/menu/_family.py @@ -37,7 +37,7 @@ from . import StringOption #------------------------------------------------------------------------- class FamilyOption(StringOption): """ - This class describes an option that allows a family from the + This class describes an option that allows a family from the database to be selected. """ def __init__(self, label): diff --git a/gramps/gen/plug/menu/_filter.py b/gramps/gen/plug/menu/_filter.py index 4365f6099..992406e2c 100644 --- a/gramps/gen/plug/menu/_filter.py +++ b/gramps/gen/plug/menu/_filter.py @@ -52,29 +52,29 @@ class FilterOption(EnumeratedListOption): """ EnumeratedListOption.__init__(self, label, value) self.__filters = [] - + def set_filters(self, filter_list): """ Set the list of filters available to be chosen from. - + :param filter_list: An array of person filters. :type filter_list: array :return: nothing """ curval = self.get_value() - items = [(value, filt.get_name()) + items = [(value, filt.get_name()) for value, filt in enumerate(filter_list)] - + self.__filters = filter_list self.clear() self.set_items( items ) - + self.set_value(curval) - + def get_filter(self): """ Return the currently selected filter object. - + :return: A filter object. """ return self.__filters[self.get_value()] diff --git a/gramps/gen/plug/menu/_media.py b/gramps/gen/plug/menu/_media.py index 0fb1fb860..fdcfc42f9 100644 --- a/gramps/gen/plug/menu/_media.py +++ b/gramps/gen/plug/menu/_media.py @@ -37,7 +37,7 @@ from . import StringOption #------------------------------------------------------------------------- class MediaOption(StringOption): """ - This class describes an option that allows a media object from the + This class describes an option that allows a media object from the database to be selected. """ def __init__(self, label): diff --git a/gramps/gen/plug/menu/_menu.py b/gramps/gen/plug/menu/_menu.py index 0a13c2b1f..001a841e8 100644 --- a/gramps/gen/plug/menu/_menu.py +++ b/gramps/gen/plug/menu/_menu.py @@ -32,11 +32,11 @@ class Menu(object): """ **Introduction** - A Menu is used to maintain a collection of options that need to be + A Menu is used to maintain a collection of options that need to be represented to the user in a non-implementation specific way. The options can be described using the various option classes. A menu contains many options and associates them with a unique name and category. - + **Usage** Menus are used in the following way. @@ -45,7 +45,7 @@ class Menu(object): 2. Add the option to the menu by specifying the option, name and category. 3. Add as many options as necessary. 4. When all the options are added, the menu can be stored and passed to - the part of the system that will actually represent the menu to + the part of the system that will actually represent the menu to the user. """ def __init__(self): @@ -53,13 +53,13 @@ class Menu(object): self.__options = {} # __categories holds the order of all categories self.__categories = [] - + def add_option(self, category, name, option): """ Add an option to the menu. - - :param category: A label that describes the category that the option - belongs to. + + :param category: A label that describes the category that the option + belongs to. Example: "Report Options" :type category: string :param name: A name that is unique to this option. @@ -73,41 +73,41 @@ class Menu(object): self.__categories.append(category) self.__options[category] = [] self.__options[category].append((name, option)) - + def get_categories(self): """ Get a list of categories in this menu. - + :return: a list of strings """ return self.__categories - + def get_option_names(self, category): """ Get a list of option names for the specified category. - + :return: a list of strings """ names = [] for (name, option) in self.__options[category]: names.append(name) return names - + def get_option(self, category, name): """ Get an option with the specified category and name. - + :return: an :class:`.Option` instance or None on failure. """ for (oname, option) in self.__options[category]: if oname == name: return option return None - + def get_all_option_names(self): """ Get a list of all the option names in this menu. - + :return: a list of strings """ names = [] @@ -115,11 +115,11 @@ class Menu(object): for (name, option) in self.__options[category]: names.append(name) return names - + def get_option_by_name(self, name): """ Get an option with the specified name. - + :return: an :class:`.Option` instance or None on failure. """ for category in self.__options: diff --git a/gramps/gen/plug/menu/_note.py b/gramps/gen/plug/menu/_note.py index 68000f6a5..a9827fb32 100644 --- a/gramps/gen/plug/menu/_note.py +++ b/gramps/gen/plug/menu/_note.py @@ -37,7 +37,7 @@ from . import StringOption #------------------------------------------------------------------------- class NoteOption(StringOption): """ - This class describes an option that allows a note from the + This class describes an option that allows a note from the database to be selected. """ def __init__(self, label): diff --git a/gramps/gen/plug/menu/_number.py b/gramps/gen/plug/menu/_number.py index 4732c86b9..d925fbf41 100644 --- a/gramps/gen/plug/menu/_number.py +++ b/gramps/gen/plug/menu/_number.py @@ -37,7 +37,7 @@ from . import Option #------------------------------------------------------------------------- class NumberOption(Option): """ - This class describes an option that is a simple number with defined maximum + This class describes an option that is a simple number with defined maximum and minimum values. """ def __init__(self, label, value, min_val, max_val, step = 1): @@ -63,27 +63,27 @@ class NumberOption(Option): self.__min = min_val self.__max = max_val self.__step = step - + def get_min(self): """ Get the minimum value for this option. - + :return: an int that represents the minimum value for this option. """ return self.__min - + def get_max(self): """ Get the maximum value for this option. - + :return: an int that represents the maximum value for this option. """ return self.__max - + def get_step(self): """ Get the step size for this option. - + :return: an int that represents the step size for this option. """ return self.__step diff --git a/gramps/gen/plug/menu/_option.py b/gramps/gen/plug/menu/_option.py index b38aae273..44179ae2f 100644 --- a/gramps/gen/plug/menu/_option.py +++ b/gramps/gen/plug/menu/_option.py @@ -37,14 +37,14 @@ from ...utils.callback import Callback #------------------------------------------------------------------------- class Option(Callback): """ - This class serves as a base class for all options. All Options must - minimally provide the services provided by this class. Options are allowed + This class serves as a base class for all options. All Options must + minimally provide the services provided by this class. Options are allowed to add additional functionality. """ - + __signals__ = { 'value-changed' : None, 'avail-changed' : None} - + def __init__(self, label, value): """ :param label: A friendly label to be applied to this option. @@ -60,38 +60,38 @@ class Option(Callback): self.__label = label self.__help_str = "" self.__available = True - + def get_label(self): """ Get the friendly label for this option. - + :return: string """ return self.__label - + def set_label(self, label): """ Set the friendly label for this option. - + :param label: A friendly label to be applied to this option. Example: "Exclude living people" :type label: string :return: nothing """ self.__label = label - + def get_value(self): """ Get the value of this option. - + :return: The option value. """ return self.__value - + def set_value(self, value): """ Set the value of this option. - + :param value: A value for this option. Example: True :type value: The type will depend on the type of option. @@ -99,33 +99,33 @@ class Option(Callback): """ self.__value = value self.emit('value-changed') - + def get_help(self): """ Get the help information for this option. - + :return: A string that provides additional help beyond the label. """ return self.__help_str - + def set_help(self, help_text): """ Set the help information for this option. - + :param help: A string that provides additional help beyond the label. - Example: "Whether to include or exclude people who are calculated + Example: "Whether to include or exclude people who are calculated to be alive at the time of the generation of this report" :type value: string :return: nothing """ self.__help_str = help_text - + def set_available(self, avail): """ Set the availability of this option. - - :param avail: An indicator of whether this option is currently - available. True indicates that the option is available. + + :param avail: An indicator of whether this option is currently + available. True indicates that the option is available. False indicates that the option is not available. :type avail: Bool :return: nothing @@ -133,12 +133,12 @@ class Option(Callback): if avail != self.__available: self.__available = avail self.emit('avail-changed') - + def get_available(self): """ Get the availability of this option. - - :return: A Bool indicating the availablity of this option. True + + :return: A Bool indicating the availablity of this option. True indicates that the option is available. False indicates that the option is not available. """ diff --git a/gramps/gen/plug/menu/_person.py b/gramps/gen/plug/menu/_person.py index ab1cf6e7c..004b8825a 100644 --- a/gramps/gen/plug/menu/_person.py +++ b/gramps/gen/plug/menu/_person.py @@ -37,7 +37,7 @@ from . import StringOption #------------------------------------------------------------------------- class PersonOption(StringOption): """ - This class describes an option that allows a person from the + This class describes an option that allows a person from the database to be selected. """ def __init__(self, label): diff --git a/gramps/gen/plug/menu/_personlist.py b/gramps/gen/plug/menu/_personlist.py index 6feaa0866..ba9a48322 100644 --- a/gramps/gen/plug/menu/_personlist.py +++ b/gramps/gen/plug/menu/_personlist.py @@ -37,7 +37,7 @@ from . import Option #------------------------------------------------------------------------- class PersonListOption(Option): """ - This class describes a widget that allows multiple people from the + This class describes a widget that allows multiple people from the database to be selected. """ def __init__(self, label): diff --git a/gramps/gen/plug/menu/_placelist.py b/gramps/gen/plug/menu/_placelist.py index 8e08c2ae5..7a73c1661 100644 --- a/gramps/gen/plug/menu/_placelist.py +++ b/gramps/gen/plug/menu/_placelist.py @@ -37,7 +37,7 @@ from . import Option #------------------------------------------------------------------------- class PlaceListOption(Option): """ - This class describes a widget that allows multiple places from the + This class describes a widget that allows multiple places from the database to be selected. """ def __init__(self, label): diff --git a/gramps/gen/plug/menu/_style.py b/gramps/gen/plug/menu/_style.py index 2d36f943f..575db89cb 100644 --- a/gramps/gen/plug/menu/_style.py +++ b/gramps/gen/plug/menu/_style.py @@ -40,13 +40,13 @@ class StyleOption(EnumeratedListOption): """ This class describes an option that allows the use to select a style sheet. """ - + def __init__(self, label, default_style, module_name): """ :param label: A friendly label to be applied to this option. Example: "Style" :type label: string - :param default_style: A docgen StyleSheet instance which provides the + :param default_style: A docgen StyleSheet instance which provides the default styles. :type default_style: docgen StyleSheet :param module_name: The name of the module the style sheets belong to. @@ -55,25 +55,25 @@ class StyleOption(EnumeratedListOption): :return: nothing """ EnumeratedListOption.__init__(self, label, "default") - + self.__default_style = default_style self.__default_style.set_name("default") self.__style_file = "%s_style.xml" % module_name - style_list = StyleSheetList(self.__style_file, + style_list = StyleSheetList(self.__style_file, self.__default_style) for style_name in style_list.get_style_names(): self.add_item(style_name, style_name) - + def get_default_style(self): """ Get the default style """ return self.__default_style - + def get_style_file(self): """ Get the name of the style file """ return self.__style_file - + def get_style(self): """ Get the selected style """ - style_list = StyleSheetList(self.__style_file, + style_list = StyleSheetList(self.__style_file, self.__default_style) return style_list.get_style_sheet(self.get_value()) diff --git a/gramps/gen/plug/report/_bibliography.py b/gramps/gen/plug/report/_bibliography.py index ad48cc77f..26fcc7144 100644 --- a/gramps/gen/plug/report/_bibliography.py +++ b/gramps/gen/plug/report/_bibliography.py @@ -49,16 +49,16 @@ class Citation(object): """ self.__src_handle = None self.__ref_list = [] - + def get_source_handle(self): """ Provide the handle to the source that this citation is for. - + :return: Source Handle :rtype: handle """ return self.__src_handle - + def set_source_handle(self, handle): """ Set the handle for the source that this citation is for. @@ -67,7 +67,7 @@ class Citation(object): :type handle: handle """ self.__src_handle = handle - + def get_ref_list(self): """ List all the references to this citation. @@ -102,12 +102,12 @@ class Citation(object): float(letter_count))) # Exclude index for number_of_letters-1 for n in range(1, number_of_letters-1): - ref_count -= pow(letter_count, n) + ref_count -= pow(letter_count, n) # Adjust number_of_letters for new index number_of_letters = 1 + int(math.log(float(ref_count), float(letter_count))) for n in range(1, number_of_letters): - x_ref_count -= pow(letter_count, n) + x_ref_count -= pow(letter_count, n) for letter in range(1, number_of_letters): index = x_ref_count // pow(letter_count, letter) % letter_count key += letters[index] @@ -132,7 +132,7 @@ class Bibliography(object): citations (citations). Duplicate entries will not be added. To change what is considered duplicate, you can tell the bibliography what source ref information you are interested in by passing in the mode. - + Possible modes include: - MODE_DATE @@ -141,7 +141,7 @@ class Bibliography(object): - MODE_NOTE - MODE_MEDIA - MODE_ALL - + If you only care about pages, set "mode=MODE_PAGE". If you only care about dates and pages, set "mode=MODE_DATE|MODE_PAGE". If you care about everything, set "mode=MODE_ALL". @@ -157,13 +157,13 @@ class Bibliography(object): :param citation: Citation object :type citation: :class:`~.citation.Citation` - :return: A tuple containing the index of the source among all the + :return: A tuple containing the index of the source among all the sources and the key of the reference among all the references. If there is no reference information, the second element will be None. :rtype: (int,char) or (int,None) - - .. note:: + + .. note:: Within this file, the name 'citation' is used both for gen.lib.Citation, and for _bibliography.Citation. It is not clear how best to rename the concepts in this file to avoid the clash, @@ -182,7 +182,7 @@ class Bibliography(object): citation_found = True break cindex += 1 - + if not citation_found: citation = Citation() citation.set_source_handle(source_handle) @@ -192,13 +192,13 @@ class Bibliography(object): if self.__sref_has_info(lib_citation): for key, ref in citation.get_ref_list(): if self.__srefs_are_equal(ref, lib_citation): - # if a reference like this already exists, don't add + # if a reference like this already exists, don't add # another one return (cindex, key) rkey = citation.add_reference(lib_citation) - + return (cindex, rkey) - + def get_citation_count(self): """ Report the number of citations in this bibliography. @@ -207,7 +207,7 @@ class Bibliography(object): :rtype: int """ return len(self.__citation_list) - + def get_citation_list(self): """ Return a list containing all the citations in this bibliography. @@ -219,7 +219,7 @@ class Bibliography(object): def __sref_has_info(self, source_ref): """ - Determine if this source_ref has any useful information based on the + Determine if this source_ref has any useful information based on the current mode. """ if ( self.mode & self.MODE_PAGE ) == self.MODE_PAGE: @@ -242,10 +242,10 @@ class Bibliography(object): return True # Can't find anything interesting. return False - + def __srefs_are_equal(self, source_ref1, source_ref2): """ - Determine if two source references are equal based on the + Determine if two source references are equal based on the current mode. """ # The criterion for equality (in mode==MODE_ALL) is changed for diff --git a/gramps/gen/plug/report/_book.py b/gramps/gen/plug/report/_book.py index 4af478680..54cf7cae6 100644 --- a/gramps/gen/plug/report/_book.py +++ b/gramps/gen/plug/report/_book.py @@ -21,7 +21,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -# Written by Alex Roitman, +# Written by Alex Roitman, # largely based on the BaseDoc classes by Don Allingham #------------------------------------------------------------------------- @@ -85,8 +85,8 @@ class BookItem(object): def __init__(self, dbase, name): """ Create a new empty BookItem. - - name: the book item is retrieved + + name: the book item is retrieved from the book item registry using name for lookup """ self.dbase = dbase @@ -134,7 +134,7 @@ class BookItem(object): def set_style_name(self, style_name): """ Set the style name for the item. - + style_name: name of the style to set. """ self.style_name = style_name @@ -176,11 +176,11 @@ class Book(object): self.item_list = obj.item_list else: self.item_list = [] - + def set_name(self, name): """ Set the name of the book. - + name: the name to set. """ self.name = name @@ -214,7 +214,7 @@ class Book(object): def append_item(self, item): """ Add an item to the book. - + item: an item to append. """ self.item_list.append(item) @@ -222,8 +222,8 @@ class Book(object): def insert_item(self, index, item): """ Inserts an item into the given position in the book. - - index: a position index. + + index: a position index. item: an item to append. """ self.item_list.insert(index, item) @@ -231,24 +231,24 @@ class Book(object): def pop_item(self, index): """ Pop an item from given position in the book. - - index: a position index. + + index: a position index. """ return self.item_list.pop(index) def get_item(self, index): """ Return an item at a given position in the book. - - index: a position index. + + index: a position index. """ return self.item_list[index] def set_item(self, index, item): """ Set an item at a given position in the book. - - index: a position index. + + index: a position index. item: an item to set. """ self.item_list[index] = item @@ -400,14 +400,14 @@ class Book(object): #------------------------------------------------------------------------ class BookList(object): """ - Interface into the user-defined list of books. + Interface into the user-defined list of books. BookList is loaded from a specified XML file if it exists. """ def __init__(self, filename, dbase): """ - Create a new BookList from the books that may be defined in the + Create a new BookList from the books that may be defined in the specified file. file: XML file that contains book items definitions @@ -416,7 +416,7 @@ class BookList(object): self.bookmap = {} self.file = os.path.join(HOME_DIR, filename) self.parse() - + def delete_book(self, name): """ Remove a book from the list. Since each book must have a @@ -446,7 +446,7 @@ class BookList(object): def set_book(self, name, book): """ - Add or replaces a Book in the BookList. + Add or replaces a Book in the BookList. name: name associated with the Book to add or replace. book: definition of the Book @@ -465,7 +465,7 @@ class BookList(object): dbname = book.get_dbname() f.write('\n' % (name, dbname) ) for item in book.get_item_list(): - f.write(' \n' % + f.write(' \n' % (item.get_name(),item.get_translated_name() ) ) options = item.option_class.handler.options_dict for option_name in sorted(options.keys()): # enable a diff @@ -500,7 +500,7 @@ class BookList(object): if book.get_paper_name(): f.write(' \n' % book.get_paper_name() ) if book.get_orientation() is not None: # 0 is legal - f.write(' \n' % + f.write(' \n' % book.get_orientation() ) if book.get_paper_metric() is not None: # 0 is legal f.write(' \n' % book.get_paper_metric() ) @@ -519,7 +519,7 @@ class BookList(object): f.write('\n') f.close() - + def parse(self): """ Loads the BookList from the associated file, if it exists. @@ -544,7 +544,7 @@ class BookParser(handler.ContentHandler): """ SAX parsing class for the Books XML file. """ - + def __init__(self, booklist, dbase): """ Create a BookParser class that populates the passed booklist. @@ -562,7 +562,7 @@ class BookParser(handler.ContentHandler): self.s = None self.bname = None self.iname = None - + def startElement(self, tag, attrs): """ Overridden class that handles the start of a XML element @@ -667,7 +667,7 @@ def append_styles(selected_style, item): for this_style_name in style_sheet.get_paragraph_style_names(): selected_style.add_paragraph_style( - this_style_name, + this_style_name, style_sheet.get_paragraph_style(this_style_name)) for this_style_name in style_sheet.get_draw_style_names(): diff --git a/gramps/gen/plug/report/_options.py b/gramps/gen/plug/report/_options.py index 4a726827a..5d78c612b 100644 --- a/gramps/gen/plug/report/_options.py +++ b/gramps/gen/plug/report/_options.py @@ -84,7 +84,7 @@ class OptionList(_options.OptionList): self.format_name = None self.css_filename = None self.output = None - + def set_style_name(self, style_name): """ Set the style name for the OptionList. @@ -434,7 +434,7 @@ class OptionListCollection(_options.OptionListCollection): def set_last_format_name(self, format_name): """ Set the last format used for any report in this collection. - + :param format_name: name of the format to set. """ self.last_format_name = format_name @@ -485,7 +485,7 @@ class OptionListCollection(_options.OptionListCollection): f.write(' \n' % (size[0], size[1]) ) if option_list.get_margins(): margins = option_list.get_margins() - for pos in range(len(margins)): + for pos in range(len(margins)): f.write(' \n' % (pos, margins[pos])) @@ -519,7 +519,7 @@ class OptionParser(_options.OptionParser): """ SAX parsing class for the OptionListCollection XML file. """ - + def __init__(self, collection): """ Create a OptionParser class that populates the passed collection. @@ -600,7 +600,7 @@ class OptionParser(_options.OptionParser): else: # Tag is not report-specific, so we let the base class handle it. _options.OptionParser.endElement(self, tag) - + #------------------------------------------------------------------------ # # Empty class to keep the BaseDoc-targeted format happy @@ -614,16 +614,16 @@ class EmptyDoc(object): def set_creator(self, creator): pass - + def open(self, filename): pass - + def close(self): pass #------------------------------------------------------------------------- # -# Class handling options for plugins +# Class handling options for plugins # #------------------------------------------------------------------------- class OptionHandler(_options.OptionHandler): @@ -680,7 +680,7 @@ class OptionHandler(_options.OptionHandler): def save_options(self): """ Saves options to file. - + """ # First we save options from options_dict @@ -722,7 +722,7 @@ class OptionHandler(_options.OptionHandler): # Get the first part of name, if it contains a comma: # (will just be module_name, if no comma) filename = "%s.xml" % self.module_name.split(",")[0] - return os.path.join(HOME_DIR, filename) + return os.path.join(HOME_DIR, filename) def get_default_stylesheet_name(self): return self.style_name @@ -793,7 +793,7 @@ class ReportOptions(_options.Options): """ Defines options and provides handling interface. - + This is a base Options class for the reports. All reports, options classes should derive from it. """ @@ -806,22 +806,22 @@ class ReportOptions(_options.Options): self.options_dict = {} self.options_help = {} self.handler = None - + def load_previous_values(self): self.handler = OptionHandler(self.name, self.options_dict) def make_default_style(self, default_style): """ Defines default style for this report. - + This method MUST be overridden by reports that use the user-adjustable paragraph styles. .. note:: Unique names MUST be used for all style names, otherwise the styles will collide when making a book with duplicate style names. A rule of safety is to prepend style name with the - acronym based on report name. - + acronym based on report name. + The following acronyms are already taken: ==== ================================ @@ -854,7 +854,7 @@ class ReportOptions(_options.Options): def get_document(self): """ Return document instance. - + .. warning:: This method MUST NOT be overridden by subclasses. """ return self.handler.doc @@ -862,7 +862,7 @@ class ReportOptions(_options.Options): def set_document(self, val): """ Set document to a given instance. - + .. warning:: This method MUST NOT be overridden by subclasses. """ self.handler.doc = val @@ -870,7 +870,7 @@ class ReportOptions(_options.Options): def get_output(self): """ Return document output destination. - + .. warning:: This method MUST NOT be overridden by subclasses. """ return self.handler.output @@ -878,7 +878,7 @@ class ReportOptions(_options.Options): def set_output(self, val): """ Set output destination to a given string. - + .. warning:: This method MUST NOT be overridden by subclasses. """ self.handler.output = val @@ -894,19 +894,19 @@ class MenuReportOptions(MenuOptions, ReportOptions): The MenuReportOptions class implements the :class:`ReportOptions` functionality in a generic way so that the user does not need to be concerned with the actual representation of the options. - - The user should inherit the MenuReportOptions class and override the - add_menu_options function. The user can add options to the menu and the + + The user should inherit the MenuReportOptions class and override the + add_menu_options function. The user can add options to the menu and the MenuReportOptions class will worry about setting up the UI. """ def __init__(self, name, dbase): ReportOptions.__init__(self, name, dbase) MenuOptions.__init__(self) - + def load_previous_values(self): ReportOptions.load_previous_values(self) - # Pass the loaded values to the menu options so they will be displayed + # Pass the loaded values to the menu options so they will be displayed # properly. for optname in self.options_dict: menu_option = self.menu.get_option_by_name(optname) @@ -935,7 +935,7 @@ class DocOptionHandler(_options.OptionHandler): """ Set options to be used in this plugin according to the passed options dictionary. - + Dictionary values are all strings, since they were read from XML. Here we need to convert them to the needed types. We use default values to determine the type. @@ -946,7 +946,7 @@ class DocOptionHandler(_options.OptionHandler): for option_name, option_data in options.items(): if ( option_name in self.options_dict and isinstance(option_data, list) and - option_data and + option_data and option_data[0] in docgen_names ): try: converter = get_type_converter( @@ -972,7 +972,7 @@ class DocOptions(MenuOptions): """ self.name = name MenuOptions.__init__(self) - + def load_previous_values(self): self.handler = DocOptionHandler(self.name, self.options_dict) @@ -1015,7 +1015,7 @@ class DocOptionParser(_options.OptionParser): """ SAX parsing class for the DocOptionListCollection XML file. """ - + def __init__(self, collection): """ Create a DocOptionParser class that populates the passed collection. diff --git a/gramps/gen/plug/report/endnotes.py b/gramps/gen/plug/report/endnotes.py index 489498b34..d9eb5b5ff 100644 --- a/gramps/gen/plug/report/endnotes.py +++ b/gramps/gen/plug/report/endnotes.py @@ -13,7 +13,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -47,7 +47,7 @@ from ...utils.string import conf_strings def add_endnote_styles(style_sheet): """ Add paragraph styles to a style sheet to be used for displaying endnotes. - + :param style_sheet: Style sheet :type style_sheet: :class:`.StyleSheet` """ @@ -68,7 +68,7 @@ def add_endnote_styles(style_sheet): para.set_description(_('The basic style used for ' 'the endnotes source display.')) style_sheet.add_paragraph_style("Endnotes-Source", para) - + para = ParagraphStyle() para.set(lmargin=.75) para.set_top_margin(0.2) @@ -84,7 +84,7 @@ def add_endnote_styles(style_sheet): para.set_description(_('The basic style used for ' 'the endnotes reference display.')) style_sheet.add_paragraph_style("Endnotes-Ref", para) - + para = ParagraphStyle() para.set(lmargin=1.9) para.set_top_margin(0.2) @@ -96,7 +96,7 @@ def add_endnote_styles(style_sheet): def cite_source(bibliography, database, obj, elocale=glocale): """ Cite any sources for the object and add them to the bibliography. - + :param bibliography: The bibliography to contain the citations. :type bibliography: :class:`.Bibliography` :param obj: An object with source references. @@ -128,7 +128,7 @@ def write_endnotes(bibliography, database, doc, printnotes=False, links=False, elocale=glocale): """ Write all the entries in the bibliography as endnotes. - + If elocale is passed in (a :class:`.GrampsLocale`), then (insofar as possible) the translated values will be returned instead. @@ -155,17 +155,17 @@ def write_endnotes(bibliography, database, doc, printnotes=False, links=False, doc.start_paragraph('Endnotes-Header') doc.write_text(trans_text('Endnotes')) doc.end_paragraph() - + cindex = 0 for citation in bibliography.get_citation_list(): cindex += 1 source = database.get_source_from_handle(citation.get_source_handle()) first = True - + doc.start_paragraph('Endnotes-Source', "%d." % cindex) doc.write_text(_format_source_text(source, elocale), links=links) doc.end_paragraph() - + if printnotes: _print_notes(source, database, doc, 'Endnotes-Source-Notes', links) @@ -187,36 +187,36 @@ def _format_source_text(source, elocale): # trans_text is a defined keyword (see po/update_po.py, po/genpot.sh) src_txt = "" - + if source.get_author(): src_txt += source.get_author() - + if source.get_title(): if src_txt: # translators: needed for Arabic, ignore otherwise src_txt += trans_text(', ') # translators: ignore unless your quotation marks differ src_txt += trans_text('"%s"') % source.get_title() - + if source.get_publication_info(): if src_txt: # translators: needed for Arabic, ignore otherwise src_txt += trans_text(', ') src_txt += source.get_publication_info() - + if source.get_abbreviation(): if src_txt: # translators: needed for Arabic, ignore otherwise src_txt += trans_text(', ') src_txt += "(%s)" % source.get_abbreviation() - + return src_txt def _format_ref_text(ref, key, elocale): if not ref: return "" - + ref_txt = "" - + datepresent = False date = ref.get_date_object() if date is not None and not date.is_empty(): @@ -228,18 +228,18 @@ def _format_ref_text(ref, key, elocale): ref_txt = elocale.get_date(date) else: ref_txt = ref.get_page() - + # Print only confidence level if it is not Normal if ref.get_confidence_level() != Citation.CONF_NORMAL: ref_txt += " [" + elocale.translation.gettext( conf_strings[ref.get_confidence_level()]) + "]" - + return ref_txt def _print_notes(obj, db, doc, style, links): note_list = obj.get_note_list() ind = 1 - for notehandle in note_list: + for notehandle in note_list: note = db.get_note_from_handle(notehandle) contains_html = note.get_type() == NoteType.HTML_CODE doc.write_styled_note(note.get_styledtext(), note.get_format(), style, diff --git a/gramps/gen/plug/report/utils.py b/gramps/gen/plug/report/utils.py index 294c473c5..8c057daef 100644 --- a/gramps/gen/plug/report/utils.py +++ b/gramps/gen/plug/report/utils.py @@ -12,7 +12,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -56,7 +56,7 @@ def _T_(value): # enable deferred translations (see Python docs 22.1.3.4) #------------------------------------------------------------------------- def pt2cm(pt): """ - Convert points to centimeters. Fonts are typically specified in points, + Convert points to centimeters. Fonts are typically specified in points, but the :class:`.BaseDoc` classes use centimeters. :param pt: points @@ -68,7 +68,7 @@ def pt2cm(pt): def cm2pt(cm): """ - Convert centimeters to points. Fonts are typically specified in points, + Convert centimeters to points. Fonts are typically specified in points, but the :class:`.BaseDoc` classes use centimeters. :param cm: centimeters @@ -114,7 +114,7 @@ def roman(num): #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- def place_name(db, place_handle): @@ -124,7 +124,7 @@ def place_name(db, place_handle): else: name = "" return str(name) - + #------------------------------------------------------------------------- # # Functions commonly used in reports @@ -152,7 +152,7 @@ def insert_image(database, doc, photo, user, alt=alt, style_name=style_name, crop=photo.get_rectangle()) else: - user.warn(_("Could not add photo to page"), + user.warn(_("Could not add photo to page"), "%s: %s" % (filename, _('File does not exist'))) #------------------------------------------------------------------------- @@ -172,7 +172,7 @@ def find_spouse(person, family): # find_marriage # #------------------------------------------------------------------------- -def find_marriage(database, family): +def find_marriage(database, family): for event_ref in family.get_event_ref_list(): event = database.get_event_from_handle(event_ref.ref) if (event and event.type.is_marriage() and @@ -188,18 +188,18 @@ def find_marriage(database, family): def get_person_mark(db, person): """ Return a IndexMark that can be used to index a person in a report - + :param db: the Gramps database instance :param person: the key is for """ if not person: return None - + name = person.get_primary_name().get_name() birth = " " death = " " key = "" - + birth_ref = person.get_birth_ref() if birth_ref: birthEvt = db.get_event_from_handle(birth_ref.ref) @@ -214,7 +214,7 @@ def get_person_mark(db, person): key = name else: key = "%s (%s - %s)" % (name, birth, death) - + return IndexMark( key, INDEX_TYPE_ALP ) #------------------------------------------------------------------------- @@ -225,19 +225,19 @@ def get_person_mark(db, person): def get_address_str(addr): """ Return a string that combines the elements of an address - + :param addr: the Gramps address instance """ str = "" - elems = [ addr.get_street(), - addr.get_locality(), - addr.get_city(), - addr.get_county(), - addr.get_state(), - addr.get_country(), - addr.get_postal_code(), + elems = [ addr.get_street(), + addr.get_locality(), + addr.get_city(), + addr.get_county(), + addr.get_state(), + addr.get_country(), + addr.get_postal_code(), addr.get_phone() ] - + for info in elems: if info: if str == "": @@ -246,7 +246,7 @@ def get_address_str(addr): # translators: needed for Arabic, ignore otherwise str = _("%(str1)s, %(str2)s") % {'str1':str, 'str2':info} return str - + #------------------------------------------------------------------------- # # People Filters @@ -277,7 +277,7 @@ def get_person_filters(person, include_single=True, name_format=None): # Do this in case of command line options query (show=filter) name = _("PERSON") gramps_id = '' - + if include_single: filt_id = GenericFilter() filt_id.set_name(name) diff --git a/gramps/gen/plug/utils.py b/gramps/gen/plug/utils.py index 3295176f1..b1edff39c 100644 --- a/gramps/gen/plug/utils.py +++ b/gramps/gen/plug/utils.py @@ -112,7 +112,7 @@ class Zipfile(object): names = self.zip_obj.namelist() for name in self.get_paths(names): fullname = os.path.join(path, name) - if not os.path.exists(fullname): + if not os.path.exists(fullname): os.mkdir(fullname) for name in self.get_files(names): fullname = os.path.join(path, name) @@ -307,8 +307,8 @@ def load_addon_file(path, callback=None): callback((_("Examining '%s'...") % gpr_file) + "\n") contents = file_obj.extractfile(gpr_file).read() # Put a fake register and _ function in environment: - env = make_environment(register=register, - newplugin=newplugin, + env = make_environment(register=register, + newplugin=newplugin, _=lambda text: text) # clear out the result variable: globals()["register_results"] = [] diff --git a/gramps/gen/proxy/filter.py b/gramps/gen/proxy/filter.py index 5006d892d..aee05d6f9 100644 --- a/gramps/gen/proxy/filter.py +++ b/gramps/gen/proxy/filter.py @@ -11,7 +11,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -39,10 +39,10 @@ class FilterProxyDb(ProxyDbBase): the user. """ - def __init__(self, db, person_filter=None, event_filter=None, + def __init__(self, db, person_filter=None, event_filter=None, note_filter=None): """ - Create a new FilterProxyDb instance. + Create a new FilterProxyDb instance. """ ProxyDbBase.__init__(self, db) self.person_filter = person_filter @@ -57,7 +57,7 @@ class FilterProxyDb(ProxyDbBase): self.db, self.db.iter_event_handles())) else: self.elist = set(self.db.iter_event_handles()) - + if note_filter: self.nlist = set(note_filter.apply( self.db, self.db.iter_note_handles())) @@ -104,25 +104,25 @@ class FilterProxyDb(ProxyDbBase): person.set_birth_ref(bref) if dref in new_eref_list: person.set_death_ref(dref) - + # Filter notes out self.sanitize_person(person) - + return person else: return None def include_person(self, handle): - return handle in self.plist + return handle in self.plist def include_family(self, handle): - return handle in self.flist + return handle in self.flist def include_event(self, handle): - return handle in self.elist + return handle in self.elist def include_note(self, handle): - return handle in self.nlist + return handle in self.nlist def get_source_from_handle(self, handle): """ @@ -134,14 +134,14 @@ class FilterProxyDb(ProxyDbBase): if source: # Filter notes out self.sanitize_notebase(source) - + media_ref_list = source.get_media_list() for media_ref in media_ref_list: self.sanitize_notebase(media_ref) attributes = media_ref.get_attribute_list() for attribute in attributes: self.sanitize_notebase(attribute) - + repo_ref_list = source.get_reporef_list() for repo_ref in repo_ref_list: self.sanitize_notebase(repo_ref) @@ -168,7 +168,7 @@ class FilterProxyDb(ProxyDbBase): if media: # Filter notes out self.sanitize_notebase(media) - + attributes = media.get_attribute_list() for attr in attributes: self.sanitize_notebase(attr) @@ -181,11 +181,11 @@ class FilterProxyDb(ProxyDbBase): If no such Place exists, None is returned. """ place = self.db.get_place_from_handle(handle) - + if place: # Filter notes out self.sanitize_notebase(place) - + media_ref_list = place.get_media_list() for media_ref in media_ref_list: self.sanitize_notebase(media_ref) @@ -223,20 +223,20 @@ class FilterProxyDb(ProxyDbBase): if family.get_father_handle() not in self.plist: family.set_father_handle(None) - + if family.get_mother_handle() not in self.plist: family.set_mother_handle(None) clist = [ cref for cref in family.get_child_ref_list() if cref.ref in self.plist ] family.set_child_ref_list(clist) - + # Filter notes out for cref in clist: self.sanitize_notebase(cref) - + self.sanitize_notebase(family) - + attributes = family.get_attribute_list() for attr in attributes: self.sanitize_notebase(attr) @@ -247,7 +247,7 @@ class FilterProxyDb(ProxyDbBase): attributes = event_ref.get_attribute_list() for attribute in attributes: self.sanitize_notebase(attribute) - + media_ref_list = family.get_media_list() for media_ref in media_ref_list: self.sanitize_notebase(media_ref) @@ -394,7 +394,7 @@ class FilterProxyDb(ProxyDbBase): def iter_person_handles(self): """ Return an iterator over database handles, one handle for each Person in - the database. + the database. """ return self.plist @@ -407,14 +407,14 @@ class FilterProxyDb(ProxyDbBase): def get_event_handles(self): """ Return a list of database handles, one handle for each Event in - the database. + the database. """ return list(self.elist) - + def iter_event_handles(self): """ Return an iterator over database handles, one handle for each Event in - the database. + the database. """ return self.elist @@ -430,11 +430,11 @@ class FilterProxyDb(ProxyDbBase): the database. """ return list(self.flist) - + def iter_family_handles(self): """ Return an iterator over database handles, one handle for each Family in - the database. + the database. """ return self.flist @@ -442,7 +442,7 @@ class FilterProxyDb(ProxyDbBase): """ Return an iterator over objects for Families in the database """ - return map(self.get_family_from_handle, self.flist) + return map(self.get_family_from_handle, self.flist) def get_note_handles(self): """ @@ -454,7 +454,7 @@ class FilterProxyDb(ProxyDbBase): def iter_note_handles(self): """ Return an iterator over database handles, one handle for each Note in - the database. + the database. """ return self.nlist @@ -462,7 +462,7 @@ class FilterProxyDb(ProxyDbBase): """ Return an iterator over objects for Notes in the database """ - return map(self.get_note_from_handle, self.nlist) + return map(self.get_note_from_handle, self.nlist) def get_default_person(self): """returns the default Person of the database""" @@ -479,7 +479,7 @@ class FilterProxyDb(ProxyDbBase): return handle else: return None - + def has_person_handle(self, handle): """ returns True if the handle exists in the current Person database. @@ -492,7 +492,7 @@ class FilterProxyDb(ProxyDbBase): """ return handle in self.elist - def has_family_handle(self, handle): + def has_family_handle(self, handle): """ returns True if the handle exists in the current Family database. """ @@ -514,7 +514,7 @@ class FilterProxyDb(ProxyDbBase): :param include_classes: list of class names to include in the results. Default: None means include all classes. :type include_classes: list of class names - + This default implementation does a sequential scan through all the primary object databases and is very slow. Backends can override this method to provide much faster implementations that @@ -527,7 +527,7 @@ class FilterProxyDb(ProxyDbBase): """ #FIXME: add a filter for returned handles (see private.py as an example) return self.db.find_backlink_handles(handle, include_classes) - + def sanitize_notebase(self, notebase): """ Filters notes out of the passed notebase object according to the Note Filter. @@ -539,13 +539,13 @@ class FilterProxyDb(ProxyDbBase): note_list = notebase.get_note_list() new_note_list = [ note for note in note_list if note in self.nlist ] notebase.set_note_list(new_note_list) - + def sanitize_addressbase(self, addressbase): if addressbase: addresses = addressbase.get_address_list() for address in addresses: self.sanitize_notebase(address) - + def sanitize_person(self, person): """ Cleans filtered notes out of the passed person diff --git a/gramps/gen/proxy/living.py b/gramps/gen/proxy/living.py index 50175be87..e02fccd2c 100644 --- a/gramps/gen/proxy/living.py +++ b/gramps/gen/proxy/living.py @@ -1,6 +1,6 @@ # # Gramps - a GTK+/GNOME based genealogy program -# +# # Copyright (C) 2007-2008 Brian G. Matherly # # This program is free software; you can redistribute it and/or modify @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -50,12 +50,12 @@ class LivingProxyDb(ProxyDbBase): def __init__(self, dbase, mode, current_year=None, years_after_death=0): """ Create a new LivingProxyDb instance. - + :param dbase: The database to be a proxy for :type dbase: DbBase :param mode: - The method for handling living people. - LivingProxyDb.MODE_EXCLUDE_ALL will remove living people altogether. + The method for handling living people. + LivingProxyDb.MODE_EXCLUDE_ALL will remove living people altogether. LivingProxyDb.MODE_INCLUDE_LAST_NAME_ONLY will remove all information and change their given name to "[Living]" or what has been set in Preferences -> Text. @@ -65,7 +65,7 @@ class LivingProxyDb(ProxyDbBase): :param current_year: The current year to use for living determination. If None is supplied, the current year will be found from the system. :type current_year: int or None - :param years_after_death: The number of years after a person's death to + :param years_after_death: The number of years after a person's death to still consider them living. :type years_after_death: int """ @@ -106,7 +106,7 @@ class LivingProxyDb(ProxyDbBase): """ for person in filter(None, self.db.iter_people()): if self.__is_living(person): - if self.mode == self.MODE_EXCLUDE_ALL: + if self.mode == self.MODE_EXCLUDE_ALL: continue else: yield self.__restrict_person(person) @@ -141,8 +141,8 @@ class LivingProxyDb(ProxyDbBase): person = self.get_unfiltered_person(handle) if person and self.__is_living(person): return False - return True - + return True + def get_default_person(self): """returns the default Person of the database""" person_handle = self.db.get_default_handle() @@ -173,7 +173,7 @@ class LivingProxyDb(ProxyDbBase): :param include_classes: list of class names to include in the results. Default: None means include all classes. :type include_classes: list of class names - + This default implementation does a sequential scan through all the primary object databases and is very slow. Backends can override this method to provide much faster implementations that @@ -191,7 +191,7 @@ class LivingProxyDb(ProxyDbBase): continue yield (class_name, handle) return - + def __is_living(self, person): """ Check if a person is considered living. @@ -204,7 +204,7 @@ class LivingProxyDb(ProxyDbBase): self.db, self.current_date, self.years_after_death ) - + def __remove_living_from_family(self, family): """ Remove information from a family that pertains to living people. @@ -213,9 +213,9 @@ class LivingProxyDb(ProxyDbBase): """ if family is None: return None - + parent_is_living = False - + father_handle = family.get_father_handle() if father_handle: father = self.db.get_person_from_handle(father_handle) @@ -223,7 +223,7 @@ class LivingProxyDb(ProxyDbBase): parent_is_living = True if self.mode == self.MODE_EXCLUDE_ALL: family.set_father_handle(None) - + mother_handle = family.get_mother_handle() if mother_handle: mother = self.db.get_person_from_handle(mother_handle) @@ -231,29 +231,29 @@ class LivingProxyDb(ProxyDbBase): parent_is_living = True if self.mode == self.MODE_EXCLUDE_ALL: family.set_mother_handle(None) - + if parent_is_living: # Clear all events for families where a parent is living. family.set_event_ref_list([]) - + if self.mode == self.MODE_EXCLUDE_ALL: for child_ref in family.get_child_ref_list(): child_handle = child_ref.get_reference_handle() child = self.db.get_person_from_handle(child_handle) if child and self.__is_living(child): family.remove_child_ref(child_ref) - + return family def __restrict_person(self, person): """ - Remove information from a person and replace the first name with + Remove information from a person and replace the first name with "[Living]" or what has been set in Preferences -> Text. """ new_person = Person() new_name = Name() old_name = person.get_primary_name() - + new_name.set_group_as(old_name.get_group_as()) new_name.set_sort_as(old_name.get_sort_as()) new_name.set_display_as(old_name.get_display_as()) @@ -268,7 +268,7 @@ class LivingProxyDb(ProxyDbBase): surnlst = [] for surn in old_name.get_surname_list(): surname = Surname(source=surn) - if int(surname.origintype) in [NameOriginType.PATRONYMIC, + if int(surname.origintype) in [NameOriginType.PATRONYMIC, NameOriginType.MATRONYMIC]: surname.set_surname(config.get('preferences.private-surname-text')) surnlst.append(surname) @@ -280,9 +280,9 @@ class LivingProxyDb(ProxyDbBase): new_person.set_handle(person.get_handle()) new_person.set_change_time(person.get_change_time()) new_person.set_family_handle_list(person.get_family_handle_list()) - new_person.set_parent_family_handle_list( + new_person.set_parent_family_handle_list( person.get_parent_family_handle_list() ) new_person.set_tag_list(person.get_tag_list()) - + return new_person diff --git a/gramps/gen/proxy/private.py b/gramps/gen/proxy/private.py index 5ee51d4d1..05938c5f5 100644 --- a/gramps/gen/proxy/private.py +++ b/gramps/gen/proxy/private.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -39,8 +39,8 @@ LOG = logging.getLogger(".citation") # GRAMPS libraries # #------------------------------------------------------------------------- -from ..lib import (MediaRef, Attribute, Address, EventRef, - Person, Name, Source, RepoRef, MediaObject, Place, Event, +from ..lib import (MediaRef, Attribute, Address, EventRef, + Person, Name, Source, RepoRef, MediaObject, Place, Event, Family, ChildRef, Repository, LdsOrd, Surname, Citation, SrcAttribute, Note, Tag) from .proxybase import ProxyDbBase @@ -53,7 +53,7 @@ class PrivateProxyDb(ProxyDbBase): def __init__(self, db): """ - Create a new PrivateProxyDb instance. + Create a new PrivateProxyDb instance. """ ProxyDbBase.__init__(self, db) @@ -238,67 +238,67 @@ class PrivateProxyDb(ProxyDbBase): return None # Define predicate functions for use by default iterator methods - + def include_person(self, handle): """ Predicate returning True if object is to be included, else False """ obj = self.get_unfiltered_person(handle) return obj and not obj.get_privacy() - + def include_family(self, handle): """ Predicate returning True if object is to be included, else False - """ + """ obj = self.get_unfiltered_family(handle) return obj and not obj.get_privacy() - + def include_event(self, handle): """ Predicate returning True if object is to be included, else False - """ + """ obj = self.get_unfiltered_event(handle) return obj and not obj.get_privacy() - + def include_source(self, handle): """ Predicate returning True if object is to be included, else False - """ + """ obj = self.get_unfiltered_source(handle) return obj and not obj.get_privacy() - + def include_citation(self, handle): """ Predicate returning True if object is to be included, else False - """ + """ obj = self.get_unfiltered_citation(handle) return obj and not obj.get_privacy() - + def include_place(self, handle): """ Predicate returning True if object is to be included, else False - """ + """ obj = self.get_unfiltered_place(handle) return obj and not obj.get_privacy() - + def include_media_object(self, handle): """ Predicate returning True if object is to be included, else False """ obj = self.get_unfiltered_object(handle) return obj and not obj.get_privacy() - + def include_repository(self, handle): """ Predicate returning True if object is to be included, else False - """ + """ obj = self.get_unfiltered_repository(handle) return obj and not obj.get_privacy() - + def include_note(self, handle): """ Predicate returning True if object is to be included, else False - """ + """ obj = self.get_unfiltered_note(handle) return obj and not obj.get_privacy() @@ -316,7 +316,7 @@ class PrivateProxyDb(ProxyDbBase): if person and not person.get_privacy(): return handle return None - + def has_person_handle(self, handle): """ returns True if the handle exists in the current Person database. @@ -362,7 +362,7 @@ class PrivateProxyDb(ProxyDbBase): return True return False - def has_family_handle(self, handle): + def has_family_handle(self, handle): """ Return True if the handle exists in the current Family database. """ @@ -408,7 +408,7 @@ class PrivateProxyDb(ProxyDbBase): :param include_classes: list of class names to include in the results. Default: None means include all classes. :type include_classes: list of class names - + This default implementation does a sequential scan through all the primary object databases and is very slow. Backends can override this method to provide much faster implementations that @@ -419,9 +419,9 @@ class PrivateProxyDb(ProxyDbBase): > result_list = list(find_backlink_handles(handle)) """ - + # This isn't done yet because it doesn't check if references are - # private (like a MediaRef). It only checks if the + # private (like a MediaRef). It only checks if the # referenced object is private. objects = { @@ -443,12 +443,12 @@ class PrivateProxyDb(ProxyDbBase): if obj and not obj.get_privacy(): yield (class_name, handle) else: - raise NotImplementedError + raise NotImplementedError return def copy_media_ref_list(db, original_obj, clean_obj): """ - Copies media references from one object to another - excluding private + Copies media references from one object to another - excluding private references and references to private objects. :param db: Gramps database to which the references belongs @@ -487,7 +487,7 @@ def copy_citation_ref_list(db, original_obj, clean_obj): source = db.get_source_from_handle(handle) if source and not source.get_privacy(): clean_obj.add_citation(citation_handle) - + def copy_notes(db, original_obj, clean_obj): """ Copies notes from one object to another - excluding references to private @@ -500,7 +500,7 @@ def copy_notes(db, original_obj, clean_obj): :param clean_obj: Object that will have only non-private references :type original_obj: NoteBase :returns: Nothing - """ + """ for note_handle in original_obj.get_note_list(): note = db.get_note_from_handle(note_handle) if note and not note.get_privacy(): @@ -529,7 +529,7 @@ def copy_associations(db, original_obj, clean_obj): def copy_attributes(db, original_obj, clean_obj): """ - Copies attributes from one object to another - excluding references to + Copies attributes from one object to another - excluding references to private attributes. :param db: Gramps database to which the references belongs @@ -539,7 +539,7 @@ def copy_attributes(db, original_obj, clean_obj): :param clean_obj: Object that will have only non-private references :type original_obj: AttributeBase :returns: Nothing - """ + """ for attribute in original_obj.get_attribute_list(): if attribute and not attribute.get_privacy(): new_attribute = Attribute() @@ -551,7 +551,7 @@ def copy_attributes(db, original_obj, clean_obj): def copy_srcattributes(db, original_obj, clean_obj): """ - Copies srcattributes from one object to another - excluding references to + Copies srcattributes from one object to another - excluding references to private srcattributes. :param db: Gramps database to which the references belongs @@ -561,7 +561,7 @@ def copy_srcattributes(db, original_obj, clean_obj): :param clean_obj: Object that will have only non-private references :type original_obj: SrcAttributeBase :returns: Nothing - """ + """ for attribute in original_obj.get_attribute_list(): if attribute and not attribute.get_privacy(): new_attribute = SrcAttribute() @@ -571,7 +571,7 @@ def copy_srcattributes(db, original_obj, clean_obj): def copy_urls(db, original_obj, clean_obj): """ - Copies urls from one object to another - excluding references to + Copies urls from one object to another - excluding references to private urls. :param db: Gramps database to which the references belongs @@ -581,14 +581,14 @@ def copy_urls(db, original_obj, clean_obj): :param clean_obj: Object that will have only non-private urls :type original_obj: UrlBase :returns: Nothing - """ + """ for url in original_obj.get_url_list(): if url and not url.get_privacy(): clean_obj.add_url(url) - + def copy_lds_ords(db, original_obj, clean_obj): """ - Copies LDS ORDs from one object to another - excluding references to + Copies LDS ORDs from one object to another - excluding references to private LDS ORDs. :param db: Gramps database to which the references belongs @@ -598,14 +598,14 @@ def copy_lds_ords(db, original_obj, clean_obj): :param clean_obj: Object that will have only non-private LDS ORDs :type original_obj: LdsOrdBase :returns: Nothing - """ + """ for lds_ord in original_obj.get_lds_ord_list(): if lds_ord and not lds_ord.get_privacy(): clean_obj.add_lds_ord(sanitize_lds_ord(db, lds_ord)) - + def copy_addresses(db, original_obj, clean_obj): """ - Copies addresses from one object to another - excluding references to + Copies addresses from one object to another - excluding references to private addresses. :param db: Gramps database to which the references belongs @@ -615,7 +615,7 @@ def copy_addresses(db, original_obj, clean_obj): :param clean_obj: Object that will have only non-private addresses :type original_obj: AddressBase :returns: Nothing - """ + """ for address in original_obj.get_address_list(): if address and not address.get_privacy(): clean_obj.add_address(sanitize_address(db, address)) @@ -625,7 +625,7 @@ def sanitize_lds_ord(db, lds_ord): Create a new LdsOrd instance based off the passed LdsOrd instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the LdsOrd object belongs :type db: DbBase :param name: source LdsOrd object that will be copied with @@ -643,9 +643,9 @@ def sanitize_lds_ord(db, lds_ord): fam = db.get_family_from_handle(fam_handle) if fam and not fam.get_privacy(): new_lds_ord.set_family_handle(fam_handle) - + new_lds_ord.set_date_object(lds_ord.get_date_object()) - + place_handle = lds_ord.get_place_handle() place = db.get_place_from_handle(place_handle) if place and not place.get_privacy(): @@ -653,15 +653,15 @@ def sanitize_lds_ord(db, lds_ord): copy_citation_ref_list(db, lds_ord, new_lds_ord) copy_notes(db, lds_ord, new_lds_ord) - + return new_lds_ord - + def sanitize_address(db, address): """ Create a new Address instance based off the passed Address instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param name: source Address object that will be copied with @@ -671,7 +671,7 @@ def sanitize_address(db, address): :rtype: Address """ new_address = Address() - + new_address.set_street(address.get_street()) new_address.set_locality(address.get_locality()) new_address.set_city(address.get_city()) @@ -680,19 +680,19 @@ def sanitize_address(db, address): new_address.set_country(address.get_country()) new_address.set_postal_code(address.get_postal_code()) new_address.set_phone(address.get_phone()) - + new_address.set_date_object(address.get_date_object()) copy_citation_ref_list(db, address, new_address) copy_notes(db, address, new_address) - + return new_address - + def sanitize_name(db, name): """ Create a new Name instance based off the passed Name instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param name: source Name object that will be copied with @@ -714,10 +714,10 @@ def sanitize_name(db, name): new_name.set_title(name.get_title()) new_name.set_date_object(name.get_date_object()) new_name.set_surname_list(name.get_surname_list()) - + copy_citation_ref_list(db, name, new_name) copy_notes(db, name, new_name) - + return new_name def sanitize_media_ref(db, media_ref): @@ -725,7 +725,7 @@ def sanitize_media_ref(db, media_ref): Create a new MediaRef instance based off the passed MediaRef instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the MediaRef object belongs :type db: DbBase :param source_ref: source MediaRef object that will be copied with @@ -736,12 +736,12 @@ def sanitize_media_ref(db, media_ref): """ new_ref = MediaRef() new_ref.set_rectangle(media_ref.get_rectangle()) - + new_ref.set_reference_handle(media_ref.get_reference_handle()) copy_notes(db, media_ref, new_ref) copy_attributes(db, media_ref, new_ref) copy_citation_ref_list(db, media_ref, new_ref) - + return new_ref def sanitize_citation(db, citation): @@ -749,7 +749,7 @@ def sanitize_citation(db, citation): Create a new Citation instance based off the passed Citation instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param citation: source Citation object that will be copied with @@ -769,15 +769,15 @@ def sanitize_citation(db, citation): copy_srcattributes(db, citation, new_citation) copy_notes(db, citation, new_citation) copy_media_ref_list(db, citation, new_citation) - + return new_citation - + def sanitize_event_ref(db, event_ref): """ Create a new EventRef instance based off the passed EventRef instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param event_ref: source EventRef object that will be copied with @@ -787,12 +787,12 @@ def sanitize_event_ref(db, event_ref): :rtype: EventRef """ new_ref = EventRef() - + new_ref.set_reference_handle(event_ref.get_reference_handle()) new_ref.set_role(event_ref.get_role()) copy_notes(db, event_ref, new_ref) copy_attributes(db, event_ref, new_ref) - + return new_ref def sanitize_person(db, person): @@ -800,7 +800,7 @@ def sanitize_person(db, person): Create a new Person instance based off the passed Person instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param person: source Person object that will be copied with @@ -817,7 +817,7 @@ def sanitize_person(db, person): new_person.set_handle(person.get_handle()) new_person.set_change_time(person.get_change_time()) new_person.set_tag_list(person.get_tag_list()) - + # copy names if not private name = person.get_primary_name() if (name and name.get_privacy()) or (person and person.get_privacy()): @@ -885,7 +885,7 @@ def sanitize_person(db, person): copy_lds_ords(db, person, new_person) copy_notes(db, person, new_person) copy_associations(db, person, new_person) - + return new_person def sanitize_source(db, source): @@ -893,7 +893,7 @@ def sanitize_source(db, source): Create a new Source instance based off the passed Source instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param source: source Source object that will be copied with @@ -903,7 +903,7 @@ def sanitize_source(db, source): :rtype: Source """ new_source = Source() - + new_source.set_author(source.get_author()) new_source.set_title(source.get_title()) new_source.set_publication_info(source.get_publication_info()) @@ -911,7 +911,7 @@ def sanitize_source(db, source): new_source.set_gramps_id(source.get_gramps_id()) new_source.set_handle(source.get_handle()) new_source.set_change_time(source.get_change_time()) - + for repo_ref in source.get_reporef_list(): if repo_ref and not repo_ref.get_privacy(): handle = repo_ref.get_reference_handle() @@ -922,7 +922,7 @@ def sanitize_source(db, source): copy_srcattributes(db, source, new_source) copy_media_ref_list(db, source, new_source) copy_notes(db, source, new_source) - + return new_source def sanitize_media(db, media): @@ -930,7 +930,7 @@ def sanitize_media(db, media): Create a new MediaObject instance based off the passed Media instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param media: source Media object that will be copied with @@ -940,7 +940,7 @@ def sanitize_media(db, media): :rtype: MediaObject """ new_media = MediaObject() - + new_media.set_mime_type(media.get_mime_type()) new_media.set_path(media.get_path()) new_media.set_description(media.get_description()) @@ -961,7 +961,7 @@ def sanitize_place(db, place): Create a new Place instance based off the passed Place instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param place: source Place object that will be copied with @@ -971,7 +971,7 @@ def sanitize_place(db, place): :rtype: Place """ new_place = Place() - + new_place.set_title(place.get_title()) new_place.set_gramps_id(place.get_gramps_id()) new_place.set_handle(place.get_handle()) @@ -988,7 +988,7 @@ def sanitize_place(db, place): copy_notes(db, place, new_place) copy_media_ref_list(db, place, new_place) copy_urls(db, place, new_place) - + return new_place def sanitize_event(db, event): @@ -996,7 +996,7 @@ def sanitize_event(db, event): Create a new Event instance based off the passed Event instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param event: source Event object that will be copied with @@ -1006,7 +1006,7 @@ def sanitize_event(db, event): :rtype: Event """ new_event = Event() - + new_event.set_type(event.get_type()) new_event.set_description(event.get_description()) new_event.set_gramps_id(event.get_gramps_id()) @@ -1018,20 +1018,20 @@ def sanitize_event(db, event): copy_notes(db, event, new_event) copy_media_ref_list(db, event, new_event) copy_attributes(db, event, new_event) - + place_handle = event.get_place_handle() place = db.get_place_from_handle(place_handle) if place and not place.get_privacy(): new_event.set_place_handle(place_handle) - + return new_event - + def sanitize_family(db, family): """ Create a new Family instance based off the passed Family instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param family: source Family object that will be copied with @@ -1041,13 +1041,13 @@ def sanitize_family(db, family): :rtype: Family """ new_family = Family() - + new_family.set_gramps_id(family.get_gramps_id()) new_family.set_handle(family.get_handle()) new_family.set_relationship(family.get_relationship()) new_family.set_change_time(family.get_change_time()) new_family.set_tag_list(family.get_tag_list()) - + # Copy the father handle. father_handle = family.get_father_handle() if father_handle: @@ -1061,7 +1061,7 @@ def sanitize_family(db, family): mother = db.get_person_from_handle(mother_handle) if mother and not mother.get_privacy(): new_family.set_mother_handle(mother_handle) - + # Copy child references. for child_ref in family.get_child_ref_list(): if child_ref and child_ref.get_privacy(): @@ -1078,7 +1078,7 @@ def sanitize_family(db, family): copy_notes(db, child_ref, new_ref) copy_citation_ref_list(db, child_ref, new_ref) new_family.add_child_ref(new_ref) - + # Copy event ref list. for event_ref in family.get_event_ref_list(): if event_ref and not event_ref.get_privacy(): @@ -1091,7 +1091,7 @@ def sanitize_family(db, family): copy_media_ref_list(db, family, new_family) copy_attributes(db, family, new_family) copy_lds_ords(db, family, new_family) - + return new_family def sanitize_repository(db, repository): @@ -1099,7 +1099,7 @@ def sanitize_repository(db, repository): Create a new Repository instance based off the passed Repository instance. The returned instance has all private records removed from it. - + :param db: Gramps database to which the Person object belongs :type db: DbBase :param repository: source Repository object that will be copied with @@ -1109,7 +1109,7 @@ def sanitize_repository(db, repository): :rtype: Repository """ new_repository = Repository() - + new_repository.set_type(repository.get_type()) new_repository.set_name(repository.get_name()) new_repository.set_gramps_id(repository.get_gramps_id()) @@ -1119,5 +1119,5 @@ def sanitize_repository(db, repository): copy_notes(db, repository, new_repository) copy_addresses(db, repository, new_repository) copy_urls(db, repository, new_repository) - + return new_repository diff --git a/gramps/gen/proxy/proxybase.py b/gramps/gen/proxy/proxybase.py index b411eee6e..03a9bde3c 100644 --- a/gramps/gen/proxy/proxybase.py +++ b/gramps/gen/proxy/proxybase.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -53,7 +53,7 @@ class ProxyCursor(object): def __exit__(self, exc_type, exc_val, exc_tb): pass - + def __iter__(self): for handle in self.get_handles(): yield bytes(handle, "utf-8"), self.get_raw(handle) @@ -76,9 +76,9 @@ class ProxyMap(object): class ProxyDbBase(DbReadBase): """ - ProxyDbBase is a base class for building a proxy to a Gramps database. - This class attempts to implement functions that are likely to be common - among proxy classes. Functions that are not likely to be common raise a + ProxyDbBase is a base class for building a proxy to a Gramps database. + This class attempts to implement functions that are likely to be common + among proxy classes. Functions that are not likely to be common raise a NotImplementedError to remind the developer to implement those functions. Real database proxy classes can inherit from this class to make sure the @@ -87,7 +87,7 @@ class ProxyDbBase(DbReadBase): def __init__(self, db): """ - Create a new ProxyDb instance. + Create a new ProxyDb instance. """ self.db = self.basedb = db while isinstance(self.basedb, ProxyDbBase): @@ -103,21 +103,21 @@ class ProxyDbBase(DbReadBase): self.media_bookmarks = db.media_bookmarks self.note_bookmarks = db.note_bookmarks - self.person_map = ProxyMap(self, self.get_raw_person_data, + self.person_map = ProxyMap(self, self.get_raw_person_data, self.get_person_handles) - self.family_map = ProxyMap(self, self.get_raw_family_data, + self.family_map = ProxyMap(self, self.get_raw_family_data, self.get_family_handles) - self.event_map = ProxyMap(self, self.get_raw_event_data, + self.event_map = ProxyMap(self, self.get_raw_event_data, self.get_event_handles) - self.place_map = ProxyMap(self, self.get_raw_place_data, + self.place_map = ProxyMap(self, self.get_raw_place_data, self.get_place_handles) - self.source_map = ProxyMap(self, self.get_raw_source_data, + self.source_map = ProxyMap(self, self.get_raw_source_data, self.get_source_handles) - self.repository_map = ProxyMap(self, self.get_raw_repository_data, + self.repository_map = ProxyMap(self, self.get_raw_repository_data, self.get_repository_handles) - self.media_map = ProxyMap(self, self.get_raw_object_data, + self.media_map = ProxyMap(self, self.get_raw_object_data, self.get_media_object_handles) - self.note_map = ProxyMap(self, self.get_raw_note_data, + self.note_map = ProxyMap(self, self.get_raw_note_data, self.get_note_handles) def is_open(self): @@ -125,12 +125,12 @@ class ProxyDbBase(DbReadBase): Return 1 if the database has been opened. """ return self.db.is_open - + def get_researcher(self): """returns the Researcher instance, providing information about the owner of the database""" - return self.db.get_researcher() - + return self.db.get_researcher() + def include_something(self, handle, obj=None): """ Model predicate. Returns True if object referred to by handle is to be @@ -141,9 +141,9 @@ class ProxyDbBase(DbReadBase): # Call function to determine if object should be included or not return obj.include() - + # Define default predicates for each object type - + include_person = \ include_family = \ include_event = \ @@ -155,9 +155,9 @@ class ProxyDbBase(DbReadBase): include_note = \ include_tag = \ None - + def get_person_cursor(self): - return ProxyCursor(self.get_raw_person_data, + return ProxyCursor(self.get_raw_person_data, self.get_person_handles) def get_family_cursor(self): @@ -199,27 +199,27 @@ class ProxyDbBase(DbReadBase): def get_person_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Person in - the database. + the database. """ if self.db.is_open: return list(self.iter_person_handles()) else: return [] - + def get_family_handles(self, sort_handles=True): """ Return a list of database handles, one handle for each Family in - the database. + the database. """ if self.db.is_open: return list(self.iter_family_handles()) else: return [] - + def get_event_handles(self, sort_handles=True): """ Return a list of database handles, one handle for each Event in - the database. + the database. """ if self.db.is_open: return list(self.iter_event_handles()) @@ -229,37 +229,37 @@ class ProxyDbBase(DbReadBase): def get_source_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Source in - the database. + the database. """ if self.db.is_open: return list(self.iter_source_handles()) else: return [] - + def get_citation_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Citation in - the database. + the database. """ if self.db.is_open: return list(self.iter_citation_handles()) else: return [] - + def get_place_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Place in - the database. + the database. """ if self.db.is_open: return list(self.iter_place_handles()) else: return [] - + def get_media_object_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each MediaObject in - the database. + the database. """ if self.db.is_open: return list(self.iter_media_object_handles()) @@ -269,17 +269,17 @@ class ProxyDbBase(DbReadBase): def get_repository_handles(self, sort_handles=True): """ Return a list of database handles, one handle for each Repository in - the database. + the database. """ if self.db.is_open: return list(self.iter_repository_handles()) else: return [] - + def get_note_handles(self, sort_handles=True): """ Return a list of database handles, one handle for each Note in - the database. + the database. """ if self.db.is_open: return list(self.iter_note_handles()) @@ -289,7 +289,7 @@ class ProxyDbBase(DbReadBase): def get_tag_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Tag in - the database. + the database. """ if self.db.is_open: return list(self.iter_tag_handles()) @@ -302,15 +302,15 @@ class ProxyDbBase(DbReadBase): def get_default_handle(self): """returns the default Person of the database""" - return self.db.get_default_handle() - + return self.db.get_default_handle() + def iter_person_handles(self): """ Return an iterator over database handles, one handle for each Person in the database. """ return filter(self.include_person, self.db.iter_person_handles()) - + def iter_family_handles(self): """ Return an iterator over database handles, one handle for each Family in @@ -330,14 +330,14 @@ class ProxyDbBase(DbReadBase): Return an iterator over database handles, one handle for each Source in the database. """ - return filter(self.include_source, self.db.iter_source_handles()) + return filter(self.include_source, self.db.iter_source_handles()) def iter_citation_handles(self): """ - Return an iterator over database handles, one handle for each Citation + Return an iterator over database handles, one handle for each Citation in the database. """ - return filter(self.include_citation, self.db.iter_citation_handles()) + return filter(self.include_citation, self.db.iter_citation_handles()) def iter_place_handles(self): """ @@ -345,7 +345,7 @@ class ProxyDbBase(DbReadBase): the database. """ return filter(self.include_place, self.db.iter_place_handles()) - + def iter_media_object_handles(self): """ Return an iterator over database handles, one handle for each Media @@ -355,7 +355,7 @@ class ProxyDbBase(DbReadBase): def iter_repository_handles(self): """ - Return an iterator over database handles, one handle for each + Return an iterator over database handles, one handle for each Repository in the database. """ return filter(self.include_repository, self.db.iter_repository_handles()) @@ -385,63 +385,63 @@ class ProxyDbBase(DbReadBase): Return an iterator over Person objects in the database """ return self.__iter_object(self.include_person, self.db.iter_people) - + def iter_families(self): """ Return an iterator over Family objects in the database """ - return self.__iter_object(self.include_family, self.db.iter_families) - + return self.__iter_object(self.include_family, self.db.iter_families) + def iter_events(self): """ Return an iterator over Event objects in the database """ return self.__iter_object(self.include_event, self.db.iter_events) - + def iter_places(self): """ Return an iterator over Place objects in the database """ - return self.__iter_object(self.include_place, self.db.iter_places) - + return self.__iter_object(self.include_place, self.db.iter_places) + def iter_sources(self): """ Return an iterator over Source objects in the database """ - return self.__iter_object(self.include_source, self.db.iter_sources) - + return self.__iter_object(self.include_source, self.db.iter_sources) + def iter_citations(self): """ Return an iterator over Citation objects in the database """ - return self.__iter_object(self.include_citation, self.db.iter_citations) - + return self.__iter_object(self.include_citation, self.db.iter_citations) + def iter_media_objects(self): """ Return an iterator over Media objects in the database """ return self.__iter_object(self.include_media_object, - self.db.iter_media_objects) - + self.db.iter_media_objects) + def iter_repositories(self): """ Return an iterator over Repositories objects in the database """ return self.__iter_object(self.include_repository, self.db.iter_repositories) - + def iter_notes(self): """ Return an iterator over Note objects in the database """ - return self.__iter_object(self.include_note, self.db.iter_notes) - + return self.__iter_object(self.include_note, self.db.iter_notes) + def iter_tags(self): """ Return an iterator over Tag objects in the database """ - return self.__iter_object(self.include_tag, self.db.iter_tags) - + return self.__iter_object(self.include_tag, self.db.iter_tags) + @staticmethod def gfilter(predicate, obj): """ @@ -469,7 +469,7 @@ class ProxyDbBase(DbReadBase): # if a write-method: if (name in DbWriteBase.__dict__ and - not name.startswith("__") and + not name.startswith("__") and type(DbWriteBase.__dict__[name]) is types.FunctionType): raise AttributeError # Default behaviour: lookup attribute in parent object @@ -489,7 +489,7 @@ class ProxyDbBase(DbReadBase): If no such Family exists, None is returned. """ return self.gfilter(self.include_family, - self.db.get_family_from_handle(handle)) + self.db.get_family_from_handle(handle)) def get_event_from_handle(self, handle): """ @@ -497,7 +497,7 @@ class ProxyDbBase(DbReadBase): If no such Event exists, None is returned. """ return self.gfilter(self.include_event, - self.db.get_event_from_handle(handle)) + self.db.get_event_from_handle(handle)) def get_source_from_handle(self, handle): """ @@ -546,7 +546,7 @@ class ProxyDbBase(DbReadBase): """ return self.gfilter(self.include_note, self.db.get_note_from_handle(handle)) - + def get_tag_from_handle(self, handle): """ Finds a Tag in the database from the passed gramps handle. @@ -554,7 +554,7 @@ class ProxyDbBase(DbReadBase): """ return self.gfilter(self.include_tag, self.db.get_tag_from_handle(handle)) - + def get_person_from_gramps_id(self, val): """ Finds a Person in the database from the passed GRAMPS ID. @@ -891,14 +891,14 @@ class ProxyDbBase(DbReadBase): """ return self.gfilter(self.include_note, self.db.get_note_from_handle(handle)) is not None - + def has_tag_handle(self, handle): """ returns True if the handle exists in the current Tag database. """ return self.gfilter(self.include_tag, self.db.get_tag_from_handle(handle)) is not None - + def get_mediapath(self): """returns the default media path of the database""" return self.db.get_mediapath() diff --git a/gramps/gen/proxy/referencedbyselection.py b/gramps/gen/proxy/referencedbyselection.py index 3bb7a6387..316824e2b 100644 --- a/gramps/gen/proxy/referencedbyselection.py +++ b/gramps/gen/proxy/referencedbyselection.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -31,7 +31,7 @@ a person. # #------------------------------------------------------------------------- from .proxybase import ProxyDbBase -from ..lib import (Person, Family, Source, Citation, Event, MediaObject, +from ..lib import (Person, Family, Source, Citation, Event, MediaObject, Place, Repository, Note, Tag) class ReferencedBySelectionProxyDb(ProxyDbBase): @@ -44,7 +44,7 @@ class ReferencedBySelectionProxyDb(ProxyDbBase): def __init__(self, dbase, all_people=False): """ - Create a new ReferencedByPeopleProxyDb instance. + Create a new ReferencedByPeopleProxyDb instance. :param all_people: if True, get all people, and the items they link to; if False, get all people that are connected to @@ -62,7 +62,7 @@ class ReferencedBySelectionProxyDb(ProxyDbBase): self.queue = [] if all_people: # Do not add references to those not already included - self.restricted_to["Person"] = [x for x in + self.restricted_to["Person"] = [x for x in self.db.iter_person_handles()] # Spread activation to all other items: for handle in self.restricted_to["Person"]: @@ -152,7 +152,7 @@ class ReferencedBySelectionProxyDb(ProxyDbBase): if person.handle in self.referenced["Person"]: return # A person that we should not add: - if (self.restricted_to["Person"] and + if (self.restricted_to["Person"] and person.handle not in self.restricted_to["Person"]): return if reference: @@ -162,7 +162,7 @@ class ReferencedBySelectionProxyDb(ProxyDbBase): for (class_name, handle) in self.db.find_backlink_handles( person.handle, ["Person", "Family"]): self.queue_object(class_name, handle) - + name = person.get_primary_name() if name: self.process_name(name) @@ -245,7 +245,7 @@ class ReferencedBySelectionProxyDb(ProxyDbBase): place = self.db.get_place_from_handle(place_handle) if place: self.process_place(place) - + def process_place(self, place): """ Follow the place object and find all of the primary objects @@ -275,7 +275,7 @@ class ReferencedBySelectionProxyDb(ProxyDbBase): for repo_ref in source.get_reporef_list(): if repo_ref: self.process_notes(repo_ref) - handle = repo_ref.get_reference_handle() + handle = repo_ref.get_reference_handle() repo = self.db.get_repository_from_handle(handle) if repo: self.process_repository(repo) @@ -361,7 +361,7 @@ class ReferencedBySelectionProxyDb(ProxyDbBase): """ Find all of the primary objects referred to """ self.process_citation_ref_list(name) self.process_notes(name) - + def process_addresses(self, original_obj): """ Find all of the primary objects referred to """ for address in original_obj.get_address_list(): @@ -451,25 +451,25 @@ class ReferencedBySelectionProxyDb(ProxyDbBase): Filter for person """ return handle in self.referenced["Person"] - + def include_place(self, handle): """ Filter for places """ return handle in self.referenced["Place"] - + def include_family(self, handle): """ Filter for families """ return handle in self.referenced["Family"] - + def include_media_object(self, handle): """ Filter for media objects """ return handle in self.referenced["MediaObject"] - + def include_event(self, handle): """ Filter for events @@ -481,36 +481,36 @@ class ReferencedBySelectionProxyDb(ProxyDbBase): Filter for sources """ return handle in self.referenced["Source"] - + def include_citation(self, handle): """ Filter for citations """ return handle in self.referenced["Citation"] - + def include_repository(self, handle): """ Filter for repositories """ return handle in self.referenced["Repository"] - + def include_note(self, handle): """ Filter for notes """ return handle in self.referenced["Note"] - + def include_tag(self, handle): """ Filter for tags """ return handle in self.referenced["Tag"] - + def find_backlink_handles(self, handle, include_classes=None): """ Return appropriate backlink handles for this proxy. """ - for (objclass, handle) in self.db.find_backlink_handles(handle, + for (objclass, handle) in self.db.find_backlink_handles(handle, include_classes): if handle in self.referenced[objclass]: yield (objclass, handle) diff --git a/gramps/gen/recentfiles.py b/gramps/gen/recentfiles.py index 274a07183..fa10912d1 100644 --- a/gramps/gen/recentfiles.py +++ b/gramps/gen/recentfiles.py @@ -119,11 +119,11 @@ class RecentFiles(object): self.gramps_recent_files = gramps_parser.get() def add(self,item2add): - # First we need to walk the existing items to see + # First we need to walk the existing items to see # if our item is already there for item in self.gramps_recent_files: if item.get_path() == item2add.get_path(): - # Found it -- modify timestamp and add all groups + # Found it -- modify timestamp and add all groups # to the item's groups item.set_time(item2add.get_time()) return @@ -134,7 +134,7 @@ class RecentFiles(object): def rename_filename(self,filename, new_filename): - # First we need to walk the existing items to see + # First we need to walk the existing items to see # if our item is already there found = False for index in range(len(self.gramps_recent_files)): @@ -146,7 +146,7 @@ class RecentFiles(object): self.gramps_recent_files[index].set_name(new_filename) def remove_filename(self,filename): - # First we need to walk the existing items to see + # First we need to walk the existing items to see # if our item is already there found = False for index in range(len(self.gramps_recent_files)): @@ -159,7 +159,7 @@ class RecentFiles(object): def check_if_recent(self,filename): - # First we need to walk the existing items to see + # First we need to walk the existing items to see # if our item is already there found = False for index in range(len(self.gramps_recent_files)): @@ -212,7 +212,7 @@ class RecentParser(object): """ Parsing class for the RecentFiles collection. """ - + def __init__(self): self.recent_files = [] @@ -300,4 +300,4 @@ def rename_filename(filename, new_filename): def check_if_recent(filename): gramps_rf = RecentFiles() return gramps_rf.check_if_recent(filename) - + diff --git a/gramps/gen/relationship.py b/gramps/gen/relationship.py index 85d84ccdb..78b35ff25 100644 --- a/gramps/gen/relationship.py +++ b/gramps/gen/relationship.py @@ -54,17 +54,17 @@ _level_name = [ "", "first", "second", "third", "fourth", "fifth", "sixth", "thirteenth", "fourteenth", "fifteenth", "sixteenth", "seventeenth", "eighteenth", "nineteenth", "twentieth" ] -_removed_level = [ "", " once removed", " twice removed", +_removed_level = [ "", " once removed", " twice removed", " three times removed", - " four times removed", " five times removed", + " four times removed", " five times removed", " six times removed", - " seven times removed", " eight times removed", + " seven times removed", " eight times removed", " nine times removed", - " ten times removed", " eleven times removed", + " ten times removed", " eleven times removed", " twelve times removed", - " thirteen times removed", " fourteen times removed", + " thirteen times removed", " fourteen times removed", " fifteen times removed", - " sixteen times removed", " seventeen times removed", + " sixteen times removed", " seventeen times removed", " eighteen times removed", " nineteen times removed", " twenty times removed" ] @@ -89,8 +89,8 @@ _parents_level = [ "", "parents", "grandparents", "great grandparents", "nineteenth great grandparents", "twentieth great grandparents", ] -_father_level = [ "", "%(step)sfather%(inlaw)s", "%(step)sgrandfather%(inlaw)s", - "great %(step)sgrandfather%(inlaw)s", +_father_level = [ "", "%(step)sfather%(inlaw)s", "%(step)sgrandfather%(inlaw)s", + "great %(step)sgrandfather%(inlaw)s", "second great %(step)sgrandfather%(inlaw)s", "third great %(step)sgrandfather%(inlaw)s", "fourth great %(step)sgrandfather%(inlaw)s", @@ -111,9 +111,9 @@ _father_level = [ "", "%(step)sfather%(inlaw)s", "%(step)sgrandfather%(inlaw)s", "nineteenth great %(step)sgrandfather%(inlaw)s", "twentieth great %(step)sgrandfather%(inlaw)s", ] -_mother_level = [ "", "%(step)smother%(inlaw)s", +_mother_level = [ "", "%(step)smother%(inlaw)s", "%(step)sgrandmother%(inlaw)s", - "great %(step)sgrandmother%(inlaw)s", + "great %(step)sgrandmother%(inlaw)s", "second great %(step)sgrandmother%(inlaw)s", "third great %(step)sgrandmother%(inlaw)s", "fourth great %(step)sgrandmother%(inlaw)s", @@ -131,55 +131,55 @@ _mother_level = [ "", "%(step)smother%(inlaw)s", "sixteenth great %(step)sgrandmother%(inlaw)s", "seventeenth great %(step)sgrandmother%(inlaw)s", "eighteenth great %(step)sgrandmother%(inlaw)s", - "nineteenth great %(step)sgrandmother%(inlaw)s", + "nineteenth great %(step)sgrandmother%(inlaw)s", "twentieth great %(step)sgrandmother%(inlaw)s", ] -_son_level = [ "", "%(step)sson%(inlaw)s", "%(step)sgrandson%(inlaw)s", - "great %(step)sgrandson%(inlaw)s", +_son_level = [ "", "%(step)sson%(inlaw)s", "%(step)sgrandson%(inlaw)s", + "great %(step)sgrandson%(inlaw)s", "second great %(step)sgrandson%(inlaw)s", "third great %(step)sgrandson%(inlaw)s", "fourth great %(step)sgrandson%(inlaw)s", "fifth great %(step)sgrandson%(inlaw)s", "sixth great %(step)sgrandson%(inlaw)s", - "seventh great %(step)sgrandson%(inlaw)s", + "seventh great %(step)sgrandson%(inlaw)s", "eighth great %(step)sgrandson%(inlaw)s", - "ninth great %(step)sgrandson%(inlaw)s", + "ninth great %(step)sgrandson%(inlaw)s", "tenth great %(step)sgrandson%(inlaw)s", "eleventh great %(step)sgrandson%(inlaw)s", "twelfth great %(step)sgrandson%(inlaw)s", - "thirteenth great %(step)sgrandson%(inlaw)s", + "thirteenth great %(step)sgrandson%(inlaw)s", "fourteenth great %(step)sgrandson%(inlaw)s", - "fifteenth great %(step)sgrandson%(inlaw)s", + "fifteenth great %(step)sgrandson%(inlaw)s", "sixteenth great %(step)sgrandson%(inlaw)s", - "seventeenth great %(step)sgrandson%(inlaw)s", + "seventeenth great %(step)sgrandson%(inlaw)s", "eighteenth great %(step)sgrandson%(inlaw)s", - "nineteenth great %(step)sgrandson%(inlaw)s", + "nineteenth great %(step)sgrandson%(inlaw)s", "twentieth great %(step)sgrandson%(inlaw)s", ] _daughter_level = [ "", "%(step)sdaughter%(inlaw)s", "%(step)sgranddaughter%(inlaw)s", "great %(step)sgranddaughter%(inlaw)s", "second great %(step)sgranddaughter%(inlaw)s", - "third great %(step)sgranddaughter%(inlaw)s", + "third great %(step)sgranddaughter%(inlaw)s", "fourth great %(step)sgranddaughter%(inlaw)s", - "fifth great %(step)sgranddaughter%(inlaw)s", + "fifth great %(step)sgranddaughter%(inlaw)s", "sixth great %(step)sgranddaughter%(inlaw)s", - "seventh great %(step)sgranddaughter%(inlaw)s", + "seventh great %(step)sgranddaughter%(inlaw)s", "eighth great %(step)sgranddaughter%(inlaw)s", "ninth great %(step)sgranddaughter%(inlaw)s", "tenth great %(step)sgranddaughter%(inlaw)s", "eleventh great %(step)sgranddaughter%(inlaw)s", "twelfth great %(step)sgranddaughter%(inlaw)s", - "thirteenth great %(step)sgranddaughter%(inlaw)s", + "thirteenth great %(step)sgranddaughter%(inlaw)s", "fourteenth great %(step)sgranddaughter%(inlaw)s", - "fifteenth great %(step)sgranddaughter%(inlaw)s", + "fifteenth great %(step)sgranddaughter%(inlaw)s", "sixteenth great %(step)sgranddaughter%(inlaw)s", - "seventeenth great %(step)sgranddaughter%(inlaw)s", + "seventeenth great %(step)sgranddaughter%(inlaw)s", "eighteenth great %(step)sgranddaughter%(inlaw)s", - "nineteenth great %(step)sgranddaughter%(inlaw)s", + "nineteenth great %(step)sgranddaughter%(inlaw)s", "twentieth great %(step)sgranddaughter%(inlaw)s", ] _sister_level = [ "", "%(step)ssister%(inlaw)s", "%(step)saunt%(inlaw)s", - "%(step)sgrandaunt%(inlaw)s", + "%(step)sgrandaunt%(inlaw)s", "great %(step)sgrandaunt%(inlaw)s", "second great %(step)sgrandaunt%(inlaw)s", "third great %(step)sgrandaunt%(inlaw)s", @@ -202,34 +202,34 @@ _sister_level = [ "", "%(step)ssister%(inlaw)s", "%(step)saunt%(inlaw)s", "twentieth great %(step)sgrandaunt%(inlaw)s", ] _brother_level = [ "", "%(step)sbrother%(inlaw)s", "%(step)suncle%(inlaw)s", - "%(step)sgranduncle%(inlaw)s", + "%(step)sgranduncle%(inlaw)s", "great %(step)sgranduncle%(inlaw)s", "second great %(step)sgranduncle%(inlaw)s", - "third great %(step)sgranduncle%(inlaw)s", + "third great %(step)sgranduncle%(inlaw)s", "fourth great %(step)sgranduncle%(inlaw)s", - "fifth great %(step)sgranduncle%(inlaw)s", + "fifth great %(step)sgranduncle%(inlaw)s", "sixth great %(step)sgranduncle%(inlaw)s", - "seventh great %(step)sgranduncle%(inlaw)s", + "seventh great %(step)sgranduncle%(inlaw)s", "eighth great %(step)sgranduncle%(inlaw)s", - "ninth great %(step)sgranduncle%(inlaw)s", + "ninth great %(step)sgranduncle%(inlaw)s", "tenth great %(step)sgranduncle%(inlaw)s", - "eleventh great %(step)sgranduncle%(inlaw)s", + "eleventh great %(step)sgranduncle%(inlaw)s", "twelfth great %(step)sgranduncle%(inlaw)s", - "thirteenth great %(step)sgranduncle%(inlaw)s", + "thirteenth great %(step)sgranduncle%(inlaw)s", "fourteenth great %(step)sgranduncle%(inlaw)s", - "fifteenth great %(step)sgranduncle%(inlaw)s", + "fifteenth great %(step)sgranduncle%(inlaw)s", "sixteenth great %(step)sgranduncle%(inlaw)s", - "seventeenth great %(step)sgranduncle%(inlaw)s", + "seventeenth great %(step)sgranduncle%(inlaw)s", "eighteenth great %(step)sgranduncle%(inlaw)s", - "nineteenth great %(step)sgranduncle%(inlaw)s", + "nineteenth great %(step)sgranduncle%(inlaw)s", "twentieth great %(step)sgranduncle%(inlaw)s", ] -_nephew_level = [ "", "%(step)snephew%(inlaw)s", "%(step)sgrandnephew%(inlaw)s", +_nephew_level = [ "", "%(step)snephew%(inlaw)s", "%(step)sgrandnephew%(inlaw)s", "great %(step)sgrandnephew%(inlaw)s", "second great %(step)sgrandnephew%(inlaw)s", - "third great %(step)sgrandnephew%(inlaw)s", + "third great %(step)sgrandnephew%(inlaw)s", "fourth great %(step)sgrandnephew%(inlaw)s", - "fifth great %(step)sgrandnephew%(inlaw)s", + "fifth great %(step)sgrandnephew%(inlaw)s", "sixth great %(step)sgrandnephew%(inlaw)s", "seventh great %(step)sgrandnephew%(inlaw)s", "eighth great %(step)sgrandnephew%(inlaw)s", @@ -246,18 +246,18 @@ _nephew_level = [ "", "%(step)snephew%(inlaw)s", "%(step)sgrandnephew%(inlaw)s", "nineteenth great %(step)sgrandnephew%(inlaw)s", "twentieth great %(step)sgrandnephew%(inlaw)s", ] -_niece_level = [ "", "%(step)sniece%(inlaw)s", "%(step)sgrandniece%(inlaw)s", - "great %(step)sgrandniece%(inlaw)s", +_niece_level = [ "", "%(step)sniece%(inlaw)s", "%(step)sgrandniece%(inlaw)s", + "great %(step)sgrandniece%(inlaw)s", "second great %(step)sgrandniece%(inlaw)s", - "third great %(step)sgrandniece%(inlaw)s", + "third great %(step)sgrandniece%(inlaw)s", "fourth great %(step)sgrandniece%(inlaw)s", - "fifth great %(step)sgrandniece%(inlaw)s", + "fifth great %(step)sgrandniece%(inlaw)s", "sixth great %(step)sgrandniece%(inlaw)s", "seventh great %(step)sgrandniece%(inlaw)s", "eighth great %(step)sgrandniece%(inlaw)s", "ninth great %(step)sgrandniece%(inlaw)s", "tenth great %(step)sgrandniece%(inlaw)s", - "eleventh great %(step)sgrandniece%(inlaw)s", + "eleventh great %(step)sgrandniece%(inlaw)s", "twelfth great %(step)sgrandniece%(inlaw)s", "thirteenth great %(step)sgrandniece%(inlaw)s", "fourteenth great %(step)sgrandniece%(inlaw)s", @@ -269,7 +269,7 @@ _niece_level = [ "", "%(step)sniece%(inlaw)s", "%(step)sgrandniece%(inlaw)s", "twentieth great %(step)sgrandniece%(inlaw)s", ] _children_level = [ "", - "children", "grandchildren", + "children", "grandchildren", "great grandchildren", "second great grandchildren", "third great grandchildren", "fourth great grandchildren", "fifth great grandchildren", "sixth great grandchildren", @@ -282,48 +282,48 @@ _children_level = [ "", "nineteenth great grandchildren", "twentieth great grandchildren", ] _siblings_level = [ "", - "siblings", "uncles/aunts", - "granduncles/aunts", "great granduncles/aunts", - "second great granduncles/aunts", "third great granduncles/aunts", - "fourth great granduncles/aunts", "fifth great granduncles/aunts", - "sixth great granduncles/aunts", "seventh great granduncles/aunts", - "eighth great granduncles/aunts", "ninth great granduncles/aunts", - "tenth great granduncles/aunts", "eleventh great granduncles/aunts", - "twelfth great granduncles/aunts", "thirteenth great granduncles/aunts", - "fourteenth great granduncles/aunts", "fifteenth great granduncles/aunts", - "sixteenth great granduncles/aunts", "seventeenth great granduncles/aunts", - "eighteenth great granduncles/aunts", "nineteenth great granduncles/aunts", + "siblings", "uncles/aunts", + "granduncles/aunts", "great granduncles/aunts", + "second great granduncles/aunts", "third great granduncles/aunts", + "fourth great granduncles/aunts", "fifth great granduncles/aunts", + "sixth great granduncles/aunts", "seventh great granduncles/aunts", + "eighth great granduncles/aunts", "ninth great granduncles/aunts", + "tenth great granduncles/aunts", "eleventh great granduncles/aunts", + "twelfth great granduncles/aunts", "thirteenth great granduncles/aunts", + "fourteenth great granduncles/aunts", "fifteenth great granduncles/aunts", + "sixteenth great granduncles/aunts", "seventeenth great granduncles/aunts", + "eighteenth great granduncles/aunts", "nineteenth great granduncles/aunts", "twentieth great granduncles/aunts", ] - + _sibling_level = [ "", - "%(step)ssibling%(inlaw)s", - "%(step)suncle/aunt%(inlaw)s", - "%(step)sgranduncle/aunt%(inlaw)s", - "great %(step)sgranduncle/aunt%(inlaw)s", - "second great %(step)sgranduncle/aunt%(inlaw)s", - "third great %(step)sgranduncle/aunt%(inlaw)s", - "fourth great %(step)sgranduncle/aunt%(inlaw)s", - "fifth great %(step)sgranduncle/aunt%(inlaw)s", - "sixth great %(step)sgranduncle/aunt%(inlaw)s", - "seventh great %(step)sgranduncle/aunt%(inlaw)s", - "eighth great %(step)sgranduncle/aunt%(inlaw)s", - "ninth great %(step)sgranduncle/aunt%(inlaw)s", - "tenth great %(step)sgranduncle/aunt%(inlaw)s", - "eleventh great %(step)sgranduncle/aunt%(inlaw)s", - "twelfth great %(step)sgranduncle/aunt%(inlaw)s", - "thirteenth great %(step)sgranduncle/aunt%(inlaw)s", - "fourteenth great %(step)sgranduncle/aunt%(inlaw)s", - "fifteenth great %(step)sgranduncle/aunt%(inlaw)s", - "sixteenth great %(step)sgranduncle/aunt%(inlaw)s", - "seventeenth great %(step)sgranduncle/aunt%(inlaw)s", - "eighteenth great %(step)sgranduncle/aunt%(inlaw)s", - "nineteenth great %(step)sgranduncle/aunt%(inlaw)s", + "%(step)ssibling%(inlaw)s", + "%(step)suncle/aunt%(inlaw)s", + "%(step)sgranduncle/aunt%(inlaw)s", + "great %(step)sgranduncle/aunt%(inlaw)s", + "second great %(step)sgranduncle/aunt%(inlaw)s", + "third great %(step)sgranduncle/aunt%(inlaw)s", + "fourth great %(step)sgranduncle/aunt%(inlaw)s", + "fifth great %(step)sgranduncle/aunt%(inlaw)s", + "sixth great %(step)sgranduncle/aunt%(inlaw)s", + "seventh great %(step)sgranduncle/aunt%(inlaw)s", + "eighth great %(step)sgranduncle/aunt%(inlaw)s", + "ninth great %(step)sgranduncle/aunt%(inlaw)s", + "tenth great %(step)sgranduncle/aunt%(inlaw)s", + "eleventh great %(step)sgranduncle/aunt%(inlaw)s", + "twelfth great %(step)sgranduncle/aunt%(inlaw)s", + "thirteenth great %(step)sgranduncle/aunt%(inlaw)s", + "fourteenth great %(step)sgranduncle/aunt%(inlaw)s", + "fifteenth great %(step)sgranduncle/aunt%(inlaw)s", + "sixteenth great %(step)sgranduncle/aunt%(inlaw)s", + "seventeenth great %(step)sgranduncle/aunt%(inlaw)s", + "eighteenth great %(step)sgranduncle/aunt%(inlaw)s", + "nineteenth great %(step)sgranduncle/aunt%(inlaw)s", "twentieth great %(step)sgranduncle/aunt%(inlaw)s", ] -_nephews_nieces_level = [ "", +_nephews_nieces_level = [ "", "siblings", "nephews/nieces", - "grandnephews/nieces", + "grandnephews/nieces", "great grandnephews/nieces", "second great grandnephews/nieces", "third great grandnephews/nieces", @@ -365,22 +365,22 @@ class RelationshipCalculator(object): REL_FAM_NONBIRTH = 'A' # going up to family, not birth relation REL_FAM_BIRTH_MOTH_ONLY = 'b' # going up to fam, only birth rel to mother REL_FAM_BIRTH_FATH_ONLY = 'c' # going up to fam, only birth rel to father - + REL_FAM_INLAW_PREFIX = 'L' # going to the partner. - + #sibling types NORM_SIB = 0 # same birth parents HALF_SIB_MOTHER = 1 # same mother, father known to be different HALF_SIB_FATHER = 2 # same father, mother known to be different STEP_SIB = 3 # birth parents known to be different UNKNOWN_SIB = 4 # insufficient data to draw conclusion - + #sibling strings STEP = 'step' HALF = 'half-' INLAW = '-in-law' - + #partner types PARTNER_MARRIED = 1 PARTNER_UNMARRIED = 2 @@ -390,7 +390,7 @@ class RelationshipCalculator(object): PARTNER_EX_UNMARRIED = 6 PARTNER_EX_CIVIL_UNION = 7 PARTNER_EX_UNKNOWN_REL = 8 - + def __init__(self): self.signal_keys = [] self.state_signal_key = None @@ -409,7 +409,7 @@ class RelationshipCalculator(object): def set_depth(self, depth): """ - Set how deep relationships must be searched. Input must be an + Set how deep relationships must be searched. Input must be an integer > 0 """ if not depth == self.depth: @@ -421,9 +421,9 @@ class RelationshipCalculator(object): Obtain depth of relationship search """ return self.depth - + DIST_FATHER = "distant %(step)sancestor%(inlaw)s (%(level)d generations)" - + def _get_father(self, level, step='', inlaw=''): """ Internal english method to create relation string @@ -432,10 +432,10 @@ class RelationshipCalculator(object): return self.DIST_FATHER % {'step': step, 'inlaw': inlaw, 'level': level} else: - return _father_level[level] % {'step': step, 'inlaw': inlaw} + return _father_level[level] % {'step': step, 'inlaw': inlaw} DIST_SON = "distant %(step)sdescendant%(inlaw)s (%(level)d generations)" - + def _get_son(self, level, step='', inlaw=''): """ Internal english method to create relation string @@ -447,7 +447,7 @@ class RelationshipCalculator(object): return _son_level[level] % {'step': step, 'inlaw': inlaw} DIST_MOTHER = "distant %(step)sancestor%(inlaw)s (%(level)d generations)" - + def _get_mother(self, level, step='', inlaw=''): """ Internal english method to create relation string @@ -456,7 +456,7 @@ class RelationshipCalculator(object): return self.DIST_MOTHER % {'step': step, 'inlaw': inlaw, 'level': level} else: - return _mother_level[level] % {'step': step, 'inlaw': inlaw} + return _mother_level[level] % {'step': step, 'inlaw': inlaw} DIST_DAUGHTER = "distant %(step)sdescendant%(inlaw)s (%(level)d generations)" @@ -465,7 +465,7 @@ class RelationshipCalculator(object): Internal english method to create relation string """ if level > len(_daughter_level) - 1: - return self.DIST_DAUGHTER % {'step': step, 'inlaw': inlaw, + return self.DIST_DAUGHTER % {'step': step, 'inlaw': inlaw, 'level': level} else: return _daughter_level[level] % {'step': step, 'inlaw': inlaw} @@ -477,7 +477,7 @@ class RelationshipCalculator(object): if level < len(_level_name): return _level_name[level] + ' ' + '%sancestor%s' % (step, inlaw) else: - return "distant %sancestor%s (%d generations)" % (step, inlaw, + return "distant %sancestor%s (%d generations)" % (step, inlaw, level) DIST_CHILD = "distant %(step)sdescendant (%(level)d generations)" @@ -501,7 +501,7 @@ class RelationshipCalculator(object): if level > len(_sister_level) - 1: return self.DIST_AUNT % {'step': step, 'inlaw': inlaw} else: - return _sister_level[level] % {'step': step, 'inlaw': inlaw} + return _sister_level[level] % {'step': step, 'inlaw': inlaw} DIST_UNCLE = "distant %(step)suncle%(inlaw)s" @@ -512,7 +512,7 @@ class RelationshipCalculator(object): if level > len(_brother_level) - 1: return self.DIST_UNCLE % {'step': step, 'inlaw': inlaw} else: - return _brother_level[level] % {'step': step, 'inlaw': inlaw} + return _brother_level[level] % {'step': step, 'inlaw': inlaw} DIST_NEPHEW = "distant %(step)snephew%(inlaw)s" @@ -523,7 +523,7 @@ class RelationshipCalculator(object): if level > len(_nephew_level) - 1: return self.DIST_NEPHEW % {'step': step, 'inlaw': inlaw} else: - return _nephew_level[level] % {'step': step, 'inlaw': inlaw} + return _nephew_level[level] % {'step': step, 'inlaw': inlaw} DIST_NIECE = "distant %(step)sniece%(inlaw)s" @@ -534,7 +534,7 @@ class RelationshipCalculator(object): if level > len(_niece_level) - 1: return self.DIST_NIECE % {'step': step, 'inlaw': inlaw} else: - return _niece_level[level] % {'step': step, 'inlaw': inlaw} + return _niece_level[level] % {'step': step, 'inlaw': inlaw} def _get_cousin(self, level, removed, dir='', step='', inlaw=''): """ @@ -557,14 +557,14 @@ class RelationshipCalculator(object): Internal english method to create relation string """ if level < len(_sibling_level): - return _sibling_level[level] % {'step': step, 'inlaw': inlaw} + return _sibling_level[level] % {'step': step, 'inlaw': inlaw} else: - return self.DIST_SIB % {'step': step, 'inlaw': inlaw} + return self.DIST_SIB % {'step': step, 'inlaw': inlaw} def get_sibling_type(self, db, orig, other): """ Translation free determination of type of orig and other as siblings - The procedure returns sibling types, these can be passed to + The procedure returns sibling types, these can be passed to get_sibling_relationship_string. Only call this method if known that orig and other are siblings """ @@ -616,7 +616,7 @@ class RelationshipCalculator(object): def get_birth_parents(self, db, person): """ Method that returns the birthparents of a person as tuple - (mother handle, father handle), if no known birthparent, the + (mother handle, father handle), if no known birthparent, the handle is replaced by None """ birthfather = None @@ -625,9 +625,9 @@ class RelationshipCalculator(object): family = db.get_family_from_handle(fam) if not family: continue - childrel = [(ref.get_mother_relation(), - ref.get_father_relation()) for ref in - family.get_child_ref_list() + childrel = [(ref.get_mother_relation(), + ref.get_father_relation()) for ref in + family.get_child_ref_list() if ref.ref == person.handle] if not birthmother and childrel[0][0] == ChildRefType.BIRTH: birthmother = family.get_mother_handle() @@ -639,8 +639,8 @@ class RelationshipCalculator(object): def _get_nonbirth_parent_list(self, db, person): """ - Returns a list of handles of parents of which it is known - they are not birth parents. + Returns a list of handles of parents of which it is known + they are not birth parents. So all parents which do not have relation BIRTH or UNKNOWN are returned. """ @@ -649,9 +649,9 @@ class RelationshipCalculator(object): family = db.get_family_from_handle(fam) if not family: continue - childrel = [(ref.get_mother_relation(), - ref.get_father_relation()) for ref in - family.get_child_ref_list() + childrel = [(ref.get_mother_relation(), + ref.get_father_relation()) for ref in + family.get_child_ref_list() if ref.ref == person.handle] if not childrel[0][0] == ChildRefType.BIRTH \ and not childrel[0][0] == ChildRefType.UNKNOWN : @@ -665,9 +665,9 @@ class RelationshipCalculator(object): def _get_spouse_type(self, db, orig, other, all_rel = False): """ Translation free determination if orig and other are partners. - The procedure returns partner types, these can be passed to + The procedure returns partner types, these can be passed to get_partner_relationship_string. - If all_rel=False, returns None or a partner type. + If all_rel=False, returns None or a partner type. If all_rel=True, returns a list, empty if no partner """ val = [] @@ -714,63 +714,63 @@ class RelationshipCalculator(object): return val[-1] else: return None - + def is_spouse(self, db, orig, other, all_rel=False): """ Determine the spouse relation """ spouse_type = self._get_spouse_type(db, orig, other, all_rel) if spouse_type: - return self.get_partner_relationship_string(spouse_type, + return self.get_partner_relationship_string(spouse_type, orig.get_gender(), other.get_gender()) else: return None - + def get_relationship_distance_new(self, db, orig_person, other_person, - all_families=False, - all_dist=False, + all_families=False, + all_dist=False, only_birth=True): """ Return if all_dist == True a 'tuple, string': - (rank, person handle, firstRel_str, firstRel_fam, - secondRel_str, secondRel_fam), msg - or if all_dist == True a 'list of tuple, string': + (rank, person handle, firstRel_str, firstRel_fam, + secondRel_str, secondRel_fam), msg + or if all_dist == True a 'list of tuple, string': [.....], msg: - + .. note:: _new can be removed once all rel_xx modules no longer overwrite get_relationship_distance - + The tuple or list of tuples consists of: - + ============== ===================================================== Element Description ============== ===================================================== - rank Total number of generations from common ancestor to + rank Total number of generations from common ancestor to the two persons, rank is -1 if no relations found person_handle The Common ancestor - firstRel_str String with the path to the common ancestor + firstRel_str String with the path to the common ancestor from orig Person - firstRel_fam Family numbers along the path as a list, eg [0,0,1]. + firstRel_fam Family numbers along the path as a list, eg [0,0,1]. For parent in multiple families, eg [0. [0, 2], 1] - secondRel_str String with the path to the common ancestor + secondRel_str String with the path to the common ancestor from otherPerson - secondRel_fam Family numbers along the path, eg [0,0,1]. + secondRel_fam Family numbers along the path, eg [0,0,1]. For parent in multiple families, eg [0. [0, 2], 1] msg List of messages indicating errors. Empyt list if no errors. ============== ===================================================== - - Example: firstRel_str = 'ffm' and firstRel_fam = [2,0,1] means + + Example: firstRel_str = 'ffm' and firstRel_fam = [2,0,1] means common ancestor is mother of the second family of the father of the first family of the father of the third family. Note that the same person might be present twice if the person is - reached via a different branch too. Path (firstRel_str and + reached via a different branch too. Path (firstRel_str and secondRel_str) will of course be different. - + :param db: database to work on - :param orig_person: first person + :param orig_person: first person :type orig_person: Person Obj :param other_person: second person, relation is sought between first and second person @@ -778,10 +778,10 @@ class RelationshipCalculator(object): :param all_families: if False only Main family is searched, otherwise all families are used :type all_families: bool - :param all_dist: if False only the shortest distance is returned, + :param all_dist: if False only the shortest distance is returned, otherwise all relationships :type all_dist: bool - :param only_birth: if True only parents with birth relation are + :param only_birth: if True only parents with birth relation are considered :type only_birth: bool """ @@ -793,20 +793,20 @@ class RelationshipCalculator(object): self.__all_dist = all_dist self.__only_birth = only_birth self.__crosslinks = False # no crosslinks - + firstRel = -1 secondRel = -1 self.__msg = [] - + common = [] firstMap = {} secondMap = {} rank = 9999999 try: - if (self.storemap and self.stored_map is not None - and self.map_handle == orig_person.handle - and not self.dirtymap): + if (self.storemap and self.stored_map is not None + and self.map_handle == orig_person.handle + and not self.dirtymap): firstMap = self.stored_map self.__maxDepthReached, self.__loopDetected, \ self.__all_families,\ @@ -816,7 +816,7 @@ class RelationshipCalculator(object): else: self.__apply_filter(db, orig_person, '', [], firstMap) self.map_meta = (self.__maxDepthReached, - self.__loopDetected, + self.__loopDetected, self.__all_families, self.__all_dist, self.__only_birth, self.__crosslinks, list(self.__msg)) @@ -830,7 +830,7 @@ class RelationshipCalculator(object): self.stored_map = firstMap self.dirtymap = False self.map_handle = orig_person.handle - + for person_handle in secondMap : if person_handle in firstMap : com = [] @@ -838,7 +838,7 @@ class RelationshipCalculator(object): for rel1, fam1 in zip(firstMap[person_handle][0], firstMap[person_handle][1]): l1 = len(rel1) - for rel2, fam2 in zip(secondMap[person_handle][0], + for rel2, fam2 in zip(secondMap[person_handle][0], secondMap[person_handle][1]): l2 = len(rel2) #collect paths to arrive at common ancestor @@ -851,7 +851,7 @@ class RelationshipCalculator(object): for ranknew, handlenew, rel1new, fam1new, rel2new, fam2new in com : insert = True for rank, handle, rel1, fam1, rel2, fam2 in common : - if ranknew < rank : + if ranknew < rank : break elif ranknew >= rank : #check subset @@ -878,7 +878,7 @@ class RelationshipCalculator(object): index += 1 deletelist.reverse() for index in deletelist: - del common[index] + del common[index] #check for extra messages if self.__maxDepthReached : self.__msg += [_('Family Tree reaches back more than the maximum ' @@ -894,7 +894,7 @@ class RelationshipCalculator(object): secondFam = common[0][5] return (rank, person_handle, firstRel, firstFam, secondRel, secondFam),\ self.__msg - if common : + if common : #list with tuples (rank, handle person,rel_str_orig,rel_fam_orig, # rel_str_other,rel_fam_str) and messages return common, self.__msg @@ -902,17 +902,17 @@ class RelationshipCalculator(object): return (-1, None, '', [], '', []), self.__msg else : return [(-1, None, '', [], '', [])], self.__msg - + def __apply_filter(self, db, person, rel_str, rel_fam, pmap, depth=1, stoprecursemap=None): """ Typically this method is called recursively in two ways: - First method is stoprecursemap= None + First method is stoprecursemap= None In this case a recursemap is builded by storing all data. - + Second method is with a stoprecursemap given - In this case parents are recursively looked up. If present in - stoprecursemap, a common ancestor is found, and the method can + In this case parents are recursively looked up. If present in + stoprecursemap, a common ancestor is found, and the method can stop looking further. If however self.__crosslinks == True, the data of first contains loops, and parents will be looked up anyway an stored if common. At end the doubles @@ -920,7 +920,7 @@ class RelationshipCalculator(object): """ if person is None or not person.handle : return - + if depth > self.__max_depth: self.__maxDepthReached = True #print('Maximum ancestor generations ('+str(depth)+') reached', \ @@ -928,7 +928,7 @@ class RelationshipCalculator(object): # 'Stopping relation algorithm.') return depth += 1 - + commonancestor = False store = True #normally we store all parents if stoprecursemap: @@ -937,8 +937,8 @@ class RelationshipCalculator(object): commonancestor = True store = True - #add person to the map, take into account that person can be obtained - #from different sides + #add person to the map, take into account that person can be obtained + #from different sides if person.handle in pmap: #person is already a grandparent in another branch, we already have # had lookup of all parents, we call that a crosslink @@ -948,34 +948,34 @@ class RelationshipCalculator(object): pmap[person.handle][1] += [rel_fam] #check if there is no loop father son of his son, ... # loop means person is twice reached, same rel_str in begin - for rel1 in pmap[person.handle][0]: + for rel1 in pmap[person.handle][0]: for rel2 in pmap[person.handle][0] : if len(rel1) < len(rel2) and \ rel1 == rel2[:len(rel1)]: #loop, keep one message in storage! self.__loopDetected = True - self.__msg += [_("Relationship loop detected:") + " " + - _("Person %(person)s connects to himself via %(relation)s") % - {'person' : person.get_primary_name().get_name(), + self.__msg += [_("Relationship loop detected:") + " " + + _("Person %(person)s connects to himself via %(relation)s") % + {'person' : person.get_primary_name().get_name(), 'relation' : rel2[len(rel1):] }] return elif store: pmap[person.handle] = [[rel_str], [rel_fam]] - - #having added person to the pmap, we only look up recursively to + + #having added person to the pmap, we only look up recursively to # parents if this person is not common relative # if however the first map has crosslinks, we need to continue reduced if commonancestor and not self.__crosslinks : #don't continue search, great speedup! - return + return family_handles = [] main = person.get_main_parents_family_handle() if main : family_handles = [main] if self.__all_families : - family_handles = person.get_parent_family_handle_list() - + family_handles = person.get_parent_family_handle_list() + try: parentstodo = {} fam = 0 @@ -985,15 +985,15 @@ class RelationshipCalculator(object): if not family: continue #obtain childref for this person - childrel = [(ref.get_mother_relation(), - ref.get_father_relation()) for ref in - family.get_child_ref_list() + childrel = [(ref.get_mother_relation(), + ref.get_father_relation()) for ref in + family.get_child_ref_list() if ref.ref == person.handle] fhandle = family.father_handle mhandle = family.mother_handle - for data in [(fhandle, self.REL_FATHER, - self.REL_FATHER_NOTBIRTH, childrel[0][1]), - (mhandle, self.REL_MOTHER, + for data in [(fhandle, self.REL_FATHER, + self.REL_FATHER_NOTBIRTH, childrel[0][1]), + (mhandle, self.REL_MOTHER, self.REL_MOTHER_NOTBIRTH, childrel[0][0])]: if data[0] and data[0] not in parentstodo : persontodo = db.get_person_from_handle(data[0]) @@ -1004,7 +1004,7 @@ class RelationshipCalculator(object): else : addstr = '' if addstr : - parentstodo[data[0]] = (persontodo, + parentstodo[data[0]] = (persontodo, rel_str + addstr, rel_fam_new) elif data [0] and data[0] in parentstodo: @@ -1052,12 +1052,12 @@ class RelationshipCalculator(object): get_relationship_distance_new. Common ancestors in the same family are collapsed to one entry, changing the person paths to family paths, eg 'mf' and 'mm' become 'ma' - - relations : list of relations as returned by + + relations : list of relations as returned by get_relationship_distance_new with all_dist = True - - returns : the same data as relations, but collapsed, hence the - handle entry is now a list of handles, and the + + returns : the same data as relations, but collapsed, hence the + handle entry is now a list of handles, and the path to common ancestors can now contain family identifiers (eg 'a', ...) In the case of sibling, this is replaced by family @@ -1081,14 +1081,14 @@ class RelationshipCalculator(object): rela2 = relation[2] rela4 = relation[4] if relation[2] and relation[2][-1] == self.REL_SIBLING: - #sibling will be the unique common ancestor, + #sibling will be the unique common ancestor, #change to a family with unknown handle for common ancestor rela2 = relation[2][:-1] + self.REL_FAM_BIRTH rela4 = relation[4] + self.REL_FAM_BIRTH relfamsec = relfamsec + [relfamfirst[-1]] relstrsec = relation[4][:-1] commonhandle = [] - + # a unique path to family of common person: familypaths = [] if relfamfirst and isinstance(relfamfirst[-1], list): @@ -1096,17 +1096,17 @@ class RelationshipCalculator(object): for val1 in relfamfirst[-1]: for val2 in relfamsec[-1]: familypaths.append((relstrfirst, relstrsec, - relfamfirst[:-1] + [val1], + relfamfirst[:-1] + [val1], relfamsec[:-1] + [val2])) else: for val1 in relfamfirst[-1]: familypaths.append((relstrfirst, relstrsec, - relfamfirst[:-1] + [val1], + relfamfirst[:-1] + [val1], relfamsec)) elif relfamsec and isinstance(relfamsec[-1], list): for val2 in relfamsec[-1]: familypaths.append((relstrfirst, relstrsec, - relfamfirst, + relfamfirst, relfamsec[:-1] + [val2])) else: familypaths.append((relstrfirst, relstrsec, @@ -1117,30 +1117,30 @@ class RelationshipCalculator(object): posfam = existing_path.index(familypath) except ValueError: posfam = None - #if relstr is '', the ancestor is unique, if posfam None, + #if relstr is '', the ancestor is unique, if posfam None, # first time we see this family path - if (posfam is not None and relstrfirst is not None and + if (posfam is not None and relstrfirst is not None and relstrsec is not None): - # We already have a common ancestor of this family, just + # We already have a common ancestor of this family, just # add the other, setting correct family relation. tmp = commonnew[posfam] frstcomstr = rela2[-1] scndcomstr = tmp[2][-1] - newcomstra = self._famrel_from_persrel(frstcomstr, + newcomstra = self._famrel_from_persrel(frstcomstr, scndcomstr) frstcomstr = rela4[-1] scndcomstr = tmp[4][-1] - newcomstrb = self._famrel_from_persrel(frstcomstr, + newcomstrb = self._famrel_from_persrel(frstcomstr, scndcomstr) - commonnew[posfam] = (tmp[0], tmp[1]+commonhandle, - rela2[:-1]+newcomstra, + commonnew[posfam] = (tmp[0], tmp[1]+commonhandle, + rela2[:-1]+newcomstra, tmp[3], rela4[:-1]+newcomstrb, tmp[5]) else : existing_path.append(familypath) commonnew.append((relation[0], commonhandle, rela2, - familypath[2], rela4, familypath[3]) + familypath[2], rela4, familypath[3]) ) #we now have multiple person handles, single families, now collapse # families again if all else equal @@ -1172,12 +1172,12 @@ class RelationshipCalculator(object): break if not found: collapsed.append(rel) - + return collapsed def _famrel_from_persrel(self, persrela, persrelb): """ - Conversion from eg 'f' and 'm' to 'a', so relation to the two + Conversion from eg 'f' and 'm' to 'a', so relation to the two persons of a common family is converted to a family relation """ if persrela == persrelb: @@ -1193,33 +1193,33 @@ class RelationshipCalculator(object): (persrelb == self.REL_FATHER and persrela == self.REL_MOTHER_NOTBIRTH): return self.REL_FAM_BIRTH_FATH_ONLY #catch calling with family relations already, return val - if (persrela == self.REL_FAM_BIRTH or + if (persrela == self.REL_FAM_BIRTH or persrela == self.REL_FAM_BIRTH_FATH_ONLY or - persrela == self.REL_FAM_BIRTH_MOTH_ONLY or + persrela == self.REL_FAM_BIRTH_MOTH_ONLY or persrela == self.REL_FAM_NONBIRTH): return persrela - if (persrelb == self.REL_FAM_BIRTH or + if (persrelb == self.REL_FAM_BIRTH or persrelb == self.REL_FAM_BIRTH_FATH_ONLY or - persrelb == self.REL_FAM_BIRTH_MOTH_ONLY or + persrelb == self.REL_FAM_BIRTH_MOTH_ONLY or persrelb == self.REL_FAM_NONBIRTH): return persrelb return self.REL_FAM_NONBIRTH def only_birth(self, path): """ - Given a path to common ancestor. Return True if only birth + Given a path to common ancestor. Return True if only birth relations, False otherwise """ only_birth = True for str in path: - only_birth = only_birth and (str not in [self.REL_FAM_NONBIRTH, + only_birth = only_birth and (str not in [self.REL_FAM_NONBIRTH, self.REL_FATHER_NOTBIRTH, self.REL_MOTHER_NOTBIRTH]) return only_birth - def get_one_relationship(self, db, orig_person, other_person, + def get_one_relationship(self, db, orig_person, other_person, extra_info=False, olocale=glocale): """ - Returns a string representing the most relevant relationship between + Returns a string representing the most relevant relationship between the two people. If extra_info = True, extra information is returned: (relation_string, distance_common_orig, distance_common_other) @@ -1243,13 +1243,13 @@ class RelationshipCalculator(object): if is_spouse: rel_str = is_spouse stop = True - + if stop: if extra_info: return (rel_str, -1, -1) else: return rel_str - + data, msg = self.get_relationship_distance_new( db, orig_person, other_person, all_dist=True, @@ -1277,7 +1277,7 @@ class RelationshipCalculator(object): if dist_orig == dist_other == 1: rel_str = self.get_sibling_relationship_string( self.get_sibling_type( - db, orig_person, other_person), + db, orig_person, other_person), orig_person.get_gender(), other_person.get_gender()) else: @@ -1286,13 +1286,13 @@ class RelationshipCalculator(object): orig_person.get_gender(), other_person.get_gender(), rel[2], rel[4], - only_birth=birth, - in_law_a=False, + only_birth=birth, + in_law_a=False, in_law_b=False) else: order = [self.REL_FAM_BIRTH, self.REL_FAM_BIRTH_MOTH_ONLY, self.REL_FAM_BIRTH_FATH_ONLY, self.REL_MOTHER, - self.REL_FATHER, self.REL_SIBLING, self.REL_FAM_NONBIRTH, + self.REL_FATHER, self.REL_SIBLING, self.REL_FAM_NONBIRTH, self.REL_MOTHER_NOTBIRTH, self.REL_FATHER_NOTBIRTH] orderbest = order.index(self.REL_MOTHER) for relother in databest: @@ -1331,7 +1331,7 @@ class RelationshipCalculator(object): if dist_orig == dist_other == 1: rel_str = self.get_sibling_relationship_string( self.get_sibling_type( - db, orig_person, other_person), + db, orig_person, other_person), orig_person.get_gender(), other_person.get_gender()) else: @@ -1340,8 +1340,8 @@ class RelationshipCalculator(object): orig_person.get_gender(), other_person.get_gender(), rel[2], rel[4], - only_birth=birth, - in_law_a=False, + only_birth=birth, + in_law_a=False, in_law_b=False) if extra_info: return (rel_str, dist_orig, dist_other) @@ -1366,7 +1366,7 @@ class RelationshipCalculator(object): if is_spouse: relstrings.append(is_spouse) commons[is_spouse] = [] - + data, msg = self.get_relationship_distance_new( db, orig_person, other_person, all_dist=True, @@ -1388,7 +1388,7 @@ class RelationshipCalculator(object): if dist_orig == dist_other == 1: rel_str = self.get_sibling_relationship_string( self.get_sibling_type( - db, orig_person, other_person), + db, orig_person, other_person), orig_person.get_gender(), other_person.get_gender()) else: @@ -1397,8 +1397,8 @@ class RelationshipCalculator(object): orig_person.get_gender(), other_person.get_gender(), rel2, rel4, - only_birth=birth, - in_law_a=False, + only_birth=birth, + in_law_a=False, in_law_b=False) if not rel_str in relstrings: relstrings.append(rel_str) @@ -1424,26 +1424,26 @@ class RelationshipCalculator(object): Provide a string that describes the relationsip between a person, and a group of people with the same relationship. E.g. "grandparents" or "children". - + Ga and Gb can be used to mathematically calculate the relationship. .. seealso:: http://en.wikipedia.org/wiki/Cousin#Mathematical_definitions - - :param Ga: The number of generations between the main person and the + + :param Ga: The number of generations between the main person and the common ancestor. :type Ga: int :param Gb: The number of generations between the group of people and the common ancestor :type Gb: int :param reltocommon_a: relation path to common ancestor or common - Family for person a. + Family for person a. Note that length = Ga - :type reltocommon_a: str + :type reltocommon_a: str :param reltocommon_b: relation path to common ancestor or common - Family for person b. + Family for person b. Note that length = Gb - :type reltocommon_b: str + :type reltocommon_b: str :param only_birth: True if relation between a and b is by birth only False otherwise :type only_birth: bool @@ -1489,53 +1489,53 @@ class RelationshipCalculator(object): else: rel_str = "distant cousins" elif Ga > 1 and Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. if Gb <= len(_level_name) and (Ga-Gb) < len(_removed_level): - rel_str = "%s cousins%s (up)" % ( _level_name[Gb-1], + rel_str = "%s cousins%s (up)" % ( _level_name[Gb-1], _removed_level[Ga-Gb] ) else: rel_str = "distant cousins" elif Gb > 1 and Gb > Ga: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. if Ga <= len(_level_name) and (Gb-Ga) < len(_removed_level): - rel_str = "%s cousins%s (down)" % ( _level_name[Ga-1], + rel_str = "%s cousins%s (down)" % ( _level_name[Ga-1], _removed_level[Gb-Ga] ) else: rel_str = "distant cousins" - + if in_law_b == True: rel_str = "spouses of %s" % rel_str - + return rel_str - + def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): """ Provide a string that describes the relationsip between a person, and another person. E.g. "grandparent" or "child". - + To be used as: 'person b is the grandparent of a', this will be in translation string: 'person b is the %(relation)s of a' - Note that languages with gender should add 'the' inside the + Note that languages with gender should add 'the' inside the translation, so eg in french: 'person b est %(relation)s de a' where relation will be here: le grandparent - + Ga and Gb can be used to mathematically calculate the relationship. - + .. seealso:: http://en.wikipedia.org/wiki/Cousin#Mathematical_definitions - + Some languages need to know the specific path to the common ancestor. - Those languages should use reltocommon_a and reltocommon_b which is + Those languages should use reltocommon_a and reltocommon_b which is a string like 'mfmf'. - + The possible string codes are: ======================= =========================================== @@ -1551,27 +1551,27 @@ class RelationshipCalculator(object): REL_FAM_BIRTH_FATH_ONLY # going up to fam, only birth rel to father ======================= =========================================== - Prefix codes are stripped, so REL_FAM_INLAW_PREFIX is not present. + Prefix codes are stripped, so REL_FAM_INLAW_PREFIX is not present. If the relation starts with the inlaw of the person a, then 'in_law_a' is True, if it starts with the inlaw of person b, then 'in_law_b' is True. - Also REL_SIBLING (# going sideways to sibling (no parents)) is not - passed to this routine. The collapse_relations changes this to a - family relation. + Also REL_SIBLING (# going sideways to sibling (no parents)) is not + passed to this routine. The collapse_relations changes this to a + family relation. - Hence, calling routines should always strip REL_SIBLING and + Hence, calling routines should always strip REL_SIBLING and REL_FAM_INLAW_PREFIX before calling get_single_relationship_string() Note that only_birth=False, means that in the reltocommon one of the NOTBIRTH specifiers is present. - The REL_FAM identifiers mean that the relation is not via a common - ancestor, but via a common family (note that that is not possible for + The REL_FAM identifiers mean that the relation is not via a common + ancestor, but via a common family (note that that is not possible for direct descendants or direct ancestors!). If the relation to one of the parents in that common family is by birth, then 'only_birth' is not set to False. The only_birth() method is normally used for this. - - :param Ga: The number of generations between the main person and the + + :param Ga: The number of generations between the main person and the common ancestor. :type Ga: int :param Gb: The number of generations between the other person and the @@ -1582,13 +1582,13 @@ class RelationshipCalculator(object): :param gender_b: gender of person b :type gender_b: int gender :param reltocommon_a: relation path to common ancestor or common - Family for person a. + Family for person a. Note that length = Ga - :type reltocommon_a: str + :type reltocommon_a: str :param reltocommon_b: relation path to common ancestor or common - Family for person b. + Family for person b. Note that length = Gb - :type reltocommon_b: str + :type reltocommon_b: str :param in_law_a: True if path to common ancestors is via the partner of person a :type in_law_a: bool @@ -1600,10 +1600,10 @@ class RelationshipCalculator(object): :type only_birth: bool :returns: A string describing the relationship between the two people :rtype: str - - .. note:: 1. the self.REL_SIBLING should not be passed to this routine, + + .. note:: 1. the self.REL_SIBLING should not be passed to this routine, so we should not check on it. All other self. - 2. for better determination of siblings, use if Ga=1=Gb + 2. for better determination of siblings, use if Ga=1=Gb get_sibling_relationship_string """ if only_birth: @@ -1657,32 +1657,32 @@ class RelationshipCalculator(object): rel_str = "distant %snephews/nieces%s" % (step, inlaw) elif Ga == Gb: # a and b cousins in the same generation - rel_str = self._get_cousin(Ga-1, 0, dir = '', step=step, + rel_str = self._get_cousin(Ga-1, 0, dir = '', step=step, inlaw=inlaw) elif Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. - rel_str = self._get_cousin(Gb-1, Ga-Gb, dir = ' (up)', + rel_str = self._get_cousin(Gb-1, Ga-Gb, dir = ' (up)', step=step, inlaw=inlaw) elif Gb > Ga: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. - rel_str = self._get_cousin(Ga-1, Gb-Ga, dir = ' (down)', + rel_str = self._get_cousin(Ga-1, Gb-Ga, dir = ' (down)', step=step, inlaw=inlaw) return rel_str - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): """ Determine the string giving the relation between two siblings of type sib_type. Eg: b is the brother of a Here 'brother' is the string we need to determine - This method gives more details about siblings than + This method gives more details about siblings than get_single_relationship_string can do. - + .. warning:: DON'T TRANSLATE THIS PROCEDURE IF LOGIC IS EQUAL IN YOUR LANGUAGE, AND SAME METHODS EXIST (get_uncle, get_aunt, get_sibling) @@ -1718,7 +1718,7 @@ class RelationshipCalculator(object): .. warning:: DON'T TRANSLATE THIS PROCEDURE IF LOGIC IS EQUAL IN YOUR LANGUAGE, AS GETTEXT IS ALREADY USED ! """ - #english only needs gender of b, we don't guess if unknown like in old + #english only needs gender of b, we don't guess if unknown like in old # procedure as that is stupid in present day cases! gender = gender_b @@ -1798,16 +1798,16 @@ class RelationshipCalculator(object): if self.__db_connected: return assert(len(self.signal_keys)==0) - self.state_signal_key = dbstate.connect('database-changed', + self.state_signal_key = dbstate.connect('database-changed', self._dbchange_callback) self.__connect_db_signals(dbstate.db) - + def __connect_db_signals(self, db): signals = ['person-add', 'person-update', 'person-delete', - 'person-rebuild', 'family-add', 'family-update', + 'person-rebuild', 'family-add', 'family-update', 'family-delete', 'family-rebuild', 'database-changed'] for name in signals: - self.signal_keys.append(db.connect(name, + self.signal_keys.append(db.connect(name, self._datachange_callback)) self.storemap = True self.__db_connected = True @@ -1824,7 +1824,7 @@ class RelationshipCalculator(object): def _dbchange_callback(self, db): """ - When database changes, the map can no longer be used. + When database changes, the map can no longer be used. Connects must be remade """ self.dirtymap = True @@ -1833,9 +1833,9 @@ class RelationshipCalculator(object): def _datachange_callback(self, list=[]): """ - When data in database changes, the map can no longer be used. - As the map might be in use or might be generated at the moment, - this method sets a dirty flag. Before reusing the map, this flag + When data in database changes, the map can no longer be used. + As the map might be in use or might be generated at the moment, + this method sets a dirty flag. Before reusing the map, this flag will be checked """ self.dirtymap = True @@ -1849,7 +1849,7 @@ class RelationshipCalculator(object): __RELCALC_CLASS = None def get_relationship_calculator(reinit=False, clocale=glocale): - """ + """ Return the relationship calculator for the current language. If clocale is passed in (a GrampsLocale) then that language will be used. @@ -1859,7 +1859,7 @@ def get_relationship_calculator(reinit=False, clocale=glocale): """ global __RELCALC_CLASS - + if __RELCALC_CLASS is None or reinit: lang = clocale.language[0] __RELCALC_CLASS = RelationshipCalculator @@ -2250,27 +2250,27 @@ def _testsibling(rc): (rc.HALF_SIB_FATHER, 'half sib father side'), (rc.STEP_SIB, 'step sib'), (rc.UNKNOWN_SIB, 'undetermined sib')] FMT = '%+50s' - for gendr, strgen in [(MALE, 'male'), - (FEMALE, 'female'), + for gendr, strgen in [(MALE, 'male'), + (FEMALE, 'female'), (UNKNOWN, 'unknown')]: for inlaw in [False, True]: for sibt, str in vals: print(FMT % rc.get_sibling_relationship_string( - sibt, MALE, gendr, + sibt, MALE, gendr, in_law_a = inlaw) + ' |info:', str, strgen) def _test_spouse(rc): FMT = '%+50s' vals = [(rc.PARTNER_MARRIED, 'married'), (rc.PARTNER_UNMARRIED, 'unmarried'), - (rc.PARTNER_CIVIL_UNION, 'civil union'), + (rc.PARTNER_CIVIL_UNION, 'civil union'), (rc.PARTNER_UNKNOWN_REL, 'unknown rel'), - (rc.PARTNER_EX_MARRIED, 'ex-married'), + (rc.PARTNER_EX_MARRIED, 'ex-married'), (rc.PARTNER_EX_UNMARRIED, 'ex-unmarried'), - (rc.PARTNER_EX_CIVIL_UNION, 'ex civil union'), + (rc.PARTNER_EX_CIVIL_UNION, 'ex civil union'), (rc.PARTNER_EX_UNKNOWN_REL, 'ex unknown rel')] - for gender, strgen in [(MALE, 'male'), - (FEMALE, 'female'), + for gender, strgen in [(MALE, 'male'), + (FEMALE, 'female'), (UNKNOWN, 'unknown')] : for spouse_type, str in vals: print(FMT % rc.get_partner_relationship_string( @@ -2332,20 +2332,20 @@ Please enter a test number and press Enter for continue: if testNum == 0 or testNum == 6: print('\n\n=== Test partner types ===') _test_spouse(rc) - + if __name__ == "__main__": # Test function. Call it as follows from the command line (so as to find # imported modules): - # export PYTHONPATH=/path/to/gramps/src python src/plugins/rel_fr.py + # export PYTHONPATH=/path/to/gramps/src python src/plugins/rel_fr.py # (Above not needed here) - + """ - TRANSLATORS, copy this if statement at the bottom of your + TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, after adding: 'from Relationship import test' and test your work with: - export PYTHONPATH=/path/to/gramps/src + export PYTHONPATH=/path/to/gramps/src python src/plugins/rel_xx.py - + See eg rel_fr.py at the bottom """ rc = RelationshipCalculator() diff --git a/gramps/gen/simple/_simpleaccess.py b/gramps/gen/simple/_simpleaccess.py index 49699ecfc..a857a9559 100644 --- a/gramps/gen/simple/_simpleaccess.py +++ b/gramps/gen/simple/_simpleaccess.py @@ -23,7 +23,7 @@ """ Provide a simplified database access interface to the Gramps database. """ -from ..lib import (Person, Family, Event, Source, Place, Citation, +from ..lib import (Person, Family, Event, Source, Place, Citation, MediaObject, Repository, Note, Date, Tag) from ..lib.handle import Handle from ..datehandler import displayer @@ -46,17 +46,17 @@ class SimpleAccess(object): """ Provide a simplified database access system. This system has been designed to ease the development of reports. - - The user needs to take care when using this interface. Since it returns real + + The user needs to take care when using this interface. Since it returns real objects instead of database references, it can consume a significant amount of memory if the user is not careful. - + **Example** - + A typical system of usage would be:: - + sa = SimpleAccess(database) - + print "Person : ", sa.name(person) print "Gender : ", sa.gender(person) print "Birth date : ", sa.birth_date(person) @@ -71,10 +71,10 @@ class SimpleAccess(object): print "Marriage Place: ", sa.marriage_place(person) for child in sa.children(person): print "Child : ", sa.name(child) - + # Print out burial and baptism events for event in sa.events( person , [ "Burial", "Baptism" ]): - print "Event : ", sa.event_type(event), sa.event_date(event), + print "Event : ", sa.event_type(event), sa.event_date(event), print sa.event_place(event) This would produce an output that looks like:: @@ -107,7 +107,7 @@ class SimpleAccess(object): def __init__(self, dbase): """ Initialize the SimpleAccess object with the database that will be used. - + :param dbase: Gramps database object :type dbase: DbBase """ @@ -124,7 +124,7 @@ class SimpleAccess(object): """ if isinstance(person, str): person = self.dbase.get_person_from_handle(person) - assert(person is None or isinstance(person, Person)) + assert(person is None or isinstance(person, Person)) if person: return name_displayer.display(person) else: @@ -139,15 +139,15 @@ class SimpleAccess(object): :return: Returns the name of the person based of the program preferences :rtype: unicode """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) - assert(person is None or isinstance(person, Person)) + assert(person is None or isinstance(person, Person)) if person: surname = person.get_primary_name().get_surname() return surname or config.get('preferences.no-surname-text') else: return '' - + def first_name(self, person): """ Return the first name of the person, or and empty string if the person @@ -159,7 +159,7 @@ class SimpleAccess(object): preferences :rtype: unicode """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) assert(person is None or isinstance(person, Person)) if person: @@ -190,7 +190,7 @@ class SimpleAccess(object): :return: Returns a string indentifying the person's gender :rtype: unicode """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) assert(person is None or isinstance(person, Person)) if person: @@ -318,7 +318,7 @@ class SimpleAccess(object): :return: The spouse identified as the person's primary spouse :rtype: :py:class:`.Person` """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) assert(person is None or isinstance(person, Person)) @@ -346,7 +346,7 @@ class SimpleAccess(object): person and his/per primary spouse. :rtype: unicode """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) assert(person is None or isinstance(person, Person)) @@ -370,7 +370,7 @@ class SimpleAccess(object): his/her spouse where married. :rtype: unicode """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) assert(person is None or isinstance(person, Person)) @@ -382,9 +382,9 @@ class SimpleAccess(object): if family: reflist = family.get_event_ref_list() if reflist: - elist = [ self.dbase.get_event_from_handle(ref.ref) + elist = [ self.dbase.get_event_from_handle(ref.ref) for ref in reflist ] - events = [ evnt for evnt in elist + events = [ evnt for evnt in elist if event.type == EventType.MARRIAGE ] if events: return place_displayer.display_event(self.dbase, events[0]) @@ -401,7 +401,7 @@ class SimpleAccess(object): his/her spouse where married. :rtype: unicode """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) assert(person is None or isinstance(person, Person)) @@ -413,9 +413,9 @@ class SimpleAccess(object): if family: reflist = family.get_event_ref_list() if reflist: - elist = [ self.dbase.get_event_from_handle(ref.ref) + elist = [ self.dbase.get_event_from_handle(ref.ref) for ref in reflist ] - events = [ evnt for evnt in elist + events = [ evnt for evnt in elist if event.type == EventType.MARRIAGE ] if events: date_obj = events[0].get_date_object() @@ -440,11 +440,11 @@ class SimpleAccess(object): if family_handle_list: family_id = family_handle_list[0] family = self.dbase.get_family_from_handle(family_id) - - return [ self.dbase.get_person_from_handle(hndl.ref) + + return [ self.dbase.get_person_from_handle(hndl.ref) for hndl in family.get_child_ref_list() ] elif isinstance(obj, Family): - return [ self.dbase.get_person_from_handle(hndl.ref) + return [ self.dbase.get_person_from_handle(hndl.ref) for hndl in obj.get_child_ref_list() ] return [] @@ -483,7 +483,7 @@ class SimpleAccess(object): return self.__family_parent(obj, Family.get_mother_handle) else: return None - + def birth_date(self, person): """ Return a string indicating the date when the person's birth. @@ -493,7 +493,7 @@ class SimpleAccess(object): :return: Returns a string indicating the date when the person's birth. :rtype: unicode """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) return self.__event_date(person, Person.get_birth_ref) @@ -506,7 +506,7 @@ class SimpleAccess(object): :return: Returns the date when the person's birth. :rtype: :py:class:`.Date` """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) return self.__event_date_obj(person, Person.get_birth_ref) @@ -520,7 +520,7 @@ class SimpleAccess(object): :return: Returns the date when the person's birth or fallback. :rtype: :py:class:`.Date` """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) event = get_birth_or_fallback(self.dbase, person, "%s") if get_event: @@ -539,7 +539,7 @@ class SimpleAccess(object): :return: Returns a string indicating the place of the person's birth. :rtype: unicode """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) return self.__event_place(person, Person.get_birth_ref) @@ -565,7 +565,7 @@ class SimpleAccess(object): :return: Returns the date when the person's death. :rtype: :py:class:`.Date` """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) return self.__event_date_obj(person, Person.get_death_ref) @@ -578,7 +578,7 @@ class SimpleAccess(object): :return: Returns the date of the person's death or fallback. :rtype: :py:class:`.Date` """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) event = get_death_or_fallback(self.dbase, person, "%s") if get_event: @@ -597,7 +597,7 @@ class SimpleAccess(object): :return: Returns a string indicating the place of the person's death. :rtype: unicode """ - if isinstance(person, str): + if isinstance(person, str): person = self.dbase.get_person_from_handle(person) return self.__event_place(person, Person.get_death_ref) @@ -693,11 +693,11 @@ class SimpleAccess(object): if obj: event_handles = [ ref.ref for ref in obj.get_event_ref_list() ] - events = [ self.dbase.get_event_from_handle(h) + events = [ self.dbase.get_event_from_handle(h) for h in event_handles ] if restrict: restrict = [ r.lower() for r in restrict ] - events = [ event for event in events + events = [ event for event in events if str(event.get_type()).lower() in restrict ] return events else: @@ -733,10 +733,10 @@ class SimpleAccess(object): """ if isinstance(person, str): person = self.dbase.get_person_from_handle(person) - assert(person is None or isinstance(person, Person)) - + assert(person is None or isinstance(person, Person)) + if person: - return [ self.dbase.get_family_from_handle(handle) + return [ self.dbase.get_family_from_handle(handle) for handle in person.get_family_handle_list() ] return [] @@ -753,21 +753,21 @@ class SimpleAccess(object): if isinstance(person, str): person = self.dbase.get_person_from_handle(person) assert(person is None or isinstance(person, Person)) - + if person: - return [ self.dbase.get_family_from_handle(handle) + return [ self.dbase.get_family_from_handle(handle) for handle in person.get_parent_family_handle_list() ] return [] def __all_objects(self, gen_cursor, get_object): """ - Return a all the objects of a particular type in the database, one - at a time as an iterator. The user can treat this just like a list. + Return a all the objects of a particular type in the database, one + at a time as an iterator. The user can treat this just like a list. :return: list of objects of a particular type in the database :rtype: list """ - + with gen_cursor() as cursor: for key, data in cursor: yield get_object(key) @@ -783,7 +783,7 @@ class SimpleAccess(object): :return: list of people in the database :rtype: list """ - + with self.dbase.get_person_cursor() as cursor: # data[3] is primary_name; data[3][5][0][0] is surname slist = sorted((data[3][5][0][0], key) for key, data in cursor) @@ -803,7 +803,7 @@ class SimpleAccess(object): :return: list of families in the database :rtype: list """ - return self.__all_objects(self.dbase.get_family_cursor, + return self.__all_objects(self.dbase.get_family_cursor, self.dbase.get_family_from_handle) def all_events(self): @@ -817,7 +817,7 @@ class SimpleAccess(object): :return: list of events in the database :rtype: list """ - return self.__all_objects(self.dbase.get_event_cursor, + return self.__all_objects(self.dbase.get_event_cursor, self.dbase.get_event_from_handle) def all_sources(self): @@ -828,7 +828,7 @@ class SimpleAccess(object): :return: list of sources in the database :rtype: list """ - return self.__all_objects(self.dbase.get_source_cursor, + return self.__all_objects(self.dbase.get_source_cursor, self.dbase.get_source_from_handle) def all_citations(self): @@ -839,7 +839,7 @@ class SimpleAccess(object): :return: list of citations in the database :rtype: list """ - return self.__all_objects(self.dbase.get_citation_cursor, + return self.__all_objects(self.dbase.get_citation_cursor, self.dbase.get_citation_from_handle) def all_repositories(self): @@ -850,7 +850,7 @@ class SimpleAccess(object): :return: list of repositories in the database :rtype: list """ - return self.__all_objects(self.dbase.get_repository_cursor, + return self.__all_objects(self.dbase.get_repository_cursor, self.dbase.get_repository_from_handle) def all_media(self): @@ -861,7 +861,7 @@ class SimpleAccess(object): :return: list of media in the database :rtype: list """ - return self.__all_objects(self.dbase.get_media_cursor, + return self.__all_objects(self.dbase.get_media_cursor, self.dbase.get_object_from_handle) def all_places(self): @@ -872,7 +872,7 @@ class SimpleAccess(object): :return: list of places in the database :rtype: list """ - return self.__all_objects(self.dbase.get_place_cursor, + return self.__all_objects(self.dbase.get_place_cursor, self.dbase.get_place_from_handle) def all_notes(self): @@ -883,7 +883,7 @@ class SimpleAccess(object): :return: list of notes in the database :rtype: list """ - return self.__all_objects(self.dbase.get_note_cursor, + return self.__all_objects(self.dbase.get_note_cursor, self.dbase.get_note_from_handle) def all_tags(self): @@ -894,7 +894,7 @@ class SimpleAccess(object): :return: list of tags in the database :rtype: list """ - return self.__all_objects(self.dbase.get_tag_cursor, + return self.__all_objects(self.dbase.get_tag_cursor, self.dbase.get_tag_from_handle) def title(self, source): @@ -954,7 +954,7 @@ class SimpleAccess(object): def display(self, object_class, prop, value): """ Given a object_class, prop, and value return a display string - describing object. + describing object. :param object_class: "Person", "Source", etc. :param prop: "gramps_id", or "handle" @@ -965,44 +965,44 @@ class SimpleAccess(object): [prop + "_func"](value) if obj: if isinstance(obj, Person): - return "%s: %s [%s]" % (_(object_class), - self.name(obj), + return "%s: %s [%s]" % (_(object_class), + self.name(obj), self.gid(obj)) elif isinstance(obj, Event): - return "%s: %s [%s]" % (_(object_class), + return "%s: %s [%s]" % (_(object_class), self.event_type(obj), self.gid(obj)) elif isinstance(obj, Family): - return "%s: %s/%s [%s]" % (_(object_class), - self.name(self.mother(obj)), - self.name(self.father(obj)), + return "%s: %s/%s [%s]" % (_(object_class), + self.name(self.mother(obj)), + self.name(self.father(obj)), self.gid(obj)) elif isinstance(obj, MediaObject): - return "%s: %s [%s]" % (_(object_class), - obj.desc, + return "%s: %s [%s]" % (_(object_class), + obj.desc, self.gid(obj)) elif isinstance(obj, Source): - return "%s: %s [%s]" % (_(object_class), - self.title(obj), + return "%s: %s [%s]" % (_(object_class), + self.title(obj), self.gid(obj)) elif isinstance(obj, Citation): - return "%s: [%s]" % (_(object_class), + return "%s: [%s]" % (_(object_class), self.gid(obj)) elif isinstance(obj, Place): place_title = place_displayer.display(self.dbase, obj) - return "%s: %s [%s]" % (_(object_class), + return "%s: %s [%s]" % (_(object_class), place_title, self.gid(obj)) elif isinstance(obj, Repository): - return "%s: %s [%s]" % (_(object_class), - obj.type, + return "%s: %s [%s]" % (_(object_class), + obj.type, self.gid(obj)) elif isinstance(obj, Note): - return "%s: %s [%s]" % (_(object_class), - obj.type, + return "%s: %s [%s]" % (_(object_class), + obj.type, self.gid(obj)) elif isinstance(obj, Tag): - return "%s: [%s]" % (_(object_class), + return "%s: [%s]" % (_(object_class), obj.name) else: return "Error: incorrect object class in display: '%s'" % type(obj) @@ -1015,26 +1015,26 @@ class SimpleAccess(object): def describe(self, obj, prop=None, value=None): """ - Given a object, return a string describing the object. + Given a object, return a string describing the object. """ if prop and value: if self.dbase.get_table_metadata(obj): obj = self.dbase.get_table_metadata(obj)[prop + "_func"](value) if isinstance(obj, Person): - return "%s [%s]" % (self.name(obj), + return "%s [%s]" % (self.name(obj), self.gid(obj)) elif isinstance(obj, Event): return "%s [%s]" % (self.event_type(obj), self.gid(obj)) elif isinstance(obj, Family): - return "%s/%s [%s]" % (self.name(self.mother(obj)), - self.name(self.father(obj)), + return "%s/%s [%s]" % (self.name(self.mother(obj)), + self.name(self.father(obj)), self.gid(obj)) elif isinstance(obj, MediaObject): - return "%s [%s]" % (obj.desc, + return "%s [%s]" % (obj.desc, self.gid(obj)) elif isinstance(obj, Source): - return "%s [%s]" % (self.title(obj), + return "%s [%s]" % (self.title(obj), self.gid(obj)) elif isinstance(obj, Citation): return "[%s]" % (self.gid(obj)) @@ -1043,10 +1043,10 @@ class SimpleAccess(object): return "%s [%s]" % (place_title, self.gid(obj)) elif isinstance(obj, Repository): - return "%s [%s]" % (obj.type, + return "%s [%s]" % (obj.type, self.gid(obj)) elif isinstance(obj, Note): - return "%s [%s]" % (obj.type, + return "%s [%s]" % (obj.type, self.gid(obj)) elif isinstance(obj, Tag): return "[%s]" % (obj.name) diff --git a/gramps/gen/simple/_simpletable.py b/gramps/gen/simple/_simpletable.py index d8393bee6..b819d9088 100644 --- a/gramps/gen/simple/_simpletable.py +++ b/gramps/gen/simple/_simpletable.py @@ -76,7 +76,7 @@ class SimpleTable(object): """ Add a row of data to sort by. """ - self._sort_vals[col].append(val) + self._sort_vals[col].append(val) def set_link_col(self, col): """ @@ -90,7 +90,7 @@ class SimpleTable(object): Add a row of data. """ link = kwargs.get("link", None) - retval = [] + retval = [] row = len(self._rows) self._raw_data.append([]) for col in range(len(data)): @@ -100,7 +100,7 @@ class SimpleTable(object): if item is None: retval.append("") elif isinstance(item, str): - if item == "checkbox": + if item == "checkbox": retval.append(False) self.set_cell_type(col, "checkbox") else: @@ -115,15 +115,15 @@ class SimpleTable(object): retval.append(self.access.describe(item)) if (self._link_col == col or link is None): link = ('Person', item.handle) - elif isinstance(item, Family): + elif isinstance(item, Family): retval.append(self.access.describe(item)) if (self._link_col == col or link is None): link = ('Family', item.handle) - elif isinstance(item, Citation): + elif isinstance(item, Citation): retval.append(self.access.describe(item)) if (self._link_col == col or link is None): link = ('Citation', item.handle) - elif isinstance(item, Source): + elif isinstance(item, Source): retval.append(self.access.describe(item)) if (self._link_col == col or link is None): link = ('Source', item.handle) @@ -152,7 +152,7 @@ class SimpleTable(object): retval.append(text) if item.get_valid(): if item.format: - self.set_cell_markup(col, row, + self.set_cell_markup(col, row, item.format % escape(text)) self.row_sort_val(col, item.sortval) else: @@ -202,7 +202,7 @@ class SimpleTable(object): doc._tbl.set_columns(columns) if self.title: doc.start_row() - doc.start_cell('TableHead', span=columns) + doc.start_cell('TableHead', span=columns) doc.start_paragraph('TableTitle') doc.write_text(_(self.title)) doc.end_paragraph() @@ -212,7 +212,7 @@ class SimpleTable(object): self._sort() doc.start_row() for col in self._columns: - doc.start_cell('TableHeaderCell', span=1) + doc.start_cell('TableHeaderCell', span=1) doc.write_text(col, 'TableTitle') doc.end_cell() doc.end_row() @@ -220,7 +220,7 @@ class SimpleTable(object): for row in self._rows: doc.start_row() for col in row: - doc.start_cell('TableDataCell', span=1) + doc.start_cell('TableDataCell', span=1) obj_type, handle = None, None if hasattr(col, "get_url"): obj_type, handle = "URL", col.get_url() @@ -236,7 +236,7 @@ class SimpleTable(object): if handle: doc.start_link(handle) else: - doc.start_link("/%s/%s" % + doc.start_link("/%s/%s" % (obj_type.lower(), handle)) doc.write_text(str(col), 'Normal') if obj_type and handle: @@ -251,19 +251,19 @@ class SimpleTable(object): def get_cell_markup(self, x, y=None, data=None): """ See if a column has formatting (if x and y are supplied) or - see if a cell has formatting. If it does, return the formatted + see if a cell has formatting. If it does, return the formatted string, otherwise return data that is escaped (if that column has formatting), or just the plain data. """ if x in self._cell_markup: - if y is None: + if y is None: return True # markup for this column elif y in self._cell_markup[x]: return self._cell_markup[x][y] else: return escape(data) else: - if y is None: + if y is None: return False # no markup for this column else: return data diff --git a/gramps/gen/sort.py b/gramps/gen/sort.py index 0b7c1be9b..861199192 100644 --- a/gramps/gen/sort.py +++ b/gramps/gen/sort.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -20,7 +20,7 @@ """ Provide sorting routines for use in Gramps. Since these functions are -intended to provide fast sorting, they tend to bypass access methods, +intended to provide fast sorting, they tend to bypass access methods, and directly use class members. For this reason, care needs to be taken to make sure these remain in sync with the rest of the design. """ @@ -49,16 +49,16 @@ from .const import GRAMPS_LOCALE as glocale #------------------------------------------------------------------------- class Sort(object): - + def __init__(self, database): self.database = database ## def by_last_name(self, first_id, second_id): -## """Sort routine for comparing two last names. If last names are equal, +## """Sort routine for comparing two last names. If last names are equal, ## uses the given name and suffix""" ## first = self.database.get_person_from_handle(first_id) ## second = self.database.get_person_from_handle(second_id) -## +## ## name1 = first.get_primary_name() ## name2 = second.get_primary_name() ## @@ -77,11 +77,11 @@ class Sort(object): def by_last_name_key(self, first_id): """ - Sort routine for comparing two last names. If last names are equal, + Sort routine for comparing two last names. If last names are equal, uses the given name and suffix """ first = self.database.get_person_from_handle(first_id) - + name1 = first.get_primary_name() fsn = name1.get_surname() @@ -256,7 +256,7 @@ class Sort(object): return 0 evt_a = self.database.get_event_from_handle(a_id) return glocale.sort_key(str(evt_a.get_type())) - + ## def by_media_title(self,a_id,b_id): ## """Sort routine for comparing two media objects by their title. """ ## if not (a_id and b_id): @@ -264,7 +264,7 @@ class Sort(object): ## a = self.database.get_object_from_handle(a_id) ## b = self.database.get_object_from_handle(b_id) ## return glocale.strcoll(a.desc, b.desc) - + def by_media_title_key(self, a_id): """Sort routine for comparing two media objects by their title. """ if not a_id: diff --git a/gramps/gen/soundex.py b/gramps/gen/soundex.py index 635995fa3..44bdd4693 100644 --- a/gramps/gen/soundex.py +++ b/gramps/gen/soundex.py @@ -46,7 +46,7 @@ TABLE = bytes.maketrans(b'ABCDEFGIJKLMNOPQRSTUVXYZ', def soundex(strval): "Return the soundex value to a string argument." - strval = unicodedata.normalize('NFKD', + strval = unicodedata.normalize('NFKD', str(strval.upper().strip())).encode('ASCII', 'ignore') if not strval: return "Z000" diff --git a/gramps/gen/test/config_test.py b/gramps/gen/test/config_test.py index df082b2c9..b61042be1 100644 --- a/gramps/gen/test/config_test.py +++ b/gramps/gen/test/config_test.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -38,24 +38,24 @@ class CompleteCheck(unittest.TestCase): def tearDown(self): os.remove(TEMP_INI) os.remove(TEST2_INI) - + def testAll(self): self.CM = ConfigManager(TEMP_INI) self.CM.register("section.setting1", 1) # int self.CM.register("section.setting2", 3.1415) # float self.CM.register("section.setting3", "String") # string self.CM.register("section.setting4", False) # boolean - + self.assertEqual(self.CM.get("section.setting1"), 1) self.assertEqual(self.CM.get("section.setting2"), 3.1415) self.assertEqual(self.CM.get("section.setting3"), "String") self.assertFalse(self.CM.get("section.setting4")) - + self.CM.set("section.setting1", 2) self.CM.set("section.setting2", 8.6) self.CM.set("section.setting3", "Another String") self.CM.set("section.setting4", True) - + self.assertEqual(self.CM.get("section.setting1"), 2) self.assertEqual(self.CM.get("section.setting2"), 8.6) self.assertEqual(self.CM.get("section.setting3"), "Another String") @@ -70,35 +70,35 @@ class CompleteCheck(unittest.TestCase): self.assertEqual(self.CM.get("section.setting2"), 8.6) self.assertEqual(self.CM.get("section.setting3"), "Another String") self.assertTrue(self.CM.get("section.setting4")) - + # Try to set one that doesn't exist: self.assertRaises(AttributeError, self.CM.set, "section.setting5", 1) - + self.CM.save() - + self.CM.reset() # to defaults - + self.assertEqual(self.CM.get("section.setting1"), 1) self.assertEqual(self.CM.get("section.setting2"), 3.1415, self.CM.get("section.setting2")) self.assertEqual(self.CM.get("section.setting3"), "String") self.assertFalse(self.CM.get("section.setting4")) - + self.CM._x = None - + cbid = self.CM.connect("section.setting1", callback) self.assertIsNone(self.CM._x) - + self.CM.set("section.setting1", 1024) self.assertEqual(self.CM._x, "1024", "x was '%s'" % self.CM._x) - + self.CM.disconnect(cbid) - + self.CM.set("section.setting1", -1) self.assertEqual(self.CM._x, "1024") - + self.CM.reset("section.setting1") self.assertEqual(self.CM.get("section.setting1"), 1) - + # No callback: self.CM._x = None self.CM.set("section.setting1", 200) @@ -108,7 +108,7 @@ class CompleteCheck(unittest.TestCase): # Now, call it: self.CM.emit("section.setting1") self.assertEqual(self.CM._x, "200") - + self.CM.set("section.setting1", 2) self.CM.set("section.setting2", 8.6) self.CM.set("section.setting3", "Another String") @@ -126,14 +126,14 @@ class CompleteCheck(unittest.TestCase): self.assertEqual(self.CM.get("section.setting2"), 3.1415) self.assertEqual(self.CM.get("section.setting3"), "String") self.assertFalse(self.CM.get("section.setting4")) - + self.CM.load(TEST2_INI) - + self.assertEqual(self.CM.get("section.setting1"), 2, self.CM.get("section.setting1")) self.assertEqual(self.CM.get("section.setting2"), 8.6) self.assertEqual(self.CM.get("section.setting3"), "Another String") self.assertTrue(self.CM.get("section.setting4")) - + self.assertEqual(self.CM.get("section2.windows-file"), r"c:\drive\path\o'malley\file.pdf") self.assertEqual(self.CM.get("section2.list"), [1, 2, 3, 4]) self.assertEqual(self.CM.get("section2.dict"), {'a': "apple", "b": "banana"}) diff --git a/gramps/gen/test/constfunc_test.py b/gramps/gen/test/constfunc_test.py index fa22c60d6..a76dded14 100644 --- a/gramps/gen/test/constfunc_test.py +++ b/gramps/gen/test/constfunc_test.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. diff --git a/gramps/gen/test/user_test.py b/gramps/gen/test/user_test.py index 7d0880744..128a3c9a4 100644 --- a/gramps/gen/test/user_test.py +++ b/gramps/gen/test/user_test.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. diff --git a/gramps/gen/user.py b/gramps/gen/user.py index eefdf3502..e1c8c74aa 100644 --- a/gramps/gen/user.py +++ b/gramps/gen/user.py @@ -42,7 +42,7 @@ class User(): Start showing a progress indicator to the user. Don't use this method directly, use progress instead. - + :param title: the title of the progress meter :type title: str :param message: the message associated with the progress meter @@ -54,7 +54,7 @@ class User(): :returns: none """ pass - + def step_progress(self): """ Advance the progress meter. @@ -62,7 +62,7 @@ class User(): Don't use this method directly, use progress instead. """ pass - + def callback(self, percentage, text=None): """ Display the precentage. @@ -96,7 +96,7 @@ class User(): Preferred form of progress reporting. Parameters: same as for begin_progress. - + Usage example (see gramps/cli/test/user_test.py):: with self.user.progress("Foo", "Bar", 0) as step: @@ -112,11 +112,11 @@ class User(): raise finally: self.end_progress() - + def prompt(self, title, message, accept_label, reject_label): """ Prompt the user with a message to select an alternative. - + :param title: the title of the question, e.g.: "Undo history warning" :type title: str :param message: the message, e.g.: "Proceeding with the tool will @@ -131,11 +131,11 @@ class User(): :rtype: bool """ return False - + def warn(self, title, warning=""): """ Warn the user. - + :param title: the title of the warning :type title: str :param warning: the warning @@ -143,11 +143,11 @@ class User(): :returns: none """ pass - + def notify_error(self, title, error=""): """ Notify the user of an error. - + :param title: the title of the error :type title: str :param error: the error message @@ -159,7 +159,7 @@ class User(): def notify_db_error(self, error): """ Notify the user of a DB error. - + :param error: the error message :type error: str :returns: none diff --git a/gramps/gen/utils/alive.py b/gramps/gen/utils/alive.py index 90bfdd976..3f6e5f045 100644 --- a/gramps/gen/utils/alive.py +++ b/gramps/gen/utils/alive.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -71,14 +71,14 @@ class ProbablyAlive(object): An object to hold the parameters for considering someone alive. """ - def __init__(self, + def __init__(self, db, - max_sib_age_diff=None, - max_age_prob_alive=None, + max_sib_age_diff=None, + max_age_prob_alive=None, avg_generation_gap=None): self.db = db if max_sib_age_diff is None: - max_sib_age_diff = _MAX_SIB_AGE_DIFF + max_sib_age_diff = _MAX_SIB_AGE_DIFF if max_age_prob_alive is None: max_age_prob_alive = _MAX_AGE_PROB_ALIVE if avg_generation_gap is None: @@ -144,17 +144,17 @@ class ProbablyAlive(object): # person died more than MAX after current year birth_date = death_date.copy_offset_ymd(year=-self.MAX_AGE_PROB_ALIVE) explain = _("death date") - + if not death_date and birth_date: # person died more than MAX after current year death_date = birth_date.copy_offset_ymd(year=self.MAX_AGE_PROB_ALIVE) explain = _("birth date") - + if death_date and birth_date: return (birth_date, death_date, explain, person) # direct self evidence - + # Neither birth nor death events are available. Try looking - # at siblings. If a sibling was born more than X years past, + # at siblings. If a sibling was born more than X years past, # or more than Z future, then probably this person is # not alive. If the sibling died more than X years # past, or more than X years future, then probably not alive. @@ -173,7 +173,7 @@ class ProbablyAlive(object): for ev_ref in child.get_primary_event_ref_list(): ev = self.db.get_event_from_handle(ev_ref.ref) if ev and ev.type.is_birth(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: # if sibling birth date too far away, then not alive: year = dobj.get_year() @@ -184,14 +184,14 @@ class ProbablyAlive(object): _("sibling birth date"), child) elif ev and ev.type.is_death(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: # if sibling death date too far away, then not alive: year = dobj.get_year() if year != 0: # sibling death date return (Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF - self.MAX_AGE_PROB_ALIVE), - Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF - self.MAX_AGE_PROB_ALIVE + Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE), _("sibling death date"), child) @@ -199,7 +199,7 @@ class ProbablyAlive(object): for ev_ref in child.get_primary_event_ref_list(): ev = self.db.get_event_from_handle(ev_ref.ref) if ev and ev.type.is_birth_fallback(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: # if sibling birth date too far away, then not alive: year = dobj.get_year() @@ -210,7 +210,7 @@ class ProbablyAlive(object): _("sibling birth-related date"), child) elif ev and ev.type.is_death_fallback(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: # if sibling death date too far away, then not alive: year = dobj.get_year() @@ -258,12 +258,12 @@ class ProbablyAlive(object): year = date.get_year() if year != 0: other = None - if person.handle == mother_handle and father_handle: + if person.handle == mother_handle and father_handle: other = self.db.get_person_from_handle(father_handle) - elif person.handle == father_handle and mother_handle: + elif person.handle == father_handle and mother_handle: other = self.db.get_person_from_handle(mother_handle) return (Date().copy_ymd(year - self.AVG_GENERATION_GAP), - Date().copy_ymd(year - self.AVG_GENERATION_GAP + + Date().copy_ymd(year - self.AVG_GENERATION_GAP + self.MAX_AGE_PROB_ALIVE), _("event with spouse"), other) @@ -274,7 +274,7 @@ class ProbablyAlive(object): def descendants_too_old (person, years): for family_handle in person.get_family_handle_list(): family = self.db.get_family_from_handle(family_handle) - if not family: + if not family: # can happen with LivingProxyDb(PrivateProxyDb(db)) continue for child_ref in family.get_child_ref_list(): @@ -297,7 +297,7 @@ class ProbablyAlive(object): child_death = self.db.get_event_from_handle(child_death_ref.ref) dobj = child_death.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP), + return (dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP), dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP + self.MAX_AGE_PROB_ALIVE), _("descendant death date"), child) @@ -308,7 +308,7 @@ class ProbablyAlive(object): for ev_ref in child.get_primary_event_ref_list(): ev = self.db.get_event_from_handle(ev_ref.ref) if ev and ev.type.is_birth_fallback(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: d = Date(dobj) val = d.get_start_date() @@ -319,9 +319,9 @@ class ProbablyAlive(object): child) elif ev and ev.type.is_death_fallback(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP), + return (dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP), dobj.copy_offset_ymd(- self.AVG_GENERATION_GAP + self.MAX_AGE_PROB_ALIVE), _("descendant death-related date"), child) @@ -346,9 +346,9 @@ class ProbablyAlive(object): LOG.debug("ancestors_too_old('%s', %s)".format( name_displayer.display(person), year) ) family_handle = person.get_main_parents_family_handle() - if family_handle: + if family_handle: family = self.db.get_family_from_handle(family_handle) - if not family: + if not family: # can happen with LivingProxyDb(PrivateProxyDb(db)) return (None, None, "", None) father_handle = family.get_father_handle() @@ -360,7 +360,7 @@ class ProbablyAlive(object): father_birth_ref.ref) dobj = father_birth.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- year), + return (dobj.copy_offset_ymd(- year), dobj.copy_offset_ymd(- year + self.MAX_AGE_PROB_ALIVE), _("ancestor birth date"), father) @@ -370,7 +370,7 @@ class ProbablyAlive(object): father_death_ref.ref) dobj = father_death.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE), + return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE), dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE), _("ancestor death date"), father) @@ -379,17 +379,17 @@ class ProbablyAlive(object): for ev_ref in father.get_primary_event_ref_list(): ev = self.db.get_event_from_handle(ev_ref.ref) if ev and ev.type.is_birth_fallback(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- year), + return (dobj.copy_offset_ymd(- year), dobj.copy_offset_ymd(- year + self.MAX_AGE_PROB_ALIVE), _("ancestor birth-related date"), father) elif ev and ev.type.is_death_fallback(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE), + return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE), dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE), _("ancestor death-related date"), father) @@ -406,7 +406,7 @@ class ProbablyAlive(object): mother_birth = self.db.get_event_from_handle(mother_birth_ref.ref) dobj = mother_birth.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- year), + return (dobj.copy_offset_ymd(- year), dobj.copy_offset_ymd(- year + self.MAX_AGE_PROB_ALIVE), _("ancestor birth date"), mother) @@ -416,7 +416,7 @@ class ProbablyAlive(object): mother_death_ref.ref) dobj = mother_death.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE), + return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE), dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE), _("ancestor death date"), mother) @@ -425,17 +425,17 @@ class ProbablyAlive(object): for ev_ref in mother.get_primary_event_ref_list(): ev = self.db.get_event_from_handle(ev_ref.ref) if ev and ev.type.is_birth_fallback(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- year), + return (dobj.copy_offset_ymd(- year), dobj.copy_offset_ymd(- year + self.MAX_AGE_PROB_ALIVE), _("ancestor birth-related date"), mother) elif ev and ev.type.is_death_fallback(): - dobj = ev.get_date_object() + dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: - return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE), + return (dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE), dobj.copy_offset_ymd(- year - self.MAX_AGE_PROB_ALIVE + self.MAX_AGE_PROB_ALIVE), _("ancestor death-related date"), mother) @@ -467,11 +467,11 @@ class ProbablyAlive(object): # probably_alive # #------------------------------------------------------------------------- -def probably_alive(person, db, - current_date=None, +def probably_alive(person, db, + current_date=None, limit=0, - max_sib_age_diff=None, - max_age_prob_alive=None, + max_sib_age_diff=None, + max_age_prob_alive=None, avg_generation_gap=None, return_range=False): """ @@ -499,22 +499,22 @@ def probably_alive(person, db, birth, death, explain)) if not birth or not death: # no evidence, must consider alive - return ((True, None, None, _("no evidence"), None) if return_range + return ((True, None, None, _("no evidence"), None) if return_range else True) # must have dates from here: if limit: death += limit # add these years to death # Finally, check to see if current_date is between dates - result = (current_date.match(birth, ">=") and + result = (current_date.match(birth, ">=") and current_date.match(death, "<=")) if return_range: return (result, birth, death, explain, relative) else: return result -def probably_alive_range(person, db, - max_sib_age_diff=None, - max_age_prob_alive=None, +def probably_alive_range(person, db, + max_sib_age_diff=None, + max_age_prob_alive=None, avg_generation_gap=None): """ Computes estimated birth and death dates. @@ -527,7 +527,7 @@ def probably_alive_range(person, db, while isinstance(basedb, ProxyDbBase): basedb = basedb.db # Now, we create a wrapper for doing work: - pb = ProbablyAlive(basedb, max_sib_age_diff, + pb = ProbablyAlive(basedb, max_sib_age_diff, max_age_prob_alive, avg_generation_gap) return pb.probably_alive_range(person) diff --git a/gramps/gen/utils/callback.py b/gramps/gen/utils/callback.py index cf3a66da1..ac82db459 100644 --- a/gramps/gen/utils/callback.py +++ b/gramps/gen/utils/callback.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -52,7 +52,7 @@ class Callback(object): Callback and signal support objects. **Declaring signals** - + Classes that want to emit signals need to inherit from the DBCallback class and ensure that its :meth:`__init__` method is called. They then need to declare the signals that they @@ -62,7 +62,7 @@ class Callback(object): class TestSignals(Callback): __signals__ = { - 'test-signal' : (int, ), + 'test-signal' : (int, ), 'test-noarg' : None } @@ -90,9 +90,9 @@ class Callback(object): The parameters are passed as a tuple so a single parameter must be passed as a 1 element tuple. - + **Connecting callbacks to signals** - + Attaching a callback to the signals is similar to the gtk connect methods. e.g.:: @@ -111,7 +111,7 @@ class Callback(object): r = R() t.connect('test-signal', r.cb_func) - + **Disconnecting callbacks** @@ -136,7 +136,7 @@ class Callback(object): t.disconnect(key) - + **Stopping and starting signals** Signals can be blocked on a per instance bassis or they can be blocked @@ -150,7 +150,7 @@ class Callback(object): class TestSignals(Callback): __signals__ = { - 'test-signal' : (int, ), + 'test-signal' : (int, ), 'test-noarg' : None } @@ -166,7 +166,7 @@ class Callback(object): t.disable_signals() ... - + # unblock t.enable_signals() @@ -174,14 +174,14 @@ class Callback(object): Callback.disable_all_signals() ... - + # unblock all signals Callback.enable_all_signals() - Any signals emitted whilst signals are blocked will be lost. - - + Any signals emitted whilst signals are blocked will be lost. + + **Debugging signal callbacks** @@ -190,7 +190,7 @@ class Callback(object): instance call :meth:`enable_logging`, to switch it off again call :meth:`disable_logging`. To switch on logging for all instance you can toggle Callback.__LOG_ALL to True. - + """ # If this True no signals will be emitted from any instance of @@ -222,12 +222,12 @@ class Callback(object): # being emitted by this instance. This is # used to prevent recursive emittion of the # same signal. - + # To speed up the signal type checking the signals declared by # each of the classes in the inheritance tree of this instance # are consolidated into a single dictionary. # The signals can't change so we only need to do this once. - + def trav(cls): """A traversal function to walk through all the classes in the inheritance tree. The return is a list of all the @@ -260,7 +260,7 @@ class Callback(object): self._log("registered signals: \n %s\n" % "\n ".join([ "%s: %s" % (k, v) for (k, v) in list(self.__signal_map.items()) ])) - + def connect(self, signal_name, callback): """ @@ -272,10 +272,10 @@ class Callback(object): """ # Check that signal exists. if signal_name not in self.__signal_map: - self._log("Warning: attempt to connect to unknown signal: %s\n" + self._log("Warning: attempt to connect to unknown signal: %s\n" % str(signal_name)) return - + # Add callable to callback_map if signal_name not in self.__callback_map: self.__callback_map[signal_name] = [] @@ -292,7 +292,7 @@ class Callback(object): """ Disconnect a callback. """ - + # Find the key in the callback map. for signal_name in self.__callback_map: for cb in self.__callback_map[signal_name]: @@ -300,7 +300,7 @@ class Callback(object): if skey == key: # delete the callback from the map. self._log("Disconnecting callback from signal" - ": %s with key: %s\n" % (signal_name, + ": %s with key: %s\n" % (signal_name, str(key))) self.__callback_map[signal_name].remove(cb) @@ -322,7 +322,7 @@ class Callback(object): if self.__BLOCK_ALL_SIGNALS or \ self.__block_instance_signals: return - + # Check signal exists if signal_name not in self.__signal_map: self._warn("Attempt to emit to unknown signal: %s\n" @@ -341,7 +341,7 @@ class Callback(object): " line: %d\n" " func: %s\n" % ((str(signal_name), ) + inspect.stack()[1][1:4])) - return + return try: self._current_signals.append(signal_name) @@ -392,8 +392,8 @@ class Callback(object): " func: %s\n" " arg passed was: %s, type of arg passed %s, type should be: %s\n" % ((str(signal_name), ) + inspect.stack()[1][1:4] +\ - (args[i], repr(type(args[i])), repr(arg_types[i])))) - return + (args[i], repr(type(args[i])), repr(arg_types[i])))) + return if signal_name in self.__callback_map: self._log("emitting signal: %s\n" % (signal_name, )) # Don't bother if there are no callbacks. @@ -416,7 +416,7 @@ class Callback(object): # def disable_signals(self): self.__block_instance_signals = True - + def enable_signals(self): self.__block_instance_signals = False diff --git a/gramps/gen/utils/callman.py b/gramps/gen/utils/callman.py index 939a0f6fa..e021854f6 100644 --- a/gramps/gen/utils/callman.py +++ b/gramps/gen/utils/callman.py @@ -98,17 +98,17 @@ def _return(*args): class CallbackManager(object): """ - Manage callback handling from GUI to the db. + Manage callback handling from GUI to the db. It is unique to a db and some GUI element. When a db is changed, one should destroy the CallbackManager and set up a new one (or delete the GUI element as it shows info from a previous db). - - Track changes to your relevant objects, calling callback functions as + + Track changes to your relevant objects, calling callback functions as needed. """ def __init__(self, database): """ - :param database: database to which to connect the callbacks of this + :param database: database to which to connect the callbacks of this CallbackManager object :type database: a class:`~gen.db.base.DbBase` object """ @@ -153,10 +153,10 @@ class CallbackManager(object): if not value[1] is None: self.database.disconnect(value[1]) self.__init_callbacks() - + def register_obj(self, baseobj, directonly=False): """ - Convenience method, will register all directly and not directly + Convenience method, will register all directly and not directly referenced prim objects connected to baseobj with the CallbackManager If directonly is True, only directly registered objects will be registered. @@ -166,14 +166,14 @@ class CallbackManager(object): self.register_handles(directhandledict(baseobj)) else: self.register_handles(handledict(baseobj)) - + def register_handles(self, ahandledict): """ Register handles that need to be tracked by the manager. - This function can be called several times, adding to existing + This function can be called several times, adding to existing registered handles. - - :param ahandledict: a dictionary with key one of the KEYS, + + :param ahandledict: a dictionary with key one of the KEYS, and value a list of handles to track """ for key in KEYS: @@ -185,15 +185,15 @@ class CallbackManager(object): def unregister_handles(self, ahandledict): """ All handles in handledict are no longer tracked - - :param handledict: a dictionary with key one of the KEYS, + + :param handledict: a dictionary with key one of the KEYS, and value a list of handles to track """ for key in KEYS: handles = ahandledict.get(key) if handles: list(map(self.__handles[key].remove, handles)) - + def unregister_all(self): """ Unregister all handles that are registered @@ -210,15 +210,15 @@ class CallbackManager(object): NOTEKEY: [], TAGKEY: [], } - + def register_callbacks(self, callbackdict): """ - register callback functions that need to be called for a specific + register callback functions that need to be called for a specific db action. This function can be called several times, adding to and if needed overwriting, existing callbacks. No db connects are done. If a signal already is connected to the db, it is removed from the connect list of the db. - + :param callbackdict: a dictionary with key one of KEYS+METHODS, or one of KEYS, and value a function to be called when signal is raised. """ @@ -234,16 +234,16 @@ class CallbackManager(object): def connect_all(self, keys=None): """ - Convenience function, connects all database signals related to the - primary objects given in keys to the callbacks attached to self. + Convenience function, connects all database signals related to the + primary objects given in keys to the callbacks attached to self. Note that only those callbacks registered with register_callbacks will - effectively result in an action, so one can connect to all keys + effectively result in an action, so one can connect to all keys even if not all keys have a registered callback. - - :param keys: list of keys of primary objects for which to connect the - signals, default is no connects being done. One can enable signal - activity to needed objects by passing a list, eg - keys=[callman.SOURCEKEY, callman.PLACEKEY], or to all with + + :param keys: list of keys of primary objects for which to connect the + signals, default is no connects being done. One can enable signal + activity to needed objects by passing a list, eg + keys=[callman.SOURCEKEY, callman.PLACEKEY], or to all with keys=callman.KEYS """ if keys is None: @@ -253,22 +253,22 @@ class CallbackManager(object): signal = key + method self.__do_unconnect(signal) self.__callbacks[signal][1] = self.database.connect( - signal, + signal, self.__callbackcreator(signal)) for method in METHODS_NONE: signal = key + method self.__do_unconnect(signal) self.__callbacks[signal][1] = self.database.connect( - signal, - self.__callbackcreator(signal, + signal, + self.__callbackcreator(signal, noarg=True)) def __do_callback(self, signal, *arg): """ Execute a specific callback. This is only actually done if one of the - registered handles is involved. - Arg must conform to the requirements of the signal emitter. - For a DbBase that is that arg must be not given (rebuild + registered handles is involved. + Arg must conform to the requirements of the signal emitter. + For a DbBase that is that arg must be not given (rebuild methods), or arg[0] must be the list of handles affected. """ key = signal.split('-')[0] @@ -281,10 +281,10 @@ class CallbackManager(object): affected = self.__handles[key] if affected: self.__callbacks[signal][0]() - + def __add_callback(self, signal, callback): """ - Add a callback to a signal. There can be only one callback per signal + Add a callback to a signal. There can be only one callback per signal that is managed, so if there is a previous one, it is removed """ self.__do_unconnect(signal) @@ -305,12 +305,12 @@ class CallbackManager(object): """ if self.database: self.custom_signal_keys.append(self.database.connect(name, callback)) - + def __callbackcreator(self, signal, noarg=False): """ - helper function, a lambda function needs a string to be defined + helper function, a lambda function needs a string to be defined explicitly. This function creates the correct lambda function to use - as callback based on the key/signal one needs to connect to. + as callback based on the key/signal one needs to connect to. AttributeError is raised for unknown key or signal. """ def gen(self, signal): @@ -332,7 +332,7 @@ class CallbackManager(object): return gen(self, signal) else: raise AttributeError('Signal ' + signal + 'not supported.') - + def directhandledict(baseobj): """ Build a handledict from baseobj with all directly referenced objects @@ -355,7 +355,7 @@ def directhandledict(baseobj): def handledict(baseobj): """ - Build a handledict from baseobj with all directly and not directly + Build a handledict from baseobj with all directly and not directly referenced base obj that are present """ handles = { diff --git a/gramps/gen/utils/cast.py b/gramps/gen/utils/cast.py index c2d4a4b70..a0e490f5d 100644 --- a/gramps/gen/utils/cast.py +++ b/gramps/gen/utils/cast.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -68,7 +68,7 @@ def get_type_converter(val): def type_name(val): """ Return the name the type of val. - + Only numbers and strings are supported. The rest becomes strings (unicode). """ @@ -86,7 +86,7 @@ def type_name(val): def get_type_converter_by_name(val_str): """ Return function that converts strings into the type given by val_str. - + Only numbers and strings are supported. The rest becomes strings (unicode). """ diff --git a/gramps/gen/utils/config.py b/gramps/gen/utils/config.py index a7a1696df..b58109f05 100644 --- a/gramps/gen/utils/config.py +++ b/gramps/gen/utils/config.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. diff --git a/gramps/gen/utils/configmanager.py b/gramps/gen/utils/configmanager.py index 77c3c318c..f2017ea9d 100644 --- a/gramps/gen/utils/configmanager.py +++ b/gramps/gen/utils/configmanager.py @@ -2,7 +2,7 @@ # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2005-2007 Donald N. Allingham -# Copyright (C) 2008-2009 Gary Burton +# Copyright (C) 2008-2009 Gary Burton # Copyright (C) 2009 Doug Blank # # This program is free software; you can redistribute it and/or modify @@ -62,13 +62,13 @@ def safe_eval(exp): #--------------------------------------------------------------- class ConfigManager(object): """ - Class to construct the singleton CONFIGMAN where all + Class to construct the singleton CONFIGMAN where all settings are stored. """ PLUGINS = {} def __init__(self, filename=None, plugins=None): - """ + """ Configure manager constructor takes an optional filename, and plugin path. @@ -112,10 +112,10 @@ class ConfigManager(object): self.data = {} self.reset() - def register_manager(self, name, override="", use_plugins_path=True, + def register_manager(self, name, override="", use_plugins_path=True, use_config_path=False): """ - Register a plugin manager. + Register a plugin manager. :param name: is used as the key of the config manager singleton. It is also be used as the base filename (unless an override is @@ -128,9 +128,9 @@ class ConfigManager(object): Override is either: - - a full path+filename ending in .ini - - a filename ending in .ini - - a dir path to put ini file into + - a full path+filename ending in .ini + - a filename ending in .ini + - a dir path to put ini file into - a full path+filename to get dir to put ini file into - a ConfigManager instance @@ -196,13 +196,13 @@ class ConfigManager(object): For item access, such as config["interface.dont-ask"] """ return self.get(item) - + def __setitem__(self, item, value): """ For item assignment, such as config["interface.dont-ask"] = True """ - self.set(item, value) - + self.set(item, value) + def reset(self, key=None): """ Resets one, a section, or all settings values to their defaults. @@ -247,7 +247,7 @@ class ConfigManager(object): return list(self.data[section].keys()) def load(self, filename=None, oldstyle=False): - """ + """ Loads an .ini into self.data. """ if filename is None: @@ -276,7 +276,7 @@ class ConfigManager(object): setting = opt.lower() if oldstyle: ####################### Upgrade from oldstyle < 3.2 - # Oldstyle didn't mark setting type, but had it + # Oldstyle didn't mark setting type, but had it # set in preferences. New style gets it from evaling # the setting's value ####################### @@ -299,7 +299,7 @@ class ConfigManager(object): else: value = safe_eval(raw_value) ####################### Now, let's test and set: - if (name in self.default and + if (name in self.default and setting in self.default[name]): if isinstance(self.default[name][setting], bool): #make sure 0 and 1 are False and True @@ -311,7 +311,7 @@ class ConfigManager(object): self.data[name][setting] = value else: logging.warning("WARNING: ignoring key with wrong type " - "'%s.%s' %s needed instead of %s" % + "'%s.%s' %s needed instead of %s" % (name, setting, type(self.data[name][setting]), type(value))) @@ -341,7 +341,7 @@ class ConfigManager(object): return; key_file.write(";; Gramps key file\n") - key_file.write((";; Automatically created at %s" % + key_file.write((";; Automatically created at %s" % time.strftime("%Y/%m/%d %H:%M:%S")) + "\n\n") sections = sorted(self.data) for section in sections: @@ -357,8 +357,8 @@ class ConfigManager(object): default = "" if isinstance(value, int): value = int(value) - key_file.write(("%s%s=%s\n")% (default, - key, + key_file.write(("%s%s=%s\n")% (default, + key, repr(value))) key_file.write("\n") key_file.close() @@ -372,12 +372,12 @@ class ConfigManager(object): if "." in key: section, setting = key.split(".", 1) else: - raise AttributeError("Invalid config section.setting name: '%s'" % + raise AttributeError("Invalid config section.setting name: '%s'" % key) if section not in self.data: raise AttributeError("No such config section name: '%s'" % section) if setting not in self.data[section]: - raise AttributeError("No such config setting name: '%s.%s'" % + raise AttributeError("No such config setting name: '%s.%s'" % (section, setting)) return self.data[section][setting] @@ -398,7 +398,7 @@ class ConfigManager(object): def has_default(self, key): """ - Does the setting have a default value? Returns True if it does, + Does the setting have a default value? Returns True if it does, False otherwise. Key is a sting in the "section.setting" format. """ if "." in key: @@ -419,12 +419,12 @@ class ConfigManager(object): if "." in key: section, setting = key.split(".", 1) else: - raise AttributeError("Invalid config section.setting name: '%s'" % + raise AttributeError("Invalid config section.setting name: '%s'" % key) if section not in self.default: raise AttributeError("No such config section name: '%s'" % section) if setting not in self.default[section]: - raise AttributeError("No such config setting name: '%s.%s'" % + raise AttributeError("No such config setting name: '%s.%s'" % (section, setting)) return self.default[section][setting] @@ -437,7 +437,7 @@ class ConfigManager(object): if "." in key: section, setting = key.split(".", 1) else: - raise AttributeError("Invalid config section.setting name: '%s'" % + raise AttributeError("Invalid config section.setting name: '%s'" % key) if section not in self.data: self.data[section] = {} @@ -460,12 +460,12 @@ class ConfigManager(object): if "." in key: section, setting = key.split(".", 1) else: - raise AttributeError("Invalid config section.setting name: '%s'" % + raise AttributeError("Invalid config section.setting name: '%s'" % key) if section not in self.data: raise AttributeError("No such config section name: '%s'" % section) if setting not in self.data[section]: - raise AttributeError("No such config setting name: '%s.%s'" % + raise AttributeError("No such config setting name: '%s.%s'" % (section, setting)) self._cb_id += 1 self.callbacks[section][setting].append((self._cb_id, func)) @@ -490,15 +490,15 @@ class ConfigManager(object): if "." in key: section, setting = key.split(".", 1) else: - raise AttributeError("Invalid config section.setting name: '%s'" % + raise AttributeError("Invalid config section.setting name: '%s'" % key) if section not in self.callbacks: raise AttributeError("No such config section name: '%s'" % section) if setting not in self.callbacks[section]: - raise AttributeError("No such config setting name: '%s.%s'" % + raise AttributeError("No such config setting name: '%s.%s'" % (section, setting)) for (cbid, func) in self.callbacks[section][setting]: - func(self, 0, str(self.data[section][setting]), None) + func(self, 0, str(self.data[section][setting]), None) def set(self, key, value): """ @@ -509,21 +509,21 @@ class ConfigManager(object): if "." in key: section, setting = key.split(".", 1) else: - raise AttributeError("Invalid config section.setting name: '%s'" % + raise AttributeError("Invalid config section.setting name: '%s'" % key) if section not in self.data: raise AttributeError("No such config section name: '%s'" % section) if setting not in self.data[section]: - raise AttributeError("No such config setting name: '%s.%s'" % + raise AttributeError("No such config setting name: '%s.%s'" % (section, setting)) # Check value to see if right type: if self.has_default(key): if not self.check_type(self.get_default(key), value): raise AttributeError("attempting to set '%s' to wrong type " "'%s'; should be '%s'" % - (key, type(value), + (key, type(value), type(self.get_default(key)))) - if (setting in self.data[section] and + if (setting in self.data[section] and self.data[section][setting] == value): # Do nothing if existed and is the same pass @@ -531,7 +531,7 @@ class ConfigManager(object): # Set the value: self.data[section][setting] = value # Only call callback if the value changed! - if (section in self.callbacks and + if (section in self.callbacks and setting in self.callbacks[section]): self.emit(key) @@ -546,7 +546,7 @@ class ConfigManager(object): elif (isinstance(value1, str) and isinstance(value2, str)): return True - elif (type1 in [int, float] and + elif (type1 in [int, float] and type2 in [int, float]): return True else: diff --git a/gramps/gen/utils/db.py b/gramps/gen/utils/db.py index 4e0a7f7d5..fcdcd443c 100644 --- a/gramps/gen/utils/db.py +++ b/gramps/gen/utils/db.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -66,8 +66,8 @@ def get_birth_or_fallback(db, person, format=None): if format: event.date.format = format return event - return None - + return None + def get_death_or_fallback(db, person, format=None): """ Get a DEATH event from a person, or fallback to an @@ -88,7 +88,7 @@ def get_death_or_fallback(db, person, format=None): if format: event.date.format = format return event - return None + return None def get_age(db, person, fallback=True, calendar="gregorian"): """ @@ -167,7 +167,7 @@ def get_timeperiod(db, person): and not event_date.is_empty()): return event_date.get_year() return None - + def get_event_ref(db, family, event_type): """ Return a reference to a primary family event of the given event type. @@ -190,8 +190,8 @@ def get_primary_event_ref_list(db, family): retval = [] for event_ref in family.get_event_ref_list(): event = db.get_event_from_handle(event_ref.ref) - if (event and - (event_ref.get_role() == EventRoleType.FAMILY or + if (event and + (event_ref.get_role() == EventRoleType.FAMILY or event_ref.get_role() == EventRoleType.PRIMARY)): retval.append(event_ref) return retval @@ -214,12 +214,12 @@ def get_marriage_or_fallback(db, family, format=None): event = db.get_event_from_handle(event_ref.ref) if (event and event.type.is_marriage_fallback() - and (event_ref.role == EventRoleType.FAMILY or + and (event_ref.role == EventRoleType.FAMILY or event_ref.role == EventRoleType.PRIMARY)): if format: event.date.format = format return event - return None + return None def get_divorce_or_fallback(db, family, format=None): """ @@ -239,7 +239,7 @@ def get_divorce_or_fallback(db, family, format=None): event = db.get_event_from_handle(event_ref.ref) if (event and event.type.is_divorce_fallback() - and (event_ref.role == EventRoleType.FAMILY or + and (event_ref.role == EventRoleType.FAMILY or event_ref.role == EventRoleType.PRIMARY)): if format: event.date.format = format @@ -253,8 +253,8 @@ def get_divorce_or_fallback(db, family, format=None): #------------------------------------------------------------------------- def get_participant_from_event(db, event_handle, all_=False): """ - Obtain the first primary or family participant to an event we find in the - database. Note that an event can have more than one primary or + Obtain the first primary or family participant to an event we find in the + database. Note that an event can have more than one primary or family participant, only one is returned, adding ellipses if there are more. If the all\_ parameter is true a comma-space separated string with the names of all primary participants is returned and no ellipses is used. @@ -273,7 +273,7 @@ def get_participant_from_event(db, event_handle, all_=False): #obtain handles without duplicates people = set([x[1] for x in result_list if x[0] == 'Person']) families = set([x[1] for x in result_list if x[0] == 'Family']) - for personhandle in people: + for personhandle in people: person = db.get_person_from_handle(personhandle) if not person: continue @@ -292,7 +292,7 @@ def get_participant_from_event(db, event_handle, all_=False): break if ellipses: return _('%s, ...') % participant - + for familyhandle in families: family = db.get_family_from_handle(familyhandle) for event_ref in family.get_event_ref_list(): @@ -308,7 +308,7 @@ def get_participant_from_event(db, event_handle, all_=False): break if ellipses: break - + if ellipses: return _('%s, ...') % participant else: @@ -490,15 +490,15 @@ def for_each_ancestor(db, start, func, data): # #------------------------------------------------------------------------- def preset_name(basepers, name, sibling=False): - """Fill up name with all family common names of basepers. + """Fill up name with all family common names of basepers. If sibling=True, pa/matronymics are retained. """ surnlist = [] primname = basepers.get_primary_name() prim = False for surn in primname.get_surname_list(): - if (not sibling) and (surn.get_origintype().value in - [NameOriginType.PATRONYMIC, + if (not sibling) and (surn.get_origintype().value in + [NameOriginType.PATRONYMIC, NameOriginType.MATRONYMIC]): continue surnlist.append(Surname(source=surn)) @@ -530,7 +530,7 @@ def family_name(family, db, noname=_("unknown")): fname = name_displayer.display(father) mname = name_displayer.display(mother) name = _("%(father)s and %(mother)s") % { - "father" : fname, + "father" : fname, "mother" : mname} elif father: name = name_displayer.display(father) @@ -547,13 +547,13 @@ def family_name(family, db, noname=_("unknown")): #------------------------------------------------------------------------- def get_referents(handle, db, primary_objects): """ Find objects that refer to an object. - + This function is the base for other get__referents functions. - + """ # Use one pass through the reference map to grab all the references object_list = list(db.find_backlink_handles(handle)) - + # Then form the object-specific lists the_lists = () @@ -567,11 +567,11 @@ def get_source_referents(source_handle, db): This function finds all primary objects that refer (directly or through secondary child-objects) to a given source handle in a given database. - + Only Citations can refer to sources, so that is all we need to check """ _primaries = ('Citation',) - + return (get_referents(source_handle, db, _primaries)) def get_citation_referents(citation_handle, db): @@ -579,27 +579,27 @@ def get_citation_referents(citation_handle, db): This function finds all primary objects that refer (directly or through secondary child-objects) to a given citation handle in a given database. - + """ - _primaries = ('Person', 'Family', 'Event', 'Place', + _primaries = ('Person', 'Family', 'Event', 'Place', 'Source', 'MediaObject', 'Repository') - + return (get_referents(citation_handle, db, _primaries)) def get_source_and_citation_referents(source_handle, db): - """ + """ Find all citations that refer to the sources, and recursively, all objects that refer to the sources. This function finds all primary objects that refer (directly or through secondary child-objects) to a given source handle in a given database. - + | Objects -> Citations -> Source | e.g. | Media object M1 -> Citation C1 -> Source S1 | Media object M2 -> Citation C1 -> Source S1 | Person object P1 -> Citation C2 -> Source S1 - + The returned structure is rather ugly, but provides all the information in a way that is consistent with the other Util functions. @@ -629,33 +629,33 @@ def get_source_and_citation_referents(source_handle, db): LOG.debug('citation %s' % citation) refs = get_citation_referents(citation, db) citation_referents_list += [(citation, refs)] - LOG.debug('citation_referents_list %s' % [citation_referents_list]) - + LOG.debug('citation_referents_list %s' % [citation_referents_list]) + (citation_list) = the_lists the_lists = (citation_list, citation_referents_list) LOG.debug('the_lists %s' % [the_lists]) - return the_lists + return the_lists def get_media_referents(media_handle, db): """ Find objects that refer the media object. This function finds all primary objects that refer to a given media handle in a given database. - + """ _primaries = ('Person', 'Family', 'Event', 'Place', 'Source', 'Citation') - + return (get_referents(media_handle, db, _primaries)) def get_note_referents(note_handle, db): """ Find objects that refer a note object. - + This function finds all primary objects that refer to a given note handle in a given database. - + """ - _primaries = ('Person', 'Family', 'Event', 'Place', + _primaries = ('Person', 'Family', 'Event', 'Place', 'Source', 'Citation', 'MediaObject', 'Repository') - + return (get_referents(note_handle, db, _primaries)) diff --git a/gramps/gen/utils/debug.py b/gramps/gen/utils/debug.py index 5d010f8a1..9d0b473e0 100644 --- a/gramps/gen/utils/debug.py +++ b/gramps/gen/utils/debug.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -50,7 +50,7 @@ def format_exception(tb_type=None, tb_value=None, tb=None): """ Get the usual traceback information, followed by a listing of all the local variables in each frame. - Based on: + Based on: code.activestate.com/recipes/52215-get-more-information-from-tracebacks """ import sys @@ -81,7 +81,7 @@ def format_exception(tb_type=None, tb_value=None, tb=None): #We have to be careful not to cause a new error in our error #handler! Calling str() on an unknown object could cause an #error we don't want. - try: + try: line = " %s = %s\n" % (key, str(value)) except: line = " %s = %s\n" % (key, "") diff --git a/gramps/gen/utils/docgen/odstab.py b/gramps/gen/utils/docgen/odstab.py index 0f1a45e91..1a724b5a2 100644 --- a/gramps/gen/utils/docgen/odstab.py +++ b/gramps/gen/utils/docgen/odstab.py @@ -20,7 +20,7 @@ #------------------------------------------------------------------------- # -# Standard Python Modules +# Standard Python Modules # #------------------------------------------------------------------------- import os @@ -69,37 +69,37 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" _DOC_FONTS = '''\ - - ''' _DOC_STYLES = '''\ - - - - - @@ -121,86 +121,86 @@ _STYLES_FONTS = '''\ _STYLES_STYLES = '''\ - - - - - - + - - + ''' _STYLES_AUTOMATIC = '''\ - - - - @@ -209,7 +209,7 @@ _STYLES_AUTOMATIC = '''\ _STYLES_MASTER = '''\ - @@ -222,27 +222,27 @@ _STYLES_MASTER = '''\ - - ??? + ??? (???) - 05/16/2001 - , + , 10:53:17 - Page - 1 / + Page + 1 / 99 @@ -252,33 +252,33 @@ _STYLES_MASTER = '''\ _MANIFEST = '''\ - - - - - - ''' _META = '''\ - @@ -325,7 +325,7 @@ class ODSTab(TabbedDoc): def open(self,filename): import time - + t = time.localtime(time.time()) self.time = "%04d-%02d-%02dT%02d:%02d:%02d" % t[:6] @@ -397,7 +397,7 @@ class ODSTab(TabbedDoc): def _write_zip(self): try: - file = zipfile.ZipFile(self.filename,"w",zipfile.ZIP_DEFLATED) + file = zipfile.ZipFile(self.filename,"w",zipfile.ZIP_DEFLATED) except IOError as msg: errmsg = "%s\n%s" % (_("Could not create %s") % self.filename, msg) raise ReportError(errmsg) @@ -415,10 +415,10 @@ class ODSTab(TabbedDoc): os.unlink(self.content_xml) os.unlink(self.meta_xml) os.unlink(self.styles_xml) - + def _write_styles_file(self): self.styles_xml = tempfile.mktemp() - + try: self.f = open(self.styles_xml,"wb") except IOError as msg: @@ -439,7 +439,7 @@ class ODSTab(TabbedDoc): self.f.write(_STYLES_STYLES) self.f.write(_STYLES_AUTOMATIC) self.f.write(_STYLES_MASTER) - + self.f.write('\n') self.f.close() @@ -450,7 +450,7 @@ class ODSTab(TabbedDoc): def end_page(self): self.f.write('\n') - + def _write_manifest(self): self.manifest_xml = tempfile.mktemp() @@ -480,7 +480,7 @@ class ODSTab(TabbedDoc): raise ReportError(_("Could not create %s") % self.meta_xml) self.f = open(self.meta_xml,"w") - + self.f.write(_META % {'program': PROGRAM_NAME, 'version': VERSION, diff --git a/gramps/gen/utils/docgen/tabbeddoc.py b/gramps/gen/utils/docgen/tabbeddoc.py index 494be6477..5ee0c8dd8 100644 --- a/gramps/gen/utils/docgen/tabbeddoc.py +++ b/gramps/gen/utils/docgen/tabbeddoc.py @@ -20,7 +20,7 @@ #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class TabbedDoc(object): diff --git a/gramps/gen/utils/grampslocale.py b/gramps/gen/utils/grampslocale.py index 4cdbc1e34..309b98c63 100644 --- a/gramps/gen/utils/grampslocale.py +++ b/gramps/gen/utils/grampslocale.py @@ -968,8 +968,8 @@ class Lexeme(str): Prints out:: In English locale: - CHRISTMAS - Christmas is celebrated in December + CHRISTMAS + Christmas is celebrated in December Merry Christmas! In Russian locale: @@ -983,17 +983,17 @@ class Lexeme(str): These forms are accessible under dictionary keys for each form. The names of the forms are language-specific. They are assigned by the human translator of the corresponding language (in XX.po) - as in the example above, - see :meth:`~GrampsTranslations.lexgettext` docs + as in the example above, + see :meth:`~GrampsTranslations.lexgettext` docs for more info. The translated format string can then refer to a specific form - of the lexeme using ``.``:attr:`~Lexeme.f` and square brackets: + of the lexeme using ``.``:attr:`~Lexeme.f` and square brackets: ``{holiday.f[GENITIVE]}`` expects holiday to be a Lexeme which has a form ``'GENITIVE'`` in it. An instance of Lexeme can also be used as a regular unicode string. - In this case, the work will be delegated to the string for the very + In this case, the work will be delegated to the string for the very first form provided in the translated string. In the example above, ``{holiday}`` in the translated string will expand to the Russian nominative form for Christmas, and ``xmas.upper()`` will produce @@ -1001,9 +1001,9 @@ class Lexeme(str): .. rubric:: Motivation - Lexeme is the term used in linguistics for the set of forms taken + Lexeme is the term used in linguistics for the set of forms taken by a particular word, e.g. cases for a noun or tenses for a verb. - + Gramps often needs to compose sentences from several blocks of text and single words, often by using python string formatting. @@ -1016,7 +1016,7 @@ class Lexeme(str): enddate_month = m2, enddate_year = y2) - To make such text translatable, the arguments injected into + To make such text translatable, the arguments injected into format string need to bear all the linguistical information on how to plug them into a sentence, i.e., the forms, depending on the linguistic context of where the argument appears. @@ -1025,8 +1025,8 @@ class Lexeme(str): On the other hand, for languages where there is no linguistic variation in such sentences, the code needs not to be aware of - the underlying :class:`~Lexeme` complexity; - and so they can be processed just like simple strings + the underlying :class:`~Lexeme` complexity; + and so they can be processed just like simple strings both when passed around in the code and when formatted. """ @@ -1036,7 +1036,7 @@ class Lexeme(str): else: od = collections.OrderedDict(iterable) l = list(od.values()) or [""] - newobj = str.__new__(cls, l[0], *args, **kwargs) + newobj = str.__new__(cls, l[0], *args, **kwargs) newobj._forms = od return newobj @@ -1044,7 +1044,7 @@ class Lexeme(str): """All lexeme forms, in the same order as given upon construction. The first one returned is the default form, which is used when the Lexeme instance is used in lieu of a string object. - + Same as ``f.values()``""" return self._forms.values() @@ -1125,7 +1125,7 @@ class GrampsTranslations(gettext.GNUTranslations): stripping the '|'-separated context using :meth:`~sgettext` The *resulting* message provided by the translator - is supposed to be '|'-separated as well. + is supposed to be '|'-separated as well. The possible formats are either (1) a single string for a language with no inflections, or (2) a list of =, separated with '|'. diff --git a/gramps/gen/utils/id.py b/gramps/gen/utils/id.py index 6f5f6f96e..f8e8f21b0 100644 --- a/gramps/gen/utils/id.py +++ b/gramps/gen/utils/id.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -49,7 +49,7 @@ from ..const import GRAMPS_UUID rand = random.Random(time.time()) def create_id(): - return "%08x%08x" % (int(time.time()*10000), + return "%08x%08x" % (int(time.time()*10000), rand.randint(0, sys.maxsize)) def create_uid(self, handle=None): diff --git a/gramps/gen/utils/image.py b/gramps/gen/utils/image.py index c66fbdb71..dd07833c1 100644 --- a/gramps/gen/utils/image.py +++ b/gramps/gen/utils/image.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -218,7 +218,7 @@ def resize_to_buffer(source, size, crop=None): :type size: list :param crop: cropping coordinates :type crop: array of integers ([start_x, start_y, end_x, end_y]) - :rtype: buffer of data + :rtype: buffer of data :returns: raw data """ from gi.repository import GdkPixbuf @@ -229,7 +229,7 @@ def resize_to_buffer(source, size, crop=None): ) = crop_percentage_to_pixel( img.get_width(), img.get_height(), crop) img = img.new_subpixbuf(start_x, start_y, end_x-start_x, end_y-start_y) - + # Need to keep the ratio intact, otherwise scaled images look stretched # if the dimensions aren't close in size (size[0], size[1]) = image_actual_size(size[0], size[1], img.get_width(), img.get_height()) @@ -254,7 +254,7 @@ def resize_to_jpeg_buffer(source, size, crop=None): :type size: list :param crop: cropping coordinates :type crop: array of integers ([start_x, start_y, end_x, end_y]) - :rtype: buffer of data + :rtype: buffer of data :returns: jpeg image as raw data """ from gi.repository import GdkPixbuf diff --git a/gramps/gen/utils/keyword.py b/gramps/gen/utils/keyword.py index a3d45e15b..c294cb061 100644 --- a/gramps/gen/utils/keyword.py +++ b/gramps/gen/utils/keyword.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -21,7 +21,7 @@ # """ -Keyword translation interface +Keyword translation interface """ # keyword, code, translated standard, translated upper @@ -37,7 +37,7 @@ Keyword translation interface # '1m': primary[sur]= surname primary surname (main) # '2m': primary[con]= connector primary surname (main) # 'y' : patronymic = pa/matronymic surname (father/mother) - assumed unique -# '0y': patronymic[pre] = prefix " +# '0y': patronymic[pre] = prefix " # '1y': patronymic[sur] = surname " # '2y': patronymic[con] = connector " # 'o' : notpatronymic = surnames without pa/matronymic and primary diff --git a/gramps/gen/utils/lds.py b/gramps/gen/utils/lds.py index 6239b0f68..60b84dc26 100644 --- a/gramps/gen/utils/lds.py +++ b/gramps/gen/utils/lds.py @@ -36,7 +36,7 @@ class LdsTemples(object): """ Parsing class for the LDS temples file """ - + def __init__(self): """ Parses the lds.xml file to load the LDS temple code to name @@ -82,18 +82,18 @@ class LdsTemples(object): def name(self, code): """ - returns the name associated with the LDS Temple code + returns the name associated with the LDS Temple code """ return self.__temple_to_abrev.get(code, _("Unknown")) - + def name_code_data(self): """ returns a list of temple codes, temple name tuples """ - return sorted([(code, name) for name, code + return sorted([(code, name) for name, code in self.__temple_codes.items()], key=lambda v: v[1]) - + def __start_element(self, tag, attrs): """ XML parsing function that is called when an XML element is first found diff --git a/gramps/gen/utils/libformatting.py b/gramps/gen/utils/libformatting.py index 2ce8d77d7..b48a53d95 100644 --- a/gramps/gen/utils/libformatting.py +++ b/gramps/gen/utils/libformatting.py @@ -20,7 +20,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -"""Format of commonly used expressions, making use of a cache to not +"""Format of commonly used expressions, making use of a cache to not recompute """ #------------------------------------------------------------------------- @@ -39,7 +39,7 @@ from ..lib import EventType from ..datehandler import get_date from ..display.name import displayer as name_displayer from ..display.place import displayer as place_displayer -from .db import (get_birth_or_fallback, get_death_or_fallback, +from .db import (get_birth_or_fallback, get_death_or_fallback, get_marriage_or_fallback) #------------------------------------------------------------------------- @@ -48,14 +48,14 @@ from .db import (get_birth_or_fallback, get_death_or_fallback, # #------------------------------------------------------------------------- class FormattingHelper(object): - """Format of commonly used expressions, making use of a cache to not + """Format of commonly used expressions, making use of a cache to not recompute """ def __init__(self, dbstate): self.dbstate = dbstate self._text_cache = {} self._markup_cache = {} - + def format_relation(self, family, line_count, use_markup=False): """ Format a relation between parents of a family """ @@ -101,10 +101,10 @@ class FormattingHelper(object): if line_count >= 3: text += mplace text += "\n" - + if not text: text = str(family.get_relationship()) - + if use_markup: if not family.handle in self._markup_cache: self._markup_cache[family.handle] = {} @@ -113,7 +113,7 @@ class FormattingHelper(object): if not family.handle in self._text_cache: self._text_cache[family.handle] = {} self._text_cache[family.handle][line_count] = text - + return text def get_place_name(self, place_handle): @@ -175,7 +175,7 @@ class FormattingHelper(object): else: ddate = "" dplace = "" - + if line_count < 5: text = "%s\n* %s\n+ %s" % (name, bdate, ddate) else: @@ -205,14 +205,14 @@ class ImportInfo(object): def __init__(self, default_info=None): """ Init of the import class. - + This creates the datastructures to hold info """ if default_info is None: self.info = {} else: self.info = default_info - + def info_text(self): """ Construct an info message from the data in the class. diff --git a/gramps/gen/utils/location.py b/gramps/gen/utils/location.py index 181406274..7b78e894b 100644 --- a/gramps/gen/utils/location.py +++ b/gramps/gen/utils/location.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. diff --git a/gramps/gen/utils/place.py b/gramps/gen/utils/place.py index d9486e2a1..3ebf87d98 100644 --- a/gramps/gen/utils/place.py +++ b/gramps/gen/utils/place.py @@ -83,7 +83,7 @@ def __convert_structure_to_float(sign, degs, mins=0, secs=0.0) : """helper function which converts a structure to a nice representation """ - v = float(degs) + v = float(degs) if mins is not None: v += float(mins) / 60. if secs is not None: @@ -94,8 +94,8 @@ def __convert_using_float_repr(stringValue): """ helper function that tries to convert the string using the float representation """ - try : - v = float(stringValue) + try : + v = float(stringValue) return v except ValueError : return None; @@ -174,7 +174,7 @@ def __convert_using_classic_repr(stringValue, typedeg): if len(l) != 2: return None - try: + try: degs = int(l[0]) #degrees must be integer value if degs < 0: return None @@ -214,7 +214,7 @@ def __convert_using_classic_repr(stringValue, typedeg): last = l3[0] secs = 0. if len(l3) > 2: - return None + return None if len(l3) == 2: last = l3[1] try: @@ -269,14 +269,14 @@ def __convert_using_modgedcom_repr(val, typedeg): stringValue = '-' + val[:pos] else: return None - try : - v = float(stringValue) + try : + v = float(stringValue) return v except ValueError : return None; def __convert_float_val(val, typedeg = "lat"): - # function converting input to float, recognizing decimal input, or + # function converting input to float, recognizing decimal input, or # degree notation input. Only english input # There is no check on maximum/minimum of degree # In case of degree minutes seconds direction input, @@ -284,32 +284,32 @@ def __convert_float_val(val, typedeg = "lat"): # 0<= seconds <= 60, direction is in the directions dic. #change , to . so that , input works in non , localization - #this is no problem, as a number like 100,000.20 cannot appear in + #this is no problem, as a number like 100,000.20 cannot appear in #lat/lon - #change XX,YY into XX.YY + #change XX,YY into XX.YY if val.find(r'.') == -1 : val = val.replace(',', '.') - + # format: XX.YYYY - v = __convert_using_float_repr(val) + v = __convert_using_float_repr(val) if v is not None: return v # format: XX:YY:ZZ - v = __convert_using_colon_repr(val) - if v is not None : + v = __convert_using_colon_repr(val) + if v is not None : return v # format: XX° YY' ZZ" [NSWE] - v = __convert_using_classic_repr(val, typedeg) - if v is not None : + v = __convert_using_classic_repr(val, typedeg) + if v is not None : return v # format XX.YYYY[NSWE] v = __convert_using_modgedcom_repr(val, typedeg) if v is not None : return v - + # no format succeeded return None @@ -321,7 +321,7 @@ def __convert_float_val(val, typedeg = "lat"): def conv_lat_lon(latitude, longitude, format="D.D4"): """ - Convert given string latitude and longitude to a required format. + Convert given string latitude and longitude to a required format. :param latitude: Latitude :type latitude: string @@ -354,14 +354,14 @@ def conv_lat_lon(latitude, longitude, format="D.D4"): i.e. ±DDMMSS.SS±DDDMMSS.SS 'RT90' Output format for the Swedish coordinate system RT90 ========= ============================================================ - + Some generalities: * -90 <= latitude <= +90 with +00 the equator * -180 <= longitude < +180 with +000 prime meridian and -180 the 180th meridian """ - + # we start the function changing latitude/longitude in english if latitude.find('N') == -1 and latitude.find('S') == -1: # entry is not in english, convert to english @@ -398,7 +398,7 @@ def conv_lat_lon(latitude, longitude, format="D.D4"): return None else: return (None, None) - + if format == "D.D4": # correct possible roundoff error str_lon = "%.4f" % (lon_float) @@ -416,7 +416,7 @@ def conv_lat_lon(latitude, longitude, format="D.D4"): return ("%i" % tx[0], "%i" % tx[1]) else: return ("%.8f" % lat_float , str_lon) - + if format == "GEDCOM": # The 5.5.1 spec is inconsistent. Length is supposedly 5 to 8 chars, # but the sample values are longer, using up to 6 fraction digits. @@ -431,11 +431,11 @@ def conv_lat_lon(latitude, longitude, format="D.D4"): str_lon = "E" + str_lon else: str_lon = "W" + "%.6f" % (-lon_float) - str_lon = str_lon[:-5] + str_lon[-5:].rstrip("0") + str_lon = str_lon[:-5] + str_lon[-5:].rstrip("0") str_lat = ("%s%.6f" % (("N", lat_float) if lat_float >= 0 else ("S", -lat_float))) - str_lat = str_lat[:-5] + str_lat[-5:].rstrip("0") + str_lat = str_lat[:-5] + str_lat[-5:].rstrip("0") return (str_lat, str_lon) - + deg_lat = int(lat_float) deg_lon = int(lon_float) min_lat = int(60. * (lat_float - float(deg_lat) )) @@ -471,7 +471,7 @@ def conv_lat_lon(latitude, longitude, format="D.D4"): else: dir_lon = translate_en_loc['W'] sign_lon= "-" - + if format == "DEG": str_lat = ("%d°%02d'%05.2f\"" % (deg_lat, min_lat, sec_lat)) + dir_lat str_lon = ("%d°%02d'%05.2f\"" % (deg_lon, min_lon, sec_lon)) + dir_lon @@ -506,7 +506,7 @@ def conv_lat_lon(latitude, longitude, format="D.D4"): str_lon = sign_lon_h + ("%d:%02d:%05.2f" % (deg_lon, min_lon, sec_lon)) # correct possible roundoff error in seconds - + if str_lat[-5] == '6': if min_lat == 59: str_lat = sign_lat + ("%d:%02d:%05.2f" % (deg_lat+1, 0, 0.)) @@ -523,7 +523,7 @@ def conv_lat_lon(latitude, longitude, format="D.D4"): else: str_lon = sign_lon_h + \ ("%d:%02d:%05.2f" % (deg_lon, min_lon+1, 0.)) - + return (str_lat, str_lon) if format == "ISO-D": # ±DD.DDDD±DDD.DDDD @@ -546,19 +546,19 @@ def conv_lat_lon(latitude, longitude, format="D.D4"): str_lon = "-" + ("%03d%06.3f" % (180, 0.)) else: str_lon = sign_lon + ("%03d%06.3f" % (deg_lon+1, 0.)) - return str_lat + str_lon + return str_lat + str_lon if format == "ISO-DMS": # ±DDMMSS.SS±DDDMMSS.SS str_lat = sign_lat + ("%02d%02d%06.3f" % (deg_lat, min_lat, sec_lat)) str_lon = sign_lon + ("%03d%02d%06.3f" % (deg_lon, min_lon, sec_lon)) # correct possible roundoff error - if str_lat[5:] == "60.000": + if str_lat[5:] == "60.000": if min_lat == 59: str_lat = sign_lat + ("%02d%02d%06.3f" % (deg_lat+1, 0, 0.)) else: str_lat = sign_lat + \ ("%02d%02d%06.3f" % (deg_lat, min_lat +1, 0.)) - if str_lon[6:] == "60.000": + if str_lon[6:] == "60.000": if min_lon == 59: if deg_lon == 179 and sign_lon == "+": str_lon = "-" + ("%03d%02d%06.3f" % (180, 0, 0)) @@ -575,14 +575,14 @@ def conv_lat_lon(latitude, longitude, format="D.D4"): def atanh(x): """arctangent hyperbolicus""" return 1.0/2.0*math.log((1.0 + x)/(1.0 -x)) - + def __conv_WGS84_SWED_RT90(lat, lon): """ Input is lat and lon as two float numbers Output is X and Y coordinates in RT90 as a tuple of float numbers - + The code below converts to/from the Swedish RT90 koordinate system. The converion functions use "Gauss Conformal Projection (Transverse Marcator)" Krüger Formulas. @@ -631,7 +631,7 @@ def __conv_WGS84_SWED_RT90(lat, lon): X = X*k0*at + FN Y = Y*k0*at + FE return (X, Y) - + def __conv_SWED_RT90_WGS84(X, Y): """ Input is X and Y coordinates in RT90 as float @@ -647,7 +647,7 @@ def __conv_SWED_RT90_WGS84(X, Y): at = a/(1.0+n)*(1.0+ 1.0/4.0* pow(n,2)+1.0/64.0*pow(n,4)) FN = -667.711 # m FE = 1500064.274 # m - + xi = (X - FN)/(k0*at) eta = (Y - FE)/(k0*at) D1 = 1.0/2.0*n - 2.0/3.0*pow(n,2) + 37.0/96.0*pow(n,3) - 1.0/360.0*pow(n,4) @@ -681,7 +681,7 @@ def __conv_SWED_RT90_WGS84(X, Y): #------------------------------------------------------------------------- # # For Testing the convert function in this module, apply it as a script: -# ==> in command line do "python PlaceUtils.py" +# ==> in command line do "python PlaceUtils.py" # #------------------------------------------------------------------------- @@ -715,12 +715,12 @@ if __name__ == '__main__': print(lat1,lon1,"in format",format7, "is",res1,res2,"\n") res1, res2 = conv_lat_lon(lat1,lon1,format8) print(lat1,lon1,"in format",format8, "is",res1,res2,"\n") - + def test_formats_fail(lat1,lon1,text=''): print("This test should make conv_lat_lon function fail, "+text+":") res1, res2 = conv_lat_lon(lat1,lon1) print(lat1,lon1," fails to convert, result=", res1,res2,"\n") - + def test_RT90_conversion(): """ a given lat/lon is converted to RT90 and back as a test: @@ -731,7 +731,7 @@ if __name__ == '__main__': lanew, lonew = __conv_SWED_RT90_WGS84(x,y) assert math.fabs(lanew - la) < 1e-6, math.fabs(lanew - la) assert math.fabs(lonew - lo) < 1e-6, math.fabs(lonew - lo) - + lat, lon = '50.849888888888', '2.885897222222' test_formats_success(lat,lon) lat, lon = ' 50°50\'59.60"N', ' 2°53\'9.23"E' diff --git a/gramps/gen/utils/resourcepath.py b/gramps/gen/utils/resourcepath.py index 36c6d6b88..11beac187 100644 --- a/gramps/gen/utils/resourcepath.py +++ b/gramps/gen/utils/resourcepath.py @@ -33,7 +33,7 @@ class ResourcePath(object): ResourcePath is a singleton, meaning that only one of them is ever created. At startup it finds the paths to Gramps's resource files and caches them for future use. - + It should be called only by const.py; other code should retrieve the paths from there. """ diff --git a/gramps/gen/utils/string.py b/gramps/gen/utils/string.py index 896b65ffe..68231030b 100644 --- a/gramps/gen/utils/string.py +++ b/gramps/gen/utils/string.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -43,35 +43,35 @@ def _T_(value): # enable deferred translations (see Python docs 22.1.3.4) # #------------------------------------------------------------------------- gender = { - Person.MALE : _("male"), - Person.FEMALE : _("female"), - Person.UNKNOWN : _("gender|unknown"), + Person.MALE : _("male"), + Person.FEMALE : _("female"), + Person.UNKNOWN : _("gender|unknown"), } def format_gender( type): return gender.get(type[0], _("Invalid")) conf_strings = { - Citation.CONF_VERY_HIGH : _T_("Very High"), - Citation.CONF_HIGH : _T_("High"), - Citation.CONF_NORMAL : _T_("Normal"), - Citation.CONF_LOW : _T_("Low"), - Citation.CONF_VERY_LOW : _T_("Very Low"), + Citation.CONF_VERY_HIGH : _T_("Very High"), + Citation.CONF_HIGH : _T_("High"), + Citation.CONF_NORMAL : _T_("Normal"), + Citation.CONF_LOW : _T_("Low"), + Citation.CONF_VERY_LOW : _T_("Very Low"), } # note that a list /very/ similar to this is in EditCitation._setup_fields # but that has the glocale's translated values since it is used in the UI family_rel_descriptions = { FamilyRelType.MARRIED : _("A legal or common-law relationship " - "between a husband and wife"), + "between a husband and wife"), FamilyRelType.UNMARRIED : _("No legal or common-law relationship " - "between man and woman"), + "between man and woman"), FamilyRelType.CIVIL_UNION : _("An established relationship between " - "members of the same sex"), + "members of the same sex"), FamilyRelType.UNKNOWN : _("Unknown relationship between a man " - "and woman"), + "and woman"), FamilyRelType.CUSTOM : _("An unspecified relationship between " - "a man and woman"), + "a man and woman"), } data_recover_msg = _('The data can only be recovered by Undo operation ' diff --git a/gramps/gen/utils/test/callback_test.py b/gramps/gen/utils/test/callback_test.py index d7e49c08b..aa5a71567 100644 --- a/gramps/gen/utils/test/callback_test.py +++ b/gramps/gen/utils/test/callback_test.py @@ -46,7 +46,7 @@ class TestCallback(unittest.TestCase): t.connect('test-signal',fn) t.emit('test-signal',(1,)) - + self.assertEqual(len(rl), 1, "No signal emitted") self.assertEqual(rl[0], 1, "Wrong argument recieved") @@ -76,16 +76,16 @@ class TestCallback(unittest.TestCase): def null(s): pass - + global log _log = log log = null - + t.connect('test-signal',borked) t.connect('test-signal',fn) t.emit('test-signal',(1,)) log = _log - + self.assertEqual(len(rl), 1, "No signal emitted") self.assertEqual(rl[0], 1, "Wrong argument recieved") @@ -105,14 +105,14 @@ class TestCallback(unittest.TestCase): key = t.connect('test-signal',fn) t.emit('test-signal',(1,)) - + self.assertEqual(len(rl), 1, "No signal emitted") self.assertEqual(rl[0], 1, "Wrong argument recieved") t.disconnect(key) t.emit('test-signal',(1,)) - + self.assertEqual(len(rl), 1, "Callback not disconnected") self.assertEqual(rl[0], 1, "Callback not disconnected") @@ -132,7 +132,7 @@ class TestCallback(unittest.TestCase): t.connect('test-noargs',fn) t.emit('test-noargs') - + self.assertEqual(len(rl), 1, "No signal emitted") self.assertEqual(rl[0], 1, "Wrong argument recieved") @@ -153,7 +153,7 @@ class TestCallback(unittest.TestCase): __signals__ = { 'test-signal' : (int,) } - + class TestSignalsSubclass(TestSignals): __signals__ = { 'test-sub-signal' : (int,), @@ -166,13 +166,13 @@ class TestCallback(unittest.TestCase): t = TestSignalsSubclass() t.connect('test-signal',fn) t.emit('test-signal',(1,)) - + self.assertEqual(len(rl), 1, "No signal emitted") self.assertEqual(rl[0], 1, "Wrong argument recieved") t.connect('test-sub-signal',fn) t.emit('test-sub-signal',(1,)) - + self.assertEqual(len(rl), 2, "No subclass signal emitted") self.assertEqual(rl[1], 1, "Wrong argument recieved in subclass") @@ -190,25 +190,25 @@ class TestCallback(unittest.TestCase): t = TestSignals() t.connect('test-signal',fn) - t.emit('test-signal',(1,)) - + t.emit('test-signal',(1,)) + self.assertEqual(len(rl), 1, "No signal emitted") self.assertEqual(rl[0], 1, "Wrong argument recieved") Callback.disable_all_signals() - t.emit('test-signal',(1,)) + t.emit('test-signal',(1,)) self.assertEqual(len(rl), 1, "Signal emitted while class blocked") Callback.enable_all_signals() - t.emit('test-signal',(1,)) + t.emit('test-signal',(1,)) self.assertEqual(len(rl), 2, "Signals not class unblocked") t.disable_signals() - t.emit('test-signal',(1,)) + t.emit('test-signal',(1,)) self.assertEqual(len(rl), 2, "Signal emitted while instance blocked") t.enable_signals() - t.emit('test-signal',(1,)) + t.emit('test-signal',(1,)) self.assertEqual(len(rl), 3, "Signals not instance unblocked") def test_type_checking(self): @@ -318,7 +318,7 @@ class TestCallback(unittest.TestCase): except RuntimeError: self.fail("multisignal recursion not blocked1.") - self.assertEqual(res[0][0:6], "Signal", + self.assertEqual(res[0][0:6], "Signal", "multisignal recursion not blocked") if __name__ == "__main__": diff --git a/gramps/gen/utils/test/grampslocale_test.py b/gramps/gen/utils/test/grampslocale_test.py index a161afbb7..f88396f09 100644 --- a/gramps/gen/utils/test/grampslocale_test.py +++ b/gramps/gen/utils/test/grampslocale_test.py @@ -29,7 +29,7 @@ try: from unittest.mock import Mock MOCKING = True - + except: MOCKING = False print ("Mocking disabled, some testing skipped", sys.exc_info()[0:2]) @@ -74,7 +74,7 @@ class LexGettextTest(unittest.TestCase): translated = "def=Default|v1=Option1|a=AnotherOption" self.setup_sgettext_mock(translated) lex = self.trans.lexgettext(self.MSGID) - formatted = "{}".format(lex) + formatted = "{}".format(lex) self.assertEqual(formatted, "Default") class LexemeTest(unittest.TestCase): @@ -89,7 +89,7 @@ class LexemeTest(unittest.TestCase): # test delegation to an arbitrary string method pulled in from unicode def testDefaultStringStartsWithAA(self): - self.assertTrue(self.lex.startswith('aa'), + self.assertTrue(self.lex.startswith('aa'), msg="default string: {} dict: {}".format( self.lex, self.lex.__dict__)) diff --git a/gramps/gen/utils/test/keyword_test.py b/gramps/gen/utils/test/keyword_test.py index fde60f381..a289616ca 100644 --- a/gramps/gen/utils/test/keyword_test.py +++ b/gramps/gen/utils/test/keyword_test.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -22,7 +22,7 @@ import unittest -from ..keyword import (KEYWORDS, get_translation_from_keyword, +from ..keyword import (KEYWORDS, get_translation_from_keyword, get_keyword_from_translation) class TestCase(unittest.TestCase): diff --git a/gramps/gen/utils/test/place_test.py b/gramps/gen/utils/test/place_test.py index 16e468414..17f978499 100644 --- a/gramps/gen/utils/test/place_test.py +++ b/gramps/gen/utils/test/place_test.py @@ -239,10 +239,10 @@ class PlaceTest(unittest.TestCase): """A given lat/lon is converted to RT90 and back""" x, y = conv_lat_lon('59:40:9.09', '12:58:57.74', 'RT90') lat, lon = conv_SWED_RT90_WGS84(float(x), float(y)) - + expetced_lat = 59.0 + 40.0/60. + 9.09/3600.0 expetced_lon = 12.0 + 58.0/60.0 + 57.74/3600.0 - + self.assertAlmostEqual(lat, expetced_lat, places=3) self.assertAlmostEqual(lon, expetced_lon, places=3) @@ -262,7 +262,7 @@ def conv_SWED_RT90_WGS84(X, Y): at = a/(1.0+n)*(1.0+ 1.0/4.0* pow(n,2)+1.0/64.0*pow(n,4)) FN = -667.711 # m FE = 1500064.274 # m - + xi = (X - FN)/(k0*at) eta = (Y - FE)/(k0*at) D1 = 1.0/2.0*n - 2.0/3.0*pow(n,2) + 37.0/96.0*pow(n,3) - 1.0/360.0*pow(n,4) diff --git a/gramps/gen/utils/thumbnails.py b/gramps/gen/utils/thumbnails.py index fbef7fa85..36bf0761a 100644 --- a/gramps/gen/utils/thumbnails.py +++ b/gramps/gen/utils/thumbnails.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -50,7 +50,7 @@ except: # gramps modules # #------------------------------------------------------------------------- -from gramps.gen.const import (ICON, IMAGE_DIR, THUMB_LARGE, THUMB_NORMAL, +from gramps.gen.const import (ICON, IMAGE_DIR, THUMB_LARGE, THUMB_NORMAL, THUMBSCALE, THUMBSCALE_LARGE, USE_THUMBNAILER) from gramps.gen.constfunc import win @@ -62,7 +62,7 @@ from gramps.gen.constfunc import win #------------------------------------------------------------------------- try: #test first for the key to avoid an error in the importer that causes - #the error logger to activate + #the error logger to activate ##TODO GTK3: Is this the best way to avoid error? import gi.repository as repo repo.__dict__['GConf'] @@ -159,7 +159,7 @@ def __build_thumb_path(path, rectangle=None, size=SIZE_NORMAL): # __create_thumbnail_image # #------------------------------------------------------------------------- -def __create_thumbnail_image(src_file, mtype=None, rectangle=None, +def __create_thumbnail_image(src_file, mtype=None, rectangle=None, size=SIZE_NORMAL): """ Generates the thumbnail image for a file. If the mime type is specified, @@ -182,7 +182,7 @@ def __create_thumbnail_image(src_file, mtype=None, rectangle=None, # Not an image, so run the thumbnailer return run_thumbnailer(mtype, src_file, filename) else: - # build a thumbnail by scaling the image using GTK's built in + # build a thumbnail by scaling the image using GTK's built in # routines. try: pixbuf = GdkPixbuf.Pixbuf.new_from_file(src_file) @@ -202,17 +202,17 @@ def __create_thumbnail_image(src_file, mtype=None, rectangle=None, pixbuf = pixbuf.new_subpixbuf(sub_x, sub_y, sub_width, sub_height) width = sub_width height = sub_height - + if size == SIZE_LARGE: thumbscale = THUMBSCALE_LARGE else: thumbscale = THUMBSCALE scale = thumbscale / (float(max(width, height))) - + scaled_width = int(width * scale) scaled_height = int(height * scale) - - pixbuf = pixbuf.scale_simple(scaled_width, scaled_height, + + pixbuf = pixbuf.scale_simple(scaled_width, scaled_height, GdkPixbuf.InterpType.BILINEAR) pixbuf.savev(filename, "png", "", "") return True @@ -259,17 +259,17 @@ def run_thumbnailer(mime_type, src_file, dest_file, size=SIZE_NORMAL): :type src_file: unicode :param dest_file: destination file for the thumbnail image :type dest_file: unicode - :param size: option parameters specifying the desired size of the + :param size: option parameters specifying the desired size of the thumbnail :type size: int :returns: True if the thumbnail was successfully generated :rtype: bool """ - # only try this if GCONF is present, the thumbnailer has not been + # only try this if GCONF is present, the thumbnailer has not been # disabled, and if the src_file actually exists if GCONF and USE_THUMBNAILER and os.path.isfile(src_file): - - # find the command and enable for the associated mime types by + + # find the command and enable for the associated mime types by # querying the gconf database base = '/desktop/gnome/thumbnailers/%s' % mime_type.replace('/', '@') cmd = __get_gconf_string(base + '/command') @@ -284,8 +284,8 @@ def run_thumbnailer(mime_type, src_file, dest_file, size=SIZE_NORMAL): thumbscale = THUMBSCALE sublist = { '%s' : "%d" % int(thumbscale), - '%u' : src_file, - '%o' : dest_file, + '%u' : src_file, + '%o' : dest_file, } cmdlist = [ sublist.get(x, x) for x in cmd.split() ] return os.spawnvpe(os.P_WAIT, cmdlist[0], cmdlist, os.environ) == 0 @@ -299,7 +299,7 @@ def run_thumbnailer(mime_type, src_file, dest_file, size=SIZE_NORMAL): def get_thumbnail_image(src_file, mtype=None, rectangle=None, size=SIZE_NORMAL): """ Return the thumbnail image (in GTK Pixbuf format) associated with the - source file passed to the function. If no thumbnail could be found, + source file passed to the function. If no thumbnail could be found, the associated icon for the mime type is returned, or if that cannot be found, a generic document icon is returned. @@ -333,7 +333,7 @@ def get_thumbnail_image(src_file, mtype=None, rectangle=None, size=SIZE_NORMAL): def get_thumbnail_path(src_file, mtype=None, rectangle=None, size=SIZE_NORMAL): """ Return the path to the thumbnail image associated with the - source file passed to the function. If the thumbnail does not exist, + source file passed to the function. If the thumbnail does not exist, or if it is older than the source file, we create a new thumbnail image. :param src_file: Source media file diff --git a/gramps/gen/utils/unknown.py b/gramps/gen/utils/unknown.py index 794874f43..c092181ef 100644 --- a/gramps/gen/utils/unknown.py +++ b/gramps/gen/utils/unknown.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -66,7 +66,7 @@ def make_unknown(class_arg, explanation, class_func, commit_func, transaction, This function exploits the fact that all import methods basically do the same thing: Create an object of the right type, fill it with some attributes, store it in the database. This function does the same, so - the observation is why not use the creation and storage methods that the + the observation is why not use the creation and storage methods that the import routines use themselves, that makes nice reuse of code. To do this formally correct we would need to specify a interface (in the OOP sence) which the import methods would need to implement. For now, that is deemed diff --git a/gramps/grampsapp.py b/gramps/grampsapp.py index e2d7215e7..bc601f6be 100644 --- a/gramps/grampsapp.py +++ b/gramps/grampsapp.py @@ -68,8 +68,8 @@ form = logging.Formatter(fmt="%(asctime)s.%(msecs).03d: %(levelname)s: " if win(): # If running in GUI mode redirect stdout and stderr to log file if hasattr(sys.stdout, "fileno") and sys.stdout.fileno() < 0: - logfile = os.path.join(HOME_DIR, - "Gramps%s%s.log") % (VERSION_TUPLE[0], + logfile = os.path.join(HOME_DIR, + "Gramps%s%s.log") % (VERSION_TUPLE[0], VERSION_TUPLE[1]) # We now carry out the first step in build_user_paths(), to make sure # that the user home directory is available to store the log file. When @@ -131,7 +131,7 @@ if not sys.version_info >= MIN_PYTHON_VERSION : "requirements. At least python %(v1)d.%(v2)d.%(v3)d is needed to" " start Gramps.\n\n" "Gramps will terminate now.") % { - 'v1': MIN_PYTHON_VERSION[0], + 'v1': MIN_PYTHON_VERSION[0], 'v2': MIN_PYTHON_VERSION[1], 'v3': MIN_PYTHON_VERSION[2]}) sys.exit(1) @@ -164,7 +164,7 @@ def show_settings(): try: from gi.repository import Gtk try: - gtkver_str = '%d.%d.%d' % (Gtk.get_major_version(), + gtkver_str = '%d.%d.%d' % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()) except : # any failure to 'get' the version gtkver_str = 'unknown version' @@ -198,7 +198,7 @@ def show_settings(): try: import cairo try: - pycairover_str = '%d.%d.%d' % cairo.version_info + pycairover_str = '%d.%d.%d' % cairo.version_info cairover_str = cairo.cairo_version_string() except :# any failure to 'get' the version pycairover_str = 'unknown version' @@ -260,7 +260,7 @@ def show_settings(): bsddb_str = 'not found' bsddb_db_str = 'not found' - try: + try: from .gen.const import VERSION gramps_str = VERSION except: @@ -300,7 +300,7 @@ def show_settings(): os_path = get_env_var('PATH','not set') os_path = os_path.split(os.pathsep) - + print ("Gramps Settings:") print ("----------------") print (' python : %s' % py_str) @@ -344,24 +344,24 @@ def show_settings(): def run(): error = [] - + try: - build_user_paths() + build_user_paths() except OSError as msg: error += [(_("Configuration error:"), str(msg))] return error except msg: LOG.error("Error reading configuration.", exc_info=True) return [(_("Error reading configuration"), str(msg))] - + if not mime_type_is_defined(APP_GRAMPS): - error += [(_("Configuration error:"), + error += [(_("Configuration error:"), _("A definition for the MIME-type %s could not " "be found \n\n Possibly the installation of Gramps " "was incomplete. Make sure the MIME-types " "of Gramps are properly installed.") % APP_GRAMPS)] - + #we start with parsing the arguments to determine if we have a cli or a # gui session @@ -373,7 +373,7 @@ def run(): argv_copy = sys.argv[:] argpars = ArgParser(argv_copy) - # Calls to LOG must be after setup_logging() and ArgParser() + # Calls to LOG must be after setup_logging() and ArgParser() LOG = logging.getLogger(".locale") LOG.debug("Encoding: %s", glocale.encoding) LOG.debug("Translating Gramps to %s", glocale.language[0]) @@ -392,7 +392,7 @@ def run(): get_env_var('LANGUAGE')) else: LOG.debug('environment: LANGUAGE is not defined') - + if argpars.need_gui(): LOG.debug("A GUI is needed, set it up") if "--qml" in sys.argv: diff --git a/gramps/gui/__init__.py b/gramps/gui/__init__.py index 5d2957717..207ab86dc 100644 --- a/gramps/gui/__init__.py +++ b/gramps/gui/__init__.py @@ -22,7 +22,7 @@ Package init for the gui package. """ -# DO NOT IMPORT METHODS/CLASSES FROM src/gui HERE ! Only __all__ +# DO NOT IMPORT METHODS/CLASSES FROM src/gui HERE ! Only __all__ -__all__ = [ "editors", "filters", "logger", "merge", "selectors", "views", +__all__ = [ "editors", "filters", "logger", "merge", "selectors", "views", "widgets"] diff --git a/gramps/gui/aboutdialog.py b/gramps/gui/aboutdialog.py index bf0fc7053..e663d92c8 100644 --- a/gramps/gui/aboutdialog.py +++ b/gramps/gui/aboutdialog.py @@ -51,8 +51,8 @@ from gi.repository import GdkPixbuf # GRAMPS modules # #------------------------------------------------------------------------- -from gramps.gen.const import (AUTHORS, AUTHORS_FILE, COMMENTS, COPYRIGHT_MSG, - DOCUMENTERS, LICENSE_FILE, PROGRAM_NAME, SPLASH, +from gramps.gen.const import (AUTHORS, AUTHORS_FILE, COMMENTS, COPYRIGHT_MSG, + DOCUMENTERS, LICENSE_FILE, PROGRAM_NAME, SPLASH, URL_HOMEPAGE, VERSION) from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext @@ -85,7 +85,7 @@ class GrampsAboutDialog(Gtk.AboutDialog): Gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_modal(True) - + self.set_name(PROGRAM_NAME) self.set_version(VERSION) self.set_copyright(COPYRIGHT_MSG) @@ -95,7 +95,7 @@ class GrampsAboutDialog(Gtk.AboutDialog): "Creative Commons Attribution-ShareAlike 2.5\n" "license.") self.set_artists(artists.split('\n')) - + try: ifile = open(LICENSE_FILE, "r") self.set_license(ifile.read().replace('\x0c', '')) @@ -106,12 +106,12 @@ class GrampsAboutDialog(Gtk.AboutDialog): self.set_comments(_(COMMENTS) + self.get_versions()) self.set_website_label(_('Gramps Homepage')) self.set_website(URL_HOMEPAGE) - + authors, contributors = _get_authors() self.set_authors(authors) if len(contributors) > 0: self.add_credit_section(_('Contributions by'), contributors) - + # TRANSLATORS: Translate this to your name in your native language self.set_translator_credits(_("translator-credits")) @@ -150,33 +150,33 @@ class GrampsAboutDialog(Gtk.AboutDialog): #------------------------------------------------------------------------- class AuthorParser(handler.ContentHandler): """Parse the ``authors.xml`` file to show in the About dialog. - + The ``authors.xml`` file has the same format as the one in the `svn2cl `_ package, with an additional ``title`` tag in the ``author`` element. For example:: - + Don Allingham <don@gramps-project.org> } - + """ def __init__(self, author_list, contributor_list): """Setup initial instance variable values.""" handler.ContentHandler.__init__(self) - + self.author_list = author_list self.contributor_list = contributor_list - + # initialize all instance variables to make pylint happy self.title = "" self.text = "" - + def startElement(self, tag, attrs): """Handle the start of an element.""" if tag == "author": self.title = attrs['title'] self.text = "" - + def endElement(self, tag): """Handle the end of an element.""" if tag == "author": @@ -187,7 +187,7 @@ class AuthorParser(handler.ContentHandler): elif (self.title == 'contributor' and developer not in self.contributor_list): self.contributor_list.append(developer) - + def characters(self, chunk): """Receive notification of character data.""" if chunk != '\n': @@ -200,27 +200,27 @@ class AuthorParser(handler.ContentHandler): #------------------------------------------------------------------------- def _get_authors(): """Return all the authors and contributors in a string. - + Parse the ``authors.xml`` file if found, or return the default list from :mod:`.const` module in case of I/O or parsing failure. - + If the ``authors.xml`` file is successfully parsed the *Authors* and *Contributors* are grouped separately with an appropriate header. - + """ try: authors = [] contributors = [] - + parser = make_parser() parser.setContentHandler(AuthorParser(authors, contributors)) - + authors_file = io.open(AUTHORS_FILE, encoding='utf-8') parser.parse(authors_file) authors_file.close() - + authors_text = [authors, contributors] - + except (IOError, OSError, SAXParseException): authors_text = [AUTHORS, []] diff --git a/gramps/gui/actiongroup.py b/gramps/gui/actiongroup.py index f856e95c3..f24c73a6f 100644 --- a/gramps/gui/actiongroup.py +++ b/gramps/gui/actiongroup.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. diff --git a/gramps/gui/autocomp.py b/gramps/gui/autocomp.py index bcb3ef2af..2e03908b9 100644 --- a/gramps/gui/autocomp.py +++ b/gramps/gui/autocomp.py @@ -42,7 +42,7 @@ def fill_combo(combo, data_list): for data in data_list: if data: store.append(row=[data]) - + combo.set_model(store) combo.set_entry_text_column(0) completion = Gtk.EntryCompletion() @@ -67,7 +67,7 @@ def fill_entry(entry, data_list): completion.set_minimum_key_length(1) completion.set_text_column(0) entry.set_completion(completion) - + #------------------------------------------------------------------------- # # StandardCustomSelector class @@ -101,7 +101,7 @@ class StandardCustomSelector(object): upon widget creation. If omitted, the entry will be empty. If present, then no selection on the user's part will return the (active_key,mapping[active_key]) tuple. - + """ def __init__(self, mapping, cbe=None, custom_key=None, active_key=None, additional=None, menu=None): diff --git a/gramps/gui/clipboard.py b/gramps/gui/clipboard.py index f641e1898..08909b380 100644 --- a/gramps/gui/clipboard.py +++ b/gramps/gui/clipboard.py @@ -234,7 +234,7 @@ class ClipWrapper(object): return True class ClipHandleWrapper(ClipWrapper): - + def __init__(self,dbstate, obj): super(ClipHandleWrapper, self).__init__(dbstate, obj) #unpack object @@ -249,7 +249,7 @@ class ClipHandleWrapper(ClipWrapper): setattr(self, item, data[item]) class ClipObjWrapper(ClipWrapper): - + def __init__(self,dbstate, obj): super(ClipObjWrapper, self).__init__(dbstate, obj) #unpack object @@ -288,7 +288,7 @@ class ClipObjWrapper(ClipWrapper): if classname in valid_func_map: if not valid_func_map[classname](handle): return False - + return True @@ -297,7 +297,7 @@ class ClipAddress(ClipObjWrapper): DROP_TARGETS = [DdTargets.ADDRESS] DRAG_TARGET = DdTargets.ADDRESS ICON = ICONS['address'] - + def __init__(self, dbstate, obj): super(ClipAddress, self).__init__(dbstate, obj) self._type = _("Address") @@ -317,7 +317,7 @@ class ClipLocation(ClipObjWrapper): DROP_TARGETS = [DdTargets.LOCATION] DRAG_TARGET = DdTargets.LOCATION ICON = ICONS['location'] - + def __init__(self, dbstate, obj): super(ClipLocation, self).__init__(dbstate, obj) self._type = _("Location") @@ -421,7 +421,7 @@ class ClipFamilyEvent(ClipObjWrapper): DROP_TARGETS = [DdTargets.FAMILY_EVENT] DRAG_TARGET = DdTargets.FAMILY_EVENT ICON = ICONS['family'] - + def __init__(self, dbstate, obj): super(ClipFamilyEvent, self).__init__(dbstate, obj) self._type = _("Family Event") @@ -496,9 +496,9 @@ class ClipCitation(ClipHandleWrapper): citation = self._db.get_citation_from_handle(self._handle) if citation: self._title = citation.get_gramps_id() - notelist = list(map(self._db.get_note_from_handle, + notelist = list(map(self._db.get_note_from_handle, citation.get_note_list())) - srctxtlist = [note for note in notelist + srctxtlist = [note for note in notelist if note.get_type() == NoteType.SOURCE_TEXT] page = citation.get_page() if not page: @@ -625,7 +625,7 @@ class ClipSurname(ClipObjWrapper): if self._obj: self._title = self._obj.get_surname() self._value = self._obj.get_surname() - + class ClipText(ClipWrapper): DROP_TARGETS = DdTargets.all_text() @@ -728,7 +728,7 @@ class ClipChildRef(ClipObjWrapper): if person: frel = str(self._obj.get_father_relation()) mrel = str(self._obj.get_mother_relation()) - self._title = _('%(frel)s %(mrel)s') % {'frel': frel, + self._title = _('%(frel)s %(mrel)s') % {'frel': frel, 'mrel': mrel} self._value = person.get_primary_name().get_name() @@ -758,7 +758,7 @@ class ClipPersonLink(ClipHandleWrapper): if obj: return True return False - + class ClipFamilyLink(ClipHandleWrapper): @@ -855,7 +855,7 @@ class ClipDropList(object): def __init__(self, dbstate, obj_list): self._dbstate = dbstate - # ('link-list', id, (('person-link', handle), + # ('link-list', id, (('person-link', handle), # ('person-link', handle), ...), 0) self._obj_list = pickle.loads(obj_list) @@ -897,7 +897,7 @@ class ClipDropHandleList(ClipDropList): def __init__(self, dbstate, obj_list): self._dbstate = dbstate # incoming: - # ('handle-list', id, (('Person', '2763526751235'), + # ('handle-list', id, (('Person', '2763526751235'), # ('Source', '3786234743978'), ...), 0) self._obj_list = pickle.loads(obj_list) @@ -944,14 +944,14 @@ class ClipboardListView(object): LOCAL_DRAG_TYPE = 'MY_TREE_MODEL_ROW' LOCAL_DRAG_ATOM_TYPE = Gdk.atom_intern(LOCAL_DRAG_TYPE, False) LOCAL_DRAG_TARGET = (LOCAL_DRAG_ATOM_TYPE, Gtk.TargetFlags.SAME_WIDGET, 0) - + def __init__(self, dbstate, widget): - + self._widget = widget self.dbstate = dbstate self.dbstate.connect('database-changed', self.database_changed) self.database_changed(dbstate.db) - + self._target_type_to_wrapper_class_map = {} self._previous_drop_time = 0 @@ -993,17 +993,17 @@ class ClipboardListView(object): self._col1.set_cell_data_func(self._col1_cellpb, self.object_pixbuf) self._col1.set_cell_data_func(self._col1_cell, self.object_type) self._col2.set_cell_data_func(self._col2_cell, self.object_title) - self._col3.set_cell_data_func(self._col3_cell, self.object_value) - self._col4.set_cell_data_func(self._col4_cell, self.get_dbname) - + self._col3.set_cell_data_func(self._col3_cell, self.object_value) + self._col4.set_cell_data_func(self._col4_cell, self.get_dbname) + # Set the column that inline searching will use. self._widget.set_enable_search(True) #self._widget.set_search_column(3) targ_data = DdTargets.all_dtype() tglist = Gtk.TargetList.new([]) - tglist.add(ClipboardListView.LOCAL_DRAG_TARGET[0], - ClipboardListView.LOCAL_DRAG_TARGET[1], + tglist.add(ClipboardListView.LOCAL_DRAG_TARGET[0], + ClipboardListView.LOCAL_DRAG_TARGET[1], ClipboardListView.LOCAL_DRAG_TARGET[2]) for tg in targ_data: tglist.add(tg.atom_drag_type, tg.target_flags, tg.app_id) @@ -1047,11 +1047,11 @@ class ClipboardListView(object): for signal in db_signals: self._db.connect(signal,self.refresh_objects) - self._db.connect('person-delete', + self._db.connect('person-delete', gen_del_obj(self.delete_object, 'person-link')) - self._db.connect('person-delete', + self._db.connect('person-delete', gen_del_obj(self.delete_object_ref, 'personref')) - self._db.connect('person-delete', + self._db.connect('person-delete', gen_del_obj(self.delete_object_ref, 'childref')) self._db.connect('source-delete', gen_del_obj(self.delete_object, 'source-link')) @@ -1095,7 +1095,7 @@ class ClipboardListView(object): data = pickle.loads(o[1]._obj) if data[2] in handle_list: model.remove(o.iter) - + def delete_object_ref(self, handle_list, link_type): model = self._widget.get_model() @@ -1105,9 +1105,9 @@ class ClipboardListView(object): data = o[1]._obj.get_reference_handle() if data in handle_list: model.remove(o.iter) - + # Method to manage the wrapper classes. - + def register_wrapper_classes(self): self.register_wrapper_class(ClipAddress) self.register_wrapper_class(ClipLocation) @@ -1136,13 +1136,13 @@ class ClipboardListView(object): self.register_wrapper_class(ClipChildRef) self.register_wrapper_class(ClipText) self.register_wrapper_class(ClipNote) - + def register_wrapper_class(self,wrapper_class): - for drop_target in wrapper_class.DROP_TARGETS: + for drop_target in wrapper_class.DROP_TARGETS: self._target_type_to_wrapper_class_map[drop_target.drag_type] = wrapper_class # Methods for rendering the cells. - + def object_pixbuf(self, column, cell, model, node, user_data=None): o = model.get_value(node, 1) if o._dbid is not None and o._dbid != self.dbstate.db.get_dbid(): @@ -1150,19 +1150,19 @@ class ClipboardListView(object): cell.set_property('icon-name', o.__class__.UNAVAILABLE_ICON) else: - cell.set_property('pixbuf', + cell.set_property('pixbuf', o.__class__.UNAVAILABLE_ICON) else: cell.set_property('pixbuf', o.__class__.ICON) - + def object_type(self, column, cell, model, node, user_data=None): o = model.get_value(node, 1) cell.set_property('text', o.get_type()) - + def object_title(self, column, cell, model, node, user_data=None): o = model.get_value(node, 1) cell.set_property('text', o.get_title()) - + def object_value(self, column, cell, model, node, user_data=None): o = model.get_value(node, 1) cell.set_property('text', o.get_value()) @@ -1173,15 +1173,15 @@ class ClipboardListView(object): # handlers for the drag and drop events. - - def on_object_select_row(self, obj): + + def on_object_select_row(self, obj): tree_selection = self._widget.get_selection() model, paths = tree_selection.get_selected_rows() if len(paths) > 1: - targets = [(DdTargets.RAW_LIST.atom_drag_type, Gtk.TargetFlags.SAME_WIDGET, 0), - ClipboardListView.LOCAL_DRAG_TARGET] + targets = [(DdTargets.RAW_LIST.atom_drag_type, Gtk.TargetFlags.SAME_WIDGET, 0), + ClipboardListView.LOCAL_DRAG_TARGET] else: - targets = [ClipboardListView.LOCAL_DRAG_TARGET] + targets = [ClipboardListView.LOCAL_DRAG_TARGET] for path in paths: node = model.get_iter(path) if node is not None: @@ -1189,8 +1189,8 @@ class ClipboardListView(object): targets += [target.target_data_atom() for target in o.__class__.DROP_TARGETS] #TODO GTK3: wourkaround here for bug https://bugzilla.gnome.org/show_bug.cgi?id=680638 - self._widget.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, - [], + self._widget.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, + [], Gdk.DragAction.COPY | Gdk.DragAction.MOVE) tglist = Gtk.TargetList.new([]) for tg in targets: @@ -1200,7 +1200,7 @@ class ClipboardListView(object): def object_drag_begin(self, widget, drag_context): """ Handle the beginning of a drag operation. """ pass - + def object_drag_end(self, widget, drag_context): """ Handle the end of a drag operation. """ pass @@ -1247,11 +1247,11 @@ class ClipboardListView(object): possible_wrappers = [] if mac(): # context is empty on mac due to a bug, work around this - # Note that this workaround code works fine in linux too as - # we know very well inside of GRAMPS what sel_data can be, so + # Note that this workaround code works fine in linux too as + # we know very well inside of GRAMPS what sel_data can be, so # we can anticipate on it, instead of letting the wrapper handle # it. This is less clean however ! - # See http://www.gramps-project.org/bugs/view.php?id=3089 for + # See http://www.gramps-project.org/bugs/view.php?id=3089 for # an explaination of why this is required. dragtype = None try: @@ -1297,7 +1297,7 @@ class ClipboardListView(object): for o in o_list: if o.__class__.DRAG_TARGET is None: continue - data = [o.__class__.DRAG_TARGET.drag_type, o, None, + data = [o.__class__.DRAG_TARGET.drag_type, o, None, o._type, o._value, o._dbid, o._dbname] contains = model_contains(model, data) if ((context.action if hasattr(context, "action") else context.get_actions()) @@ -1318,7 +1318,7 @@ class ClipboardListView(object): # FIXME: there is one bug here: if you multi-select and drop # on self, then it moves the first, and copies the rest. - if ((context.action if hasattr(context, "action") else context.get_actions()) == + if ((context.action if hasattr(context, "action") else context.get_actions()) == Gdk.DragAction.MOVE): context.finish(True, True, time) @@ -1327,7 +1327,7 @@ class ClipboardListView(object): return o_list # proxy methods to provide access to the real widget functions. - + def set_model(self,model=None): self._widget.set_model(model) self._widget.get_selection().connect('changed',self.on_object_select_row) @@ -1364,14 +1364,14 @@ class ClipboardWindow(ManagedWindow): a responsibility on all '_drag_data_received' methods to check the references of objects before attempting to use them. """ - - # Class attribute used to hold the content of the Clipboard. + + # Class attribute used to hold the content of the Clipboard. # A class attribute is used so that the content # it preserved even when the Clipboard window is closed. # As there is only ever one Clipboard we do not need to # maintain a list of these. otree = None - + def __init__(self, dbstate, uistate): """Initialize the ClipboardWindow class, and display the window""" @@ -1383,7 +1383,7 @@ class ClipboardWindow(ManagedWindow): self.width_key = 'interface.clipboard-width' self.height_key = 'interface.clipboard-height' - + self.top = Glade() self.set_window(self.top.toplevel, None, None, msg=_("Clipboard")) self._set_size() @@ -1400,7 +1400,7 @@ class ClipboardWindow(ManagedWindow): self.set_clear_btn_sensitivity) self.object_list.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE) self.set_clear_btn_sensitivity(sel=self.object_list.get_selection()) - + if not ClipboardWindow.otree: ClipboardWindow.otree = ClipboardListModel() @@ -1411,11 +1411,11 @@ class ClipboardWindow(ManagedWindow): self.set_clear_all_btn_sensitivity) self.object_list.set_model(ClipboardWindow.otree) - + #Database might have changed, objects might have been removed, #we need to reevaluate if all data is valid self.object_list.refresh_objects() - + self.top.connect_signals({ "on_close_clipboard" : self.close, "on_clear_clicked": self.on_clear_clicked, @@ -1425,7 +1425,7 @@ class ClipboardWindow(ManagedWindow): self.clear_all_btn.connect_object('clicked', Gtk.ListStore.clear, ClipboardWindow.otree) self.db.connect('database-changed', lambda x: ClipboardWindow.otree.clear()) - + self.show() def build_menu_names(self, obj): @@ -1433,7 +1433,7 @@ class ClipboardWindow(ManagedWindow): def database_changed(self,database): self.db = database - + def set_clear_all_btn_sensitivity(self, treemodel=None, path=None, node=None, user_param1=None): if len(treemodel) == 0: @@ -1446,7 +1446,7 @@ class ClipboardWindow(ManagedWindow): self.clear_btn.set_sensitive(False) else: self.clear_btn.set_sensitive(True) - + def on_help_clicked(self, obj): """Display the relevant portion of GRAMPS manual""" display_help(webpage=WIKI_HELP_PAGE, section=WIKI_HELP_SEC) @@ -1517,13 +1517,13 @@ class MultiTreeView(Gtk.TreeView): if objclass in ['Person', 'Event', 'Media', 'Source', 'Citation', 'Repository', 'Family', 'Note', 'Place']: menu_item = Gtk.MenuItem(label=_("the object|See %s details") % glocale.trans_objclass(objclass)) - menu_item.connect("activate", + menu_item.connect("activate", lambda widget: self.edit_obj(objclass, handle)) popup.append(menu_item) menu_item.show() # --------------------------- menu_item = Gtk.MenuItem(label=_("the object|Make %s active") % glocale.trans_objclass(objclass)) - menu_item.connect("activate", + menu_item.connect("activate", lambda widget: self.uistate.set_active(handle, objclass)) popup.append(menu_item) menu_item.show() @@ -1539,14 +1539,14 @@ class MultiTreeView(Gtk.TreeView): if obj: gids.add(obj.gramps_id) menu_item = Gtk.MenuItem(label=_("the object|Create Filter from %s selected...") % glocale.trans_objclass(objclass)) - menu_item.connect("activate", - lambda widget: make_filter(self.dbstate, self.uistate, + menu_item.connect("activate", + lambda widget: make_filter(self.dbstate, self.uistate, objclass, gids, title=self.title)) popup.append(menu_item) menu_item.show() # Show the popup menu: popup.popup(None, None, None, None, 3, event.time) - return True + return True elif event.type == Gdk.EventType._2BUTTON_PRESS and event.button == 1: model, paths = self.get_selection().get_selected_rows() for path in paths: @@ -1558,7 +1558,7 @@ class MultiTreeView(Gtk.TreeView): self.edit_obj(objclass, handle) return True # otherwise: - if (target + if (target and event.type == Gdk.EventType.BUTTON_PRESS and not (event.get_state() & (Gdk.ModifierType.CONTROL_MASK|Gdk.ModifierType.SHIFT_MASK)) and self.get_selection().path_is_selected(target[0])): @@ -1569,13 +1569,13 @@ class MultiTreeView(Gtk.TreeView): def on_button_release(self, widget, event): # re-enable selection self.get_selection().set_select_function(lambda *ignore: True, None) - - target = self.get_path_at_pos(int(event.x), int(event.y)) - if (self.defer_select and target + + target = self.get_path_at_pos(int(event.x), int(event.y)) + if (self.defer_select and target and self.defer_select == target[0] and not (event.x==0 and event.y==0)): # certain drag and drop self.set_cursor(target[0], target[1], False) - + self.defer_select=False def edit_obj(self, objclass, handle): @@ -1586,7 +1586,7 @@ class MultiTreeView(Gtk.TreeView): person = self.dbstate.db.get_person_from_handle(handle) if person: try: - EditPerson(self.dbstate, + EditPerson(self.dbstate, self.uistate, [], person) except WindowActiveError: pass @@ -1594,7 +1594,7 @@ class MultiTreeView(Gtk.TreeView): event = self.dbstate.db.get_event_from_handle(handle) if event: try: - EditEvent(self.dbstate, + EditEvent(self.dbstate, self.uistate, [], event) except WindowActiveError: pass @@ -1602,7 +1602,7 @@ class MultiTreeView(Gtk.TreeView): ref = self.dbstate.db.get_family_from_handle(handle) if ref: try: - EditFamily(self.dbstate, + EditFamily(self.dbstate, self.uistate, [], ref) except WindowActiveError: pass @@ -1610,7 +1610,7 @@ class MultiTreeView(Gtk.TreeView): ref = self.dbstate.db.get_source_from_handle(handle) if ref: try: - EditSource(self.dbstate, + EditSource(self.dbstate, self.uistate, [], ref) except WindowActiveError: pass @@ -1618,7 +1618,7 @@ class MultiTreeView(Gtk.TreeView): ref = self.dbstate.db.get_place_from_handle(handle) if ref: try: - EditPlace(self.dbstate, + EditPlace(self.dbstate, self.uistate, [], ref) except WindowActiveError: pass @@ -1626,7 +1626,7 @@ class MultiTreeView(Gtk.TreeView): ref = self.dbstate.db.get_repository_from_handle(handle) if ref: try: - EditRepository(self.dbstate, + EditRepository(self.dbstate, self.uistate, [], ref) except WindowActiveError: pass @@ -1634,7 +1634,7 @@ class MultiTreeView(Gtk.TreeView): ref = self.dbstate.db.get_note_from_handle(handle) if ref: try: - EditNote(self.dbstate, + EditNote(self.dbstate, self.uistate, [], ref) except WindowActiveError: pass @@ -1642,7 +1642,7 @@ class MultiTreeView(Gtk.TreeView): ref = self.dbstate.db.get_object_from_handle(handle) if ref: try: - EditMedia(self.dbstate, + EditMedia(self.dbstate, self.uistate, [], ref) except WindowActiveError: pass diff --git a/gramps/gui/columnorder.py b/gramps/gui/columnorder.py index 271e935be..d7b374d16 100644 --- a/gramps/gui/columnorder.py +++ b/gramps/gui/columnorder.py @@ -66,7 +66,7 @@ class ColumnOrder(Gtk.Box): def __init__(self, config, column_names, widths, on_apply, tree=False): """ Create the Column Ordering widget based on config - + config: a configuration file with column data column_names: translated names for the possible columns widths: the widths of the visible columns @@ -80,13 +80,13 @@ class ColumnOrder(Gtk.Box): self.colnames = column_names self.config = config self.on_apply = on_apply - + self.pack_start(Gtk.Label(label=' '), False, False, 0) - + self.startrow = 0 if self.treeview: label = Gtk.Label(label= - _('Tree View: first column "%s" cannot be changed') % + _('Tree View: first column "%s" cannot be changed') % column_names[0]) self.startrow = 1 self.pack_start(label, False, False, 0) @@ -116,15 +116,15 @@ class ColumnOrder(Gtk.Box): # str : name of the column # int : order of the column # int : size (width) of the column - self.model = Gtk.ListStore(GObject.TYPE_BOOLEAN, GObject.TYPE_STRING, + self.model = Gtk.ListStore(GObject.TYPE_BOOLEAN, GObject.TYPE_STRING, GObject.TYPE_INT, GObject.TYPE_INT) - + self.tree.set_model(self.model) checkbox = Gtk.CellRendererToggle() checkbox.connect('toggled', toggled, self.model) renderer = Gtk.CellRendererText() - + column_n = Gtk.TreeViewColumn(_('Display'), checkbox, active=0) column_n.set_min_width(50) self.tree.append_column(column_n) diff --git a/gramps/gui/configure.py b/gramps/gui/configure.py index e56d02f8f..3e928357f 100644 --- a/gramps/gui/configure.py +++ b/gramps/gui/configure.py @@ -12,7 +12,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -54,7 +54,7 @@ from gramps.gen.display.name import displayer as _nd from gramps.gen.display.name import NameDisplayError from gramps.gen.utils.alive import update_constants from gramps.gen.utils.file import media_path -from gramps.gen.utils.keyword import (get_keywords, get_translation_from_keyword, +from gramps.gen.utils.keyword import (get_keywords, get_translation_from_keyword, get_translations, get_keyword_from_translation) from gramps.gen.lib import Date, FamilyRelType from gramps.gen.lib import Name, Surname, NameOriginType @@ -71,15 +71,15 @@ _ = glocale.translation.gettext #------------------------------------------------------------------------- # -# Constants +# Constants # #------------------------------------------------------------------------- _surname_styles = [ - _("Father's surname"), - _("None"), - _("Combination of mother's and father's surname"), - _("Icelandic style"), + _("Father's surname"), + _("None"), + _("Combination of mother's and father's surname"), + _("Icelandic style"), ] # column numbers for the 'name format' model @@ -95,8 +95,8 @@ COL_EXPL = 3 #------------------------------------------------------------------------- class DisplayNameEditor(ManagedWindow): def __init__(self, uistate, dbstate, track, dialog): - # Assumes that there are two methods: dialog.name_changed_check(), - # and dialog._build_custom_name_ui() + # Assumes that there are two methods: dialog.name_changed_check(), + # and dialog._build_custom_name_ui() ManagedWindow.__init__(self, uistate, track, DisplayNameEditor) self.dialog = dialog self.dbstate = dbstate @@ -105,26 +105,26 @@ class DisplayNameEditor(ManagedWindow): buttons=(_('_Close'), Gtk.ResponseType.CLOSE)), None, _('Display Name Editor'), None) grid = self.dialog._build_custom_name_ui() - label = Gtk.Label(label=_("""The following keywords are replaced with the appropriate name parts: + label = Gtk.Label(label=_("""The following keywords are replaced with the appropriate name parts: Given - given name (first name) Surname - surnames (with prefix and connectors) Title - title (Dr., Mrs.) Suffix - suffix (Jr., Sr.) Call - call name Nickname - nick name Initials- first letters of given Common - nick name, call, or first of given - Prefix - all prefixes (von, de) + Prefix - all prefixes (von, de) Surnames: Rest - non primary surnames Notpatronymic- all surnames, except pa/matronymic & primary Familynick- family nick name Rawsurnames - surnames (no prefixes and connectors) - Primary, Primary[pre] or [sur] or [con]- full primary surname, prefix, surname only, connector - Patronymic, or [pre] or [sur] or [con] - full pa/matronymic surname, prefix, surname only, connector + Primary, Primary[pre] or [sur] or [con]- full primary surname, prefix, surname only, connector + Patronymic, or [pre] or [sur] or [con] - full pa/matronymic surname, prefix, surname only, connector UPPERCASE keyword forces uppercase. Extra parentheses, commas are removed. Other text appears literally. Example: Dr. Edwin Jose von der Smith and Weston Wilson Sr ("Ed") - Underhills - Edwin Jose: Given, von der: Prefix, Smith and Weston: Primary, and: [con], Wilson: Patronymic, + Edwin Jose: Given, von der: Prefix, Smith and Weston: Primary, and: [con], Wilson: Patronymic, Dr.: Title, Sr: Suffix, Ed: Nickname, Underhills: Familynick, Jose: Call. """)) label.set_use_markup(True) - self.window.vbox.pack_start(label, False, True, 0) + self.window.vbox.pack_start(label, False, True, 0) self.window.vbox.pack_start(grid, True, True, 0) self.window.set_default_size(600, 550) self.window.connect('response', self.close) @@ -132,7 +132,7 @@ UPPERCASE keyword forces uppercase. Extra parentheses, commas are removed. Other def close(self, *obj): self.dialog.name_changed_check() ManagedWindow.close(self, *obj) - + def build_menu_names(self, obj): return (_(" Name Editor"), None) @@ -145,7 +145,7 @@ UPPERCASE keyword forces uppercase. Extra parentheses, commas are removed. Other class ConfigureDialog(ManagedWindow): """ - Base class for configuration dialogs. They provide a Notebook, to which + Base class for configuration dialogs. They provide a Notebook, to which pages are added with configuration options, and a Cancel and Save button. On save, a config file on which the dialog works, is saved to disk, and a callback called. @@ -158,15 +158,15 @@ class ConfigureDialog(ManagedWindow): :param uistate: a DisplayState instance :param dbstate: a DbState instance :param configure_page_funcs: a list of function that return a tuple - (str, Gtk.Widget). The string is used as label for the - configuration page, and the widget as the content of the + (str, Gtk.Widget). The string is used as label for the + configuration page, and the widget as the content of the configuration page - :param configobj: the unique object that is configured, it must be - identifiable (id(configobj)). If the configure dialog of the + :param configobj: the unique object that is configured, it must be + identifiable (id(configobj)). If the configure dialog of the configobj is already open, a WindowActiveError will be raised. Grab this exception in the calling method :param configmanager: a configmanager object. Several convenience - methods are present in ConfigureDialog to set up widgets that + methods are present in ConfigureDialog to set up widgets that write changes directly via this configmanager. :param dialogtitle: the title of the configuration dialog :param on_close: callback that is called on close @@ -175,7 +175,7 @@ class ConfigureDialog(ManagedWindow): self.__config = configmanager ManagedWindow.__init__(self, uistate, [], configobj) self.set_window( - Gtk.Dialog(dialogtitle, + Gtk.Dialog(dialogtitle, buttons=(_('_Close'), Gtk.ResponseType.CLOSE)), None, dialogtitle, None) self.panel = Gtk.Notebook() @@ -183,11 +183,11 @@ class ConfigureDialog(ManagedWindow): self.window.vbox.pack_start(self.panel, True, True, 0) self.__on_close = on_close self.window.connect('response', self.done) - + self.__setup_pages(configure_page_funcs) - + self.show() - + def __setup_pages(self, configure_page_funcs): """ This method builds the notebookpages in the panel @@ -209,7 +209,7 @@ class ConfigureDialog(ManagedWindow): """ :param obj: an object with get_text method that should contain an integer - :param constant: the config setting to which the integer value must be + :param constant: the config setting to which the integer value must be saved """ try: @@ -219,15 +219,15 @@ class ConfigureDialog(ManagedWindow): def update_markup_entry(self, obj, constant): """ - :param obj: an object with get_text method - :param constant: the config setting to which the text value must be + :param obj: an object with get_text method + :param constant: the config setting to which the text value must be saved """ try: obj.get_text() % 'test_markup' except TypeError: print("WARNING: ignoring invalid value for '%s'" % constant) - ErrorDialog(_("Invalid or incomplete format definition."), + ErrorDialog(_("Invalid or incomplete format definition."), obj.get_text(), parent=self.window) obj.set_text('%s') except ValueError: @@ -235,13 +235,13 @@ class ConfigureDialog(ManagedWindow): ErrorDialog(_("Invalid or incomplete format definition."), obj.get_text(), parent=self.window) obj.set_text('%s') - + self.__config.set(constant, unicode(obj.get_text())) def update_entry(self, obj, constant): """ - :param obj: an object with get_text method - :param constant: the config setting to which the text value must be + :param obj: an object with get_text method + :param constant: the config setting to which the text value must be saved """ self.__config.set(constant, conv_to_unicode(obj.get_text())) @@ -315,10 +315,10 @@ class ConfigureDialog(ManagedWindow): text.set_text(label) grid.attach(text, 1, index, 8, 1) - def add_path_box(self, grid, label, index, entry, path, callback_label, + def add_path_box(self, grid, label, index, entry, path, callback_label, callback_sel, config=None): - """ Add an entry to give in path and a select button to open a - dialog. + """ Add an entry to give in path and a select button to open a + dialog. Changing entry calls callback_label Clicking open button call callback_sel """ @@ -494,7 +494,7 @@ class GrampsPreferences(ConfigureDialog): self.add_advanced_panel, self.add_color_panel ) - ConfigureDialog.__init__(self, uistate, dbstate, page_funcs, + ConfigureDialog.__init__(self, uistate, dbstate, page_funcs, GrampsPreferences, config, on_close=update_constants) @@ -524,7 +524,7 @@ class GrampsPreferences(ConfigureDialog): grid.set_border_width(12) grid.set_column_spacing(6) grid.set_row_spacing(6) - self.add_entry(grid, _('Person'), 0, 'preferences.iprefix', + self.add_entry(grid, _('Person'), 0, 'preferences.iprefix', self.update_idformat_entry) self.add_entry(grid, _('Family'), 1, 'preferences.fprefix', self.update_idformat_entry) @@ -554,37 +554,37 @@ class GrampsPreferences(ConfigureDialog): grid.set_row_spacing(6) self.add_text(grid, _('Set the colors used for boxes in the graphical views'), 0, line_wrap=False) - self.add_color(grid, _('Gender Male Alive'), 1, + self.add_color(grid, _('Gender Male Alive'), 1, 'preferences.color-gender-male-alive') - self.add_color(grid, _('Border Male Alive'), 2, + self.add_color(grid, _('Border Male Alive'), 2, 'preferences.bordercolor-gender-male-alive') - self.add_color(grid, _('Gender Male Death'), 3, + self.add_color(grid, _('Gender Male Death'), 3, 'preferences.color-gender-male-death') - self.add_color(grid, _('Border Male Death'), 4, + self.add_color(grid, _('Border Male Death'), 4, 'preferences.bordercolor-gender-male-death') - self.add_color(grid, _('Gender Female Alive'), 1, + self.add_color(grid, _('Gender Female Alive'), 1, 'preferences.color-gender-female-alive', col=4) - self.add_color(grid, _('Border Female Alive'), 2, + self.add_color(grid, _('Border Female Alive'), 2, 'preferences.bordercolor-gender-female-alive', col=4) - self.add_color(grid, _('Gender Female Death'), 3, + self.add_color(grid, _('Gender Female Death'), 3, 'preferences.color-gender-female-death', col=4) - self.add_color(grid, _('Border Female Death'), 4, + self.add_color(grid, _('Border Female Death'), 4, 'preferences.bordercolor-gender-female-death', col=4) -## self.add_color(grid, _('Gender Other Alive'), 5, +## self.add_color(grid, _('Gender Other Alive'), 5, ## 'preferences.color-gender-other-alive') -## self.add_color(grid, _('Border Other Alive'), 6, +## self.add_color(grid, _('Border Other Alive'), 6, ## 'preferences.bordercolor-gender-other-alive') -## self.add_color(grid, _('Gender Other Death'), 7, +## self.add_color(grid, _('Gender Other Death'), 7, ## 'preferences.color-gender-other-death') -## self.add_color(grid, _('Border Other Death'), 8, +## self.add_color(grid, _('Border Other Death'), 8, ## 'preferences.bordercolor-gender-other-death') - self.add_color(grid, _('Gender Unknown Alive'), 5, + self.add_color(grid, _('Gender Unknown Alive'), 5, 'preferences.color-gender-unknown-alive', col=4) - self.add_color(grid, _('Border Unknown Alive'), 6, + self.add_color(grid, _('Border Unknown Alive'), 6, 'preferences.bordercolor-gender-unknown-alive', col=4) - self.add_color(grid, _('Gender Unknown Death'), 7, + self.add_color(grid, _('Gender Unknown Death'), 7, 'preferences.color-gender-unknown-death', col=4) - self.add_color(grid, _('Border Unknown Death'), 8, + self.add_color(grid, _('Border Unknown Death'), 8, 'preferences.bordercolor-gender-unknown-death', col=4) return _('Colors'), grid @@ -594,31 +594,31 @@ class GrampsPreferences(ConfigureDialog): grid.set_column_spacing(6) grid.set_row_spacing(6) self.add_checkbox( - grid, _('Suppress warning when adding parents to a child.'), + grid, _('Suppress warning when adding parents to a child.'), 0, 'preferences.family-warn') - + self.add_checkbox( - grid, _('Suppress warning when canceling with changed data.'), + grid, _('Suppress warning when canceling with changed data.'), 1, 'interface.dont-ask') - + self.add_checkbox( grid, _('Suppress warning about missing researcher when' - ' exporting to GEDCOM.'), + ' exporting to GEDCOM.'), 2, 'behavior.owner-warn') self.add_checkbox( - grid, _('Show plugin status dialog on plugin load error.'), + grid, _('Show plugin status dialog on plugin load error.'), 3, 'behavior.pop-plugin-status') - + return _('Warnings'), grid def _build_name_format_model(self, active): """ Create a common model for ComboBox and TreeView """ - name_format_model = Gtk.ListStore(GObject.TYPE_INT, - GObject.TYPE_STRING, - GObject.TYPE_STRING, + name_format_model = Gtk.ListStore(GObject.TYPE_INT, + GObject.TYPE_STRING, + GObject.TYPE_STRING, GObject.TYPE_STRING) index = 0 the_index = 0 @@ -635,21 +635,21 @@ class GrampsPreferences(ConfigureDialog): return name_format_model, the_index def __new_name(self, obj): - lyst = ["%s, %s %s (%s)" % (_("Surname"), _("Given"), _("Suffix"), + lyst = ["%s, %s %s (%s)" % (_("Surname"), _("Given"), _("Suffix"), _("Common")), - "%s, %s %s (%s)" % (_("Surname"), _("Given"), _("Suffix"), + "%s, %s %s (%s)" % (_("Surname"), _("Given"), _("Suffix"), _("Nickname")), - "%s, %s %s (%s)" % (_("Surname"), _("Name|Common"), _("Suffix"), + "%s, %s %s (%s)" % (_("Surname"), _("Name|Common"), _("Suffix"), _("Nickname")), "%s, %s %s" % (_("Surname"), _("Name|Common"), _("Suffix")), - "%s, %s %s (%s)" % (_("SURNAME"), _("Given"), _("Suffix"), + "%s, %s %s (%s)" % (_("SURNAME"), _("Given"), _("Suffix"), _("Call")), "%s, %s (%s)" % (_("Surname"), _("Given"), _("Name|Common")), "%s, %s (%s)" % (_("Surname"), _("Name|Common"), _("Nickname")), "%s %s" % (_("Given"), _("Surname")), "%s %s, %s" % (_("Given"), _("Surname"), _("Suffix")), "%s %s %s" % (_("Given"), _("NotPatronymic"), _("Patronymic")), - "%s, %s %s (%s)" % (_("SURNAME"), _("Given"), _("Suffix"), + "%s, %s %s (%s)" % (_("SURNAME"), _("Given"), _("Suffix"), _("Common")), "%s, %s (%s)" % (_("SURNAME"), _("Given"), _("Name|Common")), "%s, %s (%s)" % (_("SURNAME"), _("Given"), _("Nickname")), @@ -659,21 +659,21 @@ class GrampsPreferences(ConfigureDialog): "%s %s, %s" % (_("Given"), _("Rawsurnames"), _("Suffix")), ] #repeat above list, but not translated. - fmtlyst = ["%s, %s %s (%s)" % (("Surname"), ("Given"), ("Suffix"), + fmtlyst = ["%s, %s %s (%s)" % (("Surname"), ("Given"), ("Suffix"), ("Common")), - "%s, %s %s (%s)" % (("Surname"), ("Given"), ("Suffix"), + "%s, %s %s (%s)" % (("Surname"), ("Given"), ("Suffix"), ("Nickname")), - "%s, %s %s (%s)" % (("Surname"), ("Name|Common"), ("Suffix"), + "%s, %s %s (%s)" % (("Surname"), ("Name|Common"), ("Suffix"), ("Nickname")), "%s, %s %s" % (("Surname"), ("Name|Common"), ("Suffix")), - "%s, %s %s (%s)" % (("SURNAME"), ("Given"), ("Suffix"), + "%s, %s %s (%s)" % (("SURNAME"), ("Given"), ("Suffix"), ("Call")), "%s, %s (%s)" % (("Surname"), ("Given"), ("Name|Common")), "%s, %s (%s)" % (("Surname"), ("Name|Common"), ("Nickname")), "%s %s" % (("Given"), ("Surname")), "%s %s, %s" % (("Given"), ("Surname"), ("Suffix")), "%s %s %s" % (("Given"), ("NotPatronymic"), ("Patronymic")), - "%s, %s %s (%s)" % (("SURNAME"), ("Given"), ("Suffix"), + "%s, %s %s (%s)" % (("SURNAME"), ("Given"), ("Suffix"), ("Common")), "%s, %s (%s)" % (("SURNAME"), ("Given"), ("Name|Common")), "%s, %s (%s)" % (("SURNAME"), ("Given"), ("Nickname")), @@ -686,7 +686,7 @@ class GrampsPreferences(ConfigureDialog): f = lyst[rand] fmt = fmtlyst[rand] i = _nd.add_name_format(f, fmt) - node = self.fmt_model.append(row=[i, f, fmt, + node = self.fmt_model.append(row=[i, f, fmt, _nd.format_str(self.examplename, fmt)]) path = self.fmt_model.get_path(node) self.format_list.set_cursor(path, self.name_column, True) @@ -712,7 +712,7 @@ class GrampsPreferences(ConfigureDialog): while iter is not None: othernum = model.get_value(iter, COL_NUM) oldnum = model.get_value(oldnode, COL_NUM) - if othernum == oldnum: + if othernum == oldnum: pass# skip comparison with self else: othername = model.get_value(iter, COL_NAME) @@ -749,8 +749,8 @@ class GrampsPreferences(ConfigureDialog): if len(new_text) > 0 and text != new_text: # build a pattern from translated pattern: pattern = new_text - if (len(new_text) > 2 and - new_text[0] == '"' and + if (len(new_text) > 2 and + new_text[0] == '"' and new_text[-1] == '"'): pass else: @@ -759,8 +759,8 @@ class GrampsPreferences(ConfigureDialog): pattern = pattern.replace(key, get_keyword_from_translation(key)) # now build up a proper translation: translation = pattern - if (len(new_text) > 2 and - new_text[0] == '"' and + if (len(new_text) > 2 and + new_text[0] == '"' and new_text[-1] == '"'): pass else: @@ -772,7 +772,7 @@ class GrampsPreferences(ConfigureDialog): oldname = self.fmt_model.get_value(node, COL_NAME) # check to see if this pattern already exists if self.__check_for_name(translation, node): - ErrorDialog(_("This format exists already."), + ErrorDialog(_("This format exists already."), translation, parent=self.window) self.edit_button.emit('clicked') return @@ -781,12 +781,12 @@ class GrampsPreferences(ConfigureDialog): self.remove_button.set_sensitive(True) self.insert_button.set_sensitive(True) exmpl = _nd.format_str(self.examplename, pattern) - self.fmt_model.set(self.iter, COL_NAME, translation, - COL_FMT, pattern, + self.fmt_model.set(self.iter, COL_NAME, translation, + COL_FMT, pattern, COL_EXPL, exmpl) self.selected_fmt = (num, translation, pattern, exmpl) _nd.edit_name_format(num, translation, pattern) - self.dbstate.db.name_formats = _nd.get_name_format(only_custom=True, + self.dbstate.db.name_formats = _nd.get_name_format(only_custom=True, only_active=False) def __format_change(self, obj): @@ -811,8 +811,8 @@ class GrampsPreferences(ConfigureDialog): # make a treeview for listing all the name formats format_tree = Gtk.TreeView(self.fmt_model) name_renderer = Gtk.CellRendererText() - name_column = Gtk.TreeViewColumn(_('Format'), - name_renderer, + name_column = Gtk.TreeViewColumn(_('Format'), + name_renderer, text=COL_NAME) name_renderer.set_property('editable', False) name_renderer.connect('editing-started', self.__start_name_editing) @@ -821,11 +821,11 @@ class GrampsPreferences(ConfigureDialog): self.name_renderer = name_renderer format_tree.append_column(name_column) example_renderer = Gtk.CellRendererText() - example_column = Gtk.TreeViewColumn(_('Example'), - example_renderer, + example_column = Gtk.TreeViewColumn(_('Example'), + example_renderer, text=COL_EXPL) format_tree.append_column(example_column) - format_tree.get_selection().connect('changed', + format_tree.get_selection().connect('changed', self.cb_format_tree_select) # ... and put it into a scrolled win @@ -851,7 +851,7 @@ class GrampsPreferences(ConfigureDialog): self.remove_button = Gtk.Button.new_with_mnemonic(_('_Remove')) self.remove_button.connect('clicked', self.cb_del_fmt_str) self.remove_button.set_sensitive(False) - + grid.attach(self.insert_button, 0, 1, 1, 1) grid.attach(self.remove_button, 1, 1, 1, 1) grid.attach(self.edit_button, 2, 1, 1, 1) @@ -892,10 +892,10 @@ class GrampsPreferences(ConfigureDialog): def cb_format_tree_select(self, tree_selection): """ Name format editor TreeView callback - + Remember the values of the selected row (self.selected_fmt, self.iter) and set the Remove and Edit button sensitivity - + """ model, self.iter = tree_selection.get_selected() if self.iter is None: @@ -918,7 +918,7 @@ class GrampsPreferences(ConfigureDialog): self.fmt_model.remove(self.iter) _nd.set_format_inactive(num) - self.dbstate.db.name_formats = _nd.get_name_format(only_custom=True, + self.dbstate.db.name_formats = _nd.get_name_format(only_custom=True, only_active=False) def cb_grampletbar_close(self, obj): @@ -980,10 +980,10 @@ class GrampsPreferences(ConfigureDialog): grid.attach(lwidget, 0, row, 1, 1) grid.attach(hbox, 1, row, 2, 1) row += 1 - + # Pa/Matronymic surname handling - self.add_checkbox(grid, - _("Consider single pa/matronymic as surname"), + self.add_checkbox(grid, + _("Consider single pa/matronymic as surname"), row, 'preferences.patronimic-surname', stop=3, extra_callback=self.cb_pa_sur_changed) row += 1 @@ -1001,7 +1001,7 @@ class GrampsPreferences(ConfigureDialog): grid.attach(lwidget, 0, row, 1, 1) grid.attach(obox, 1, row, 2, 1) row += 1 - + # Age precision: # precision=1 for "year", 2: "year, month" or 3: "year, month, days" obox = Gtk.ComboBoxText() @@ -1015,7 +1015,7 @@ class GrampsPreferences(ConfigureDialog): obox.set_active(active) else: obox.set_active(0) - obox.connect('changed', + obox.connect('changed', lambda obj: config.set('preferences.age-display-precision', obj.get_active() + 1)) lwidget = BasicLabel("%s: " @@ -1023,7 +1023,7 @@ class GrampsPreferences(ConfigureDialog): grid.attach(lwidget, 0, row, 1, 1) grid.attach(obox, 1, row, 2, 1) row += 1 - + # Calendar format on report: obox = Gtk.ComboBoxText() list(map(obox.append_text, Date.ui_calendar_names)) @@ -1042,20 +1042,20 @@ class GrampsPreferences(ConfigureDialog): formats = _surname_styles list(map(obox.append_text, formats)) obox.set_active(config.get('behavior.surname-guessing')) - obox.connect('changed', - lambda obj: config.set('behavior.surname-guessing', + obox.connect('changed', + lambda obj: config.set('behavior.surname-guessing', obj.get_active())) lwidget = BasicLabel("%s: " % _('Surname guessing')) grid.attach(lwidget, 0, row, 1, 1) grid.attach(obox, 1, row, 2, 1) row += 1 - + # Default Family Relationship obox = Gtk.ComboBoxText() formats = FamilyRelType().get_standard_names() list(map(obox.append_text, formats)) obox.set_active(config.get('preferences.family-relation-type')) - obox.connect('changed', + obox.connect('changed', lambda obj: config.set('preferences.family-relation-type', obj.get_active())) lwidget = BasicLabel("%s: " % _('Default family relationship')) @@ -1063,8 +1063,8 @@ class GrampsPreferences(ConfigureDialog): grid.attach(obox, 1, row, 2, 1) row += 1 - #height multiple surname table - self.add_pos_int_entry(grid, + #height multiple surname table + self.add_pos_int_entry(grid, _('Height multiple surname box (pixels)'), row, 'interface.surname-box-height', self.update_surn_height, col_attach=0) @@ -1072,7 +1072,7 @@ class GrampsPreferences(ConfigureDialog): # Status bar: obox = Gtk.ComboBoxText() - formats = [_("Active person's name and ID"), + formats = [_("Active person's name and ID"), _("Relationship to home person")] list(map(obox.append_text, formats)) active = config.get('interface.statusbar') @@ -1080,7 +1080,7 @@ class GrampsPreferences(ConfigureDialog): obox.set_active(0) else: obox.set_active(1) - obox.connect('changed', + obox.connect('changed', lambda obj: config.set('interface.statusbar', 2*obj.get_active())) lwidget = BasicLabel("%s: " % _('Status bar')) grid.attach(lwidget, 0, row, 1, 1) @@ -1088,14 +1088,14 @@ class GrampsPreferences(ConfigureDialog): row += 1 # Text in sidebar: - self.add_checkbox(grid, - _("Show text label beside Navigator buttons (requires restart)"), + self.add_checkbox(grid, + _("Show text label beside Navigator buttons (requires restart)"), row, 'interface.sidebar-text', stop=3) row += 1 # Gramplet bar close buttons: - self.add_checkbox(grid, - _("Show close button in gramplet bar tabs"), + self.add_checkbox(grid, + _("Show close button in gramplet bar tabs"), row, 'interface.grampletbar-close', stop=3, extra_callback=self.cb_grampletbar_close) row += 1 @@ -1146,22 +1146,22 @@ class GrampsPreferences(ConfigureDialog): grid.set_border_width(12) grid.set_column_spacing(6) grid.set_row_spacing(6) - self.add_entry(grid, _('Missing surname'), row, + self.add_entry(grid, _('Missing surname'), row, 'preferences.no-surname-text') row += 1 - self.add_entry(grid, _('Missing given name'), row, + self.add_entry(grid, _('Missing given name'), row, 'preferences.no-given-text') row += 1 - self.add_entry(grid, _('Missing record'), row, + self.add_entry(grid, _('Missing record'), row, 'preferences.no-record-text') row += 1 - self.add_entry(grid, _('Private surname'), row, + self.add_entry(grid, _('Private surname'), row, 'preferences.private-surname-text') row += 1 - self.add_entry(grid, _('Private given name'), row, + self.add_entry(grid, _('Private given name'), row, 'preferences.private-given-text') row += 1 - self.add_entry(grid, _('Private record'), row, + self.add_entry(grid, _('Private record'), row, 'preferences.private-record-text') row += 1 return _('Text'), grid @@ -1183,7 +1183,7 @@ class GrampsPreferences(ConfigureDialog): def toggle_hide_previous_addons(self, obj): active = obj.get_active() - config.set('behavior.do-not-show-previously-seen-updates', + config.set('behavior.do-not-show-previously-seen-updates', bool(active)) def toggle_tag_on_import(self, obj): @@ -1201,43 +1201,43 @@ class GrampsPreferences(ConfigureDialog): def date_format_changed(self, obj): config.set('preferences.date-format', obj.get_active()) - OkDialog(_('Change is not immediate'), + OkDialog(_('Change is not immediate'), _('Changing the date format will not take ' 'effect until the next time Gramps is started.'), parent=self.window) - def date_calendar_changed(self, obj): + def date_calendar_changed(self, obj): config.set('preferences.calendar-format-report', obj.get_active()) - + def add_date_panel(self, configdialog): grid = Gtk.Grid() grid.set_border_width(12) grid.set_column_spacing(6) grid.set_row_spacing(6) - self.add_spinner(grid, + self.add_spinner(grid, _('Date about range'), 0, 'behavior.date-about-range', (1, 9999)) - self.add_spinner(grid, + self.add_spinner(grid, _('Date after range'), 1, 'behavior.date-after-range', (1, 9999)) - self.add_spinner(grid, + self.add_spinner(grid, _('Date before range'), 2, 'behavior.date-before-range', (1, 9999)) self.add_spinner(grid, _('Maximum age probably alive'), 3, 'behavior.max-age-prob-alive', (80, 140)) - self.add_spinner(grid, + self.add_spinner(grid, _('Maximum sibling age difference'), 4, 'behavior.max-sib-age-diff', (10, 30)) - self.add_spinner(grid, + self.add_spinner(grid, _('Minimum years between generations'), 5, 'behavior.min-generation-years', (5, 20)) - self.add_spinner(grid, + self.add_spinner(grid, _('Average years between generations'), 6, 'behavior.avg-generation-gap', (10, 30)) self.add_pos_int_entry(grid, - _('Markup for invalid date format'), + _('Markup for invalid date format'), 7, 'preferences.invalid-date-format', self.update_markup_entry, helptext = _('Convenience markups are:\n' @@ -1255,7 +1255,7 @@ class GrampsPreferences(ConfigureDialog): ) return _('Dates'), grid - + def add_behavior_panel(self, configdialog): grid = Gtk.Grid() grid.set_border_width(12) @@ -1263,8 +1263,8 @@ class GrampsPreferences(ConfigureDialog): grid.set_row_spacing(6) current_line = 0 - self.add_checkbox(grid, - _('Add default source on GEDCOM import'), + self.add_checkbox(grid, + _('Add default source on GEDCOM import'), current_line, 'preferences.default-source') current_line += 1 @@ -1272,19 +1272,19 @@ class GrampsPreferences(ConfigureDialog): checkbutton.set_active(config.get('preferences.tag-on-import')) checkbutton.connect("toggled", self.toggle_tag_on_import) grid.attach(checkbutton, 1, current_line, 1, 1) - self.tag_format_entry = self.add_entry(grid, None, current_line, - 'preferences.tag-on-import-format', + self.tag_format_entry = self.add_entry(grid, None, current_line, + 'preferences.tag-on-import-format', col_attach=2) self.tag_format_entry.set_sensitive(config.get('preferences.tag-on-import')) current_line += 1 - obj = self.add_checkbox(grid, - _('Enable spelling checker'), + obj = self.add_checkbox(grid, + _('Enable spelling checker'), current_line, 'behavior.spellcheck') if not HAVE_GTKSPELL: obj.set_sensitive(False) spell_dict = { 'gramps_wiki_build_spell_url' : - URL_WIKISTRING + + URL_WIKISTRING + "GEPS_029:_GTK3-GObject_introspection" "_Conversion#Spell_Check_Install" } obj.set_tooltip_text( @@ -1294,23 +1294,23 @@ class GrampsPreferences(ConfigureDialog): "%(gramps_wiki_build_spell_url)s") % spell_dict ) current_line += 1 - self.add_checkbox(grid, - _('Display Tip of the Day'), + self.add_checkbox(grid, + _('Display Tip of the Day'), current_line, 'behavior.use-tips') current_line += 1 - self.add_checkbox(grid, - _('Remember last view displayed'), + self.add_checkbox(grid, + _('Remember last view displayed'), current_line, 'preferences.use-last-view') current_line += 1 - self.add_spinner(grid, + self.add_spinner(grid, _('Max generations for relationships'), current_line, 'behavior.generation-depth', (5, 50), self.update_gendepth) current_line += 1 self.path_entry = Gtk.Entry() - self.add_path_box(grid, + self.add_path_box(grid, _('Base path for relative media paths'), current_line, self.path_entry, self.dbstate.db.get_mediapath(), self.set_mediapath, self.select_mediapath) @@ -1318,10 +1318,10 @@ class GrampsPreferences(ConfigureDialog): current_line += 1 # Check for updates: obox = Gtk.ComboBoxText() - formats = [_("Never"), - _("Once a month"), - _("Once a week"), - _("Once a day"), + formats = [_("Never"), + _("Once a month"), + _("Once a week"), + _("Once a day"), _("Always"), ] list(map(obox.append_text, formats)) active = config.get('behavior.check-for-updates') @@ -1333,8 +1333,8 @@ class GrampsPreferences(ConfigureDialog): current_line += 1 self.whattype_box = Gtk.ComboBoxText() - formats = [_("Updated addons only"), - _("New addons only"), + formats = [_("Updated addons only"), + _("New addons only"), _("New and updated addons"),] list(map(self.whattype_box.append_text, formats)) whattype = config.get('behavior.check-for-update-types') @@ -1409,8 +1409,8 @@ class GrampsPreferences(ConfigureDialog): obox.pack_start(cell, True) obox.add_attribute(cell, 'text', 1) # Build model: - model = Gtk.ListStore(GObject.TYPE_INT, - GObject.TYPE_STRING, + model = Gtk.ListStore(GObject.TYPE_INT, + GObject.TYPE_STRING, GObject.TYPE_STRING) count = 0 active = 0 @@ -1430,20 +1430,20 @@ class GrampsPreferences(ConfigureDialog): current_line += 1 self.dbpath_entry = Gtk.Entry() - self.add_path_box(grid, + self.add_path_box(grid, _('Family Tree Database path'), current_line, self.dbpath_entry, config.get('behavior.database-path'), self.set_dbpath, self.select_dbpath) current_line += 1 - #self.add_entry(grid, - # _('Family Tree Database path'), + #self.add_entry(grid, + # _('Family Tree Database path'), # 0, 'behavior.database-path') - self.add_checkbox(grid, - _('Automatically load last Family Tree'), + self.add_checkbox(grid, + _('Automatically load last Family Tree'), current_line, 'behavior.autoload') current_line += 1 - + return _('Family Tree'), grid def set_mediapath(self, *obj): diff --git a/gramps/gui/dbguielement.py b/gramps/gui/dbguielement.py index 9ca37ff60..bc264eba9 100644 --- a/gramps/gui/dbguielement.py +++ b/gramps/gui/dbguielement.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -44,20 +44,20 @@ class DbGUIElement(object): On initialization, the method :meth:`_connect_db_signals` is called. Inheriting objects are advised to group the setup of the callman attribute here. - + .. attribute callman: a :class:`.CallbackManager` object, to be used to track specific changes in the db and set up callbacks """ def __init__(self, database): self.callman = CallbackManager(database) self._connect_db_signals() - + def _add_db_signal(self, name, callback): """ Convenience function to add a custom db signal. The attributes are just - passed to the callman object. + passed to the callman object. For primary objects, use the register method of the callman attribute. - + :param name: name of the signal to connect to :type name: string :param callback: function to call when signal is emitted @@ -65,18 +65,18 @@ class DbGUIElement(object): signal """ self.callman.add_db_signal(name, callback) - + def _connect_db_signals(self): """ - Convenience method that is called on initialization of DbGUIElement. + Convenience method that is called on initialization of DbGUIElement. Use this to group setup of the callman attribute. Also called in _change_db method """ pass - + def _cleanup_callbacks(self): """ - Remove all db callbacks. + Remove all db callbacks. This is done automatically on destruction of the object, but is normally needed earlier, calling this method does so. Use _change_db method if you need to remove the callbacks because the @@ -91,9 +91,9 @@ class DbGUIElement(object): def _change_db(self, database): """ - Change the database the GUI element works on to database. + Change the database the GUI element works on to database. This removes all callbacks and all registered handles. - + :param database: the new database to connect to """ dbold = self.callman.database diff --git a/gramps/gui/dbloader.py b/gramps/gui/dbloader.py index 4d46f4ad0..947cce675 100644 --- a/gramps/gui/dbloader.py +++ b/gramps/gui/dbloader.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -56,9 +56,9 @@ from gramps.gen.db.dbconst import DBBACKEND _ = glocale.translation.gettext from gramps.cli.grampscli import CLIDbLoader from gramps.gen.config import config -from gramps.gen.db.exceptions import (DbUpgradeRequiredError, - BsddbDowngradeError, - DbVersionError, +from gramps.gen.db.exceptions import (DbUpgradeRequiredError, + BsddbDowngradeError, + DbVersionError, DbEnvironmentError, BsddbUpgradeRequiredError, BsddbDowngradeRequiredError, @@ -66,7 +66,7 @@ from gramps.gen.db.exceptions import (DbUpgradeRequiredError, PythonDowngradeError) from gramps.gen.constfunc import conv_to_unicode from .pluginmanager import GuiPluginManager -from .dialog import (DBErrorDialog, ErrorDialog, QuestionDialog2, +from .dialog import (DBErrorDialog, ErrorDialog, QuestionDialog2, WarningDialog) from .user import User from gramps.gen.errors import DbError @@ -81,18 +81,18 @@ class DbLoader(CLIDbLoader): CLIDbLoader.__init__(self, dbstate) self.uistate = uistate self.import_info = None - + def _warn(self, title, warnmessage): WarningDialog(title, warnmessage, parent=self.uistate.window) - + def _errordialog(self, title, errormessage): """ - Show the error. + Show the error. In the GUI, the error is shown, and a return happens """ ErrorDialog(title, errormessage, parent=self.uistate.window) return 1 - + def _dberrordialog(self, msg): import traceback exc = traceback.format_exc() @@ -102,12 +102,12 @@ class DbLoader(CLIDbLoader): except: DBErrorDialog(str(msg), parent=self.uistate.window) _LOG.error(str(msg) +"\n" + exc) - + def _begin_progress(self): self.uistate.set_busy_cursor(True) self.uistate.progress.show() self.uistate.pulse_progressbar(0) - + def _pulse_progress(self, value): self.uistate.pulse_progressbar(value) @@ -132,15 +132,15 @@ class DbLoader(CLIDbLoader): self.uistate.window) if not warn_dialog.run(): return False - + pmgr = GuiPluginManager.get_instance() - - import_dialog = Gtk.FileChooserDialog(_('Gramps: Import Family Tree'), - self.uistate.window, - Gtk.FileChooserAction.OPEN, + + import_dialog = Gtk.FileChooserDialog(_('Gramps: Import Family Tree'), + self.uistate.window, + Gtk.FileChooserAction.OPEN, (_('_Cancel'), - Gtk.ResponseType.CANCEL, - _('Import'), + Gtk.ResponseType.CANCEL, + _('Import'), Gtk.ResponseType.OK)) import_dialog.set_local_only(False) @@ -159,7 +159,7 @@ class DbLoader(CLIDbLoader): (box, type_selector) = format_maker() import_dialog.set_extra_widget(box) - # Suggested folder: try last open file, import, then last export, + # Suggested folder: try last open file, import, then last export, # then home. default_dir = config.get('paths.recent-import-dir') if len(default_dir)<=1: @@ -178,24 +178,24 @@ class DbLoader(CLIDbLoader): (the_path, the_file) = os.path.split(filename) config.set('paths.recent-import-dir', the_path) - + extension = type_selector.get_value() if extension == 'auto': # Guess the file format based on the file extension. - # This will get the lower case extension without a period, + # This will get the lower case extension without a period, # or an empty string. extension = os.path.splitext(filename)[-1][1:].lower() - + for plugin in pmgr.get_import_plugins(): if extension == plugin.get_extension(): - self.do_import(import_dialog, - plugin.get_import_function(), + self.do_import(import_dialog, + plugin.get_import_function(), filename) return True # Finally, we give up and declare this an unknown format ErrorDialog( - _("Could not open file: %s") % filename, + _("Could not open file: %s") % filename, _('File type "%s" is unknown to Gramps.\n\n' 'Valid types are: Gramps database, Gramps XML, ' 'Gramps package, GEDCOM, and others.') % extension, @@ -207,9 +207,9 @@ class DbLoader(CLIDbLoader): def check_errors(self, filename): """ Run common error checks and return True if any found. - + In this process, a warning dialog can pop up. - + """ if not isinstance(filename, str): return True @@ -220,14 +220,14 @@ class DbLoader(CLIDbLoader): return True elif os.path.isdir(filename): ErrorDialog( - _('Cannot open file'), + _('Cannot open file'), _('The selected file is a directory, not a file.\n'), parent=self.uistate.window) return True elif os.path.exists(filename): if not os.access(filename, os.R_OK): ErrorDialog( - _('Cannot open file'), + _('Cannot open file'), _('You do not have read access to the selected file.'), parent=self.uistate.window) return True @@ -251,7 +251,7 @@ class DbLoader(CLIDbLoader): self._begin_progress() try: - #an importer can return an object with info, object.info_text() + #an importer can return an object with info, object.info_text() #returns that info. Otherwise None is set to import_info self.import_info = importer(self.dbstate.db, filename, User(callback=self._pulse_progress, @@ -260,7 +260,7 @@ class DbLoader(CLIDbLoader): config.set('paths.recent-import-dir', dirname) except UnicodeError as msg: ErrorDialog( - _("Could not import file: %s") % filename, + _("Could not import file: %s") % filename, _("This file incorrectly identifies its character " "set, so it cannot be accurately imported. Please fix the " "encoding, and import again") + "\n\n %s" % msg, @@ -268,7 +268,7 @@ class DbLoader(CLIDbLoader): except Exception: _LOG.error("Failed to import database.", exc_info=True) self._end_progress() - + def import_info_text(self): """ On import the importer can construct an info object about the import. @@ -278,13 +278,13 @@ class DbLoader(CLIDbLoader): if self.import_info is None: return "" return self.import_info.info_text() - + def read_file(self, filename): """ This method takes care of changing database, and loading the data. - In 3.0 we only allow reading of real databases of filetype + In 3.0 we only allow reading of real databases of filetype 'x-directory/normal' - + This method should only return on success. Returning on failure makes no sense, because we cannot recover, since database has already been changed. @@ -297,7 +297,7 @@ class DbLoader(CLIDbLoader): if os.path.exists(filename): if not os.access(filename, os.W_OK): mode = "r" - self._warn(_('Read only database'), + self._warn(_('Read only database'), _('You do not have write access ' 'to the selected file.')) else: @@ -317,7 +317,7 @@ class DbLoader(CLIDbLoader): self.dbstate.no_database() self._begin_progress() - + force_schema_upgrade = False force_bsddb_upgrade = False force_bsddb_downgrade = False @@ -325,7 +325,7 @@ class DbLoader(CLIDbLoader): try: while True: try: - db.load(filename, self._pulse_progress, + db.load(filename, self._pulse_progress, mode, force_schema_upgrade, force_bsddb_upgrade, force_bsddb_downgrade, @@ -335,10 +335,10 @@ class DbLoader(CLIDbLoader): break except DbUpgradeRequiredError as msg: if QuestionDialog2(_("Are you sure you want to upgrade " - "this Family Tree?"), - str(msg), + "this Family Tree?"), + str(msg), _("I have made a backup,\n" - "please upgrade my Family Tree"), + "please upgrade my Family Tree"), _("Cancel"), self.uistate.window).run(): force_schema_upgrade = True force_bsddb_upgrade = False @@ -349,10 +349,10 @@ class DbLoader(CLIDbLoader): break except BsddbUpgradeRequiredError as msg: if QuestionDialog2(_("Are you sure you want to upgrade " - "this Family Tree?"), - str(msg), + "this Family Tree?"), + str(msg), _("I have made a backup,\n" - "please upgrade my Family Tree"), + "please upgrade my Family Tree"), _("Cancel"), self.uistate.window).run(): force_schema_upgrade = False force_bsddb_upgrade = True @@ -363,10 +363,10 @@ class DbLoader(CLIDbLoader): break except BsddbDowngradeRequiredError as msg: if QuestionDialog2(_("Are you sure you want to downgrade " - "this Family Tree?"), - str(msg), + "this Family Tree?"), + str(msg), _("I have made a backup,\n" - "please downgrade my Family Tree"), + "please downgrade my Family Tree"), _("Cancel"), self.uistate.window).run(): force_schema_upgrade = False force_bsddb_upgrade = False @@ -377,10 +377,10 @@ class DbLoader(CLIDbLoader): break except PythonUpgradeRequiredError as msg: if QuestionDialog2(_("Are you sure you want to upgrade " - "this Family Tree?"), - str(msg), + "this Family Tree?"), + str(msg), _("I have made a backup,\n" - "please upgrade my Family Tree"), + "please upgrade my Family Tree"), _("Cancel"), self.uistate.window).run(): force_schema_upgrade = False force_bsddb_upgrade = False @@ -421,7 +421,7 @@ class DbLoader(CLIDbLoader): # #------------------------------------------------------------------------- def get_default_dir(): - # Suggested folder: try last open file, last import, last export, + # Suggested folder: try last open file, last import, last export, # then home. default_dir = os.path.dirname(config.get('paths.recent-file')) if default_dir: @@ -467,7 +467,7 @@ class GrampsFormatWidget(Gtk.ComboBox): self.pack_start(cell, True) self.add_attribute(cell, 'text', 0) self.format_list = format_list - + for format, label in format_list: self.store.append(row=[label]) self.set_active(False) @@ -481,14 +481,14 @@ class GrampsFormatWidget(Gtk.ComboBox): def format_maker(): """ A factory function making format selection widgets. - + Accepts a list of formats to include into selector. The auto selection is always added as the first one. The returned box contains both the label and the selector. """ pmgr = GuiPluginManager.get_instance() format_list = [ ('auto', _('Automatically detected')) ] - + for plugin in pmgr.get_import_plugins(): format_list.append( (plugin.get_extension(), plugin.get_name()) ) diff --git a/gramps/gui/dbman.py b/gramps/gui/dbman.py index 890c93f8e..06915ac41 100644 --- a/gramps/gui/dbman.py +++ b/gramps/gui/dbman.py @@ -128,7 +128,7 @@ class Information(ManagedWindow): s.add(treeview) self.window.vbox.pack_start(s, True, True, 0) self.show() - + def on_ok_clicked(self, obj): self.window.close() @@ -148,7 +148,7 @@ class DbManager(CLIDbManager): } ERROR = ErrorDialog - + def __init__(self, uistate, dbstate, parent=None): """ Create the top level window from the glade description, and extracts @@ -179,7 +179,7 @@ class DbManager(CLIDbManager): def __connect_signals(self): """ - Connects the signals to the buttons on the interface. + Connects the signals to the buttons on the interface. """ ddtarget = DdTargets.URI_LIST self.top.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.COPY) @@ -205,7 +205,7 @@ class DbManager(CLIDbManager): def __button_press(self, obj, event): """ - Checks for a double click event. In the tree view, we want to + Checks for a double click event. In the tree view, we want to treat a double click as if it was OK button press. However, we have to make sure that an item was selected first. """ @@ -228,7 +228,7 @@ class DbManager(CLIDbManager): def __selection_changed(self, selection): """ - Called when the selection is changed in the TreeView. + Called when the selection is changed in the TreeView. """ self.__update_buttons(selection) @@ -240,7 +240,7 @@ class DbManager(CLIDbManager): buttons are disabled, and the Open button is disabled if the row represents a open database. """ - + # Get the current selection store, node = selection.get_selected() @@ -253,7 +253,7 @@ class DbManager(CLIDbManager): self.repair.set_sensitive(False) self.remove.set_sensitive(False) return - + path = self.model.get_path(node) if path is None: return @@ -278,7 +278,7 @@ class DbManager(CLIDbManager): self.repair.set_sensitive(os.path.isfile(backup)) else: self.repair.set_sensitive(False) - + self.rename.set_sensitive(True) self.info.set_sensitive(True) self.remove.set_sensitive(True) @@ -297,7 +297,7 @@ class DbManager(CLIDbManager): 'edited' signal, so that we can change the name when the user changes the column. - The last accessed column simply displays the last time famtree was + The last accessed column simply displays the last time famtree was opened. """ @@ -307,7 +307,7 @@ class DbManager(CLIDbManager): render.connect('edited', self.__change_name) render.connect('editing-canceled', self.__stop_edit) render.connect('editing-started', self.__start_edit) - self.column = Gtk.TreeViewColumn(_('Family Tree name'), render, + self.column = Gtk.TreeViewColumn(_('Family Tree name'), render, text=NAME_COL) self.column.set_sort_column_id(NAME_COL) self.column.set_sort_indicator(True) @@ -318,7 +318,7 @@ class DbManager(CLIDbManager): # build the icon column render = Gtk.CellRendererPixbuf() - #icon_column = Gtk.TreeViewColumn(_('Status'), render, + #icon_column = Gtk.TreeViewColumn(_('Status'), render, #icon_name=ICON_COL) icon_column = Gtk.TreeViewColumn(_('Status'), render) icon_column.set_cell_data_func(render, bug_fix) @@ -336,7 +336,7 @@ class DbManager(CLIDbManager): """ self._populate_cli() self._populate_model() - + def _populate_model(self): """ Builds the display model. @@ -382,7 +382,7 @@ class DbManager(CLIDbManager): # don't open a locked file if store.get_value(node, ICON_COL) == 'gramps-lock': self.__ask_to_break_lock(store, node) - continue + continue # don't open a version if len(store.get_path(node).get_indices()) > 1: continue @@ -455,9 +455,9 @@ class DbManager(CLIDbManager): def __change_name(self, renderer_sel, path, new_text): """ Change the name of the database. This is a callback from the - column, which has been marked as editable. + column, which has been marked as editable. - If the new string is empty, do nothing. Otherwise, renaming the + If the new string is empty, do nothing. Otherwise, renaming the database is simply changing the contents of the name file. """ #path is a string, convert to TreePath first @@ -471,13 +471,13 @@ class DbManager(CLIDbManager): self.__rename_revision(path, new_text) else: self.__rename_database(path, new_text) - + self.name_renderer.set_property('editable', False) self.__update_buttons(self.selection) def __rename_revision(self, path, new_text): """ - Renames the RCS revision using the rcs command. The rcs command + Renames the RCS revision using the rcs command. The rcs command is in the format of: rcs -mREV:NEW_NAME archive @@ -517,7 +517,7 @@ class DbManager(CLIDbManager): node = self.model.get_iter(path) filename = self.model.get_value(node, FILE_COL) if self.existing_name(new_text, skippath=path): - DbManager.ERROR(_("Could not rename the Family Tree."), + DbManager.ERROR(_("Could not rename the Family Tree."), _("Family Tree already exists, choose a unique name.")) return old_text, new_text = self.rename_database(filename, new_text) @@ -547,24 +547,24 @@ class DbManager(CLIDbManager): self.__checkout_copy(parent_name, name, revision, db_path) else: base_path = self.dbstate.db.get_save_path() - archive = os.path.join(base_path, ARCHIVE) + archive = os.path.join(base_path, ARCHIVE) check_in(self.dbstate.db, archive, User(), self.__start_cursor) self.__end_cursor() self.__populate() - + def __checkout_copy(self, parent_name, name, revision, db_path): """ Create a new database, then extracts a revision from RCS and imports it into the db """ new_path, newname = self._create_new_db("%s : %s" % (parent_name, name)) - + self.__start_cursor(_("Extracting archive...")) dbase = self.dbstate.make_database("bsddb") dbase.load(new_path, None) - + self.__start_cursor(_("Importing archive...")) check_out(dbase, revision, db_path, User()) self.__end_cursor() @@ -590,7 +590,7 @@ class DbManager(CLIDbManager): parent = store[(path[0],)][0] QuestionDialog( _("Remove the '%(revision)s' version of '%(database)s'") % { - 'revision' : rev, + 'revision' : rev, 'database' : parent }, _("Removing this version will prevent you from " @@ -609,7 +609,7 @@ class DbManager(CLIDbManager): # active database if self.data_to_delete[PATH_COL] == self.active: self.dbstate.no_database() - + store, node = self.selection.get_selected() path = store.get_path(node) node = self.model.get_iter(path) @@ -629,7 +629,7 @@ class DbManager(CLIDbManager): str(msg)) # rebuild the display self.__populate() - + def __really_delete_version(self): """ Delete the selected database. If the database is open, close it first. @@ -657,10 +657,10 @@ class DbManager(CLIDbManager): # rebuild the display self.__populate() - + def __rename_db(self, obj): """ - Start the rename process by calling the start_editing option on + Start the rename process by calling the start_editing option on the line with the cursor. """ store, node = self.selection.get_selected() @@ -681,12 +681,12 @@ class DbManager(CLIDbManager): def __repair_db(self, obj): """ - Start the repair process by calling the start_editing option on + Start the repair process by calling the start_editing option on the line with the cursor. """ store, node = self.selection.get_selected() dirname = store[node][1] - + #First ask user if he is really sure :-) yes_no = QuestionDialog2( _("Repair Family Tree?"), @@ -727,11 +727,11 @@ class DbManager(CLIDbManager): prompt = yes_no.run() if not prompt: return - + opened = store[node][OPEN_COL] if opened: self.dbstate.no_database() - + # delete files that are not backup files or the .txt file for filename in os.listdir(dirname): if os.path.splitext(filename)[1] not in (".gbkp", ".txt"): @@ -746,7 +746,7 @@ class DbManager(CLIDbManager): dbase.load(dirname, None) self.__start_cursor(_("Rebuilding database from backup files")) - + try: dbase.restore() except DbException as msg: @@ -778,7 +778,7 @@ class DbManager(CLIDbManager): def __new_db(self, obj): """ Callback wrapper around the actual routine that creates the - new database. Catch OSError and IOError and display a warning + new database. Catch OSError and IOError and display a warning message. """ self.new.set_sensitive(False) @@ -799,7 +799,7 @@ class DbManager(CLIDbManager): create_db, dbid) path_name = os.path.join(new_path, NAME_FILE) (tval, last) = time_val(new_path) - node = self.model.append(None, [title, new_path, path_name, + node = self.model.append(None, [title, new_path, path_name, last, tval, False, '']) self.selection.select_iter(node) path = self.model.get_path(node) @@ -807,7 +807,7 @@ class DbManager(CLIDbManager): self.dblist.set_cursor(path, self.column, True) return new_path, title - def __drag_data_received(self, widget, context, xpos, ypos, selection, + def __drag_data_received(self, widget, context, xpos, ypos, selection, info, rtime): """ Handle the reception of drag data @@ -860,7 +860,7 @@ def find_revisions(name): date_str = "" rev_str = "" com_str = "" - + get_next = False if os.path.isfile(name): for line in proc.stdout: @@ -875,7 +875,7 @@ def find_revisions(name): if match: date_str = time.strftime('%x %X', time.strptime(match.groups()[0], '%Y-%m-%d %H:%M:%S')) - + get_next = True continue if get_next: @@ -908,7 +908,7 @@ def check_out(dbase, rev, path, user): _("An attempt to retrieve the data failed " "with the following message:\n\n%s") % message ) - return + return pmgr = GuiPluginManager.get_instance() for plugin in pmgr.get_import_plugins(): @@ -926,7 +926,7 @@ def check_in(dbase, filename, user, cursor_func = None): init = [ "rcs", '-x,v', '-i', '-U', '-q', '-t-"Gramps database"' ] ci_cmd = [ "ci", '-x,v', "-q", "-f" ] archive_name = filename + ",v" - + glade = Glade(toplevel='comment') top = glade.toplevel text = glade.get_object('description') @@ -942,7 +942,7 @@ def check_in(dbase, filename, user, cursor_func = None): message = "\n".join(proc.stderr.readlines()) proc.stderr.close() del proc - + if status != 0: ErrorDialog( _("Archiving failed"), @@ -952,7 +952,7 @@ def check_in(dbase, filename, user, cursor_func = None): if cursor_func: cursor_func(_("Creating data to be archived...")) - + plugin_manager = GuiPluginManager.get_instance() for plugin in plugin_manager.get_export_plugins(): if plugin.get_extension() == "gramps": @@ -961,9 +961,9 @@ def check_in(dbase, filename, user, cursor_func = None): if cursor_func: cursor_func(_("Saving archive...")) - + cmd = ci_cmd + ['-m%s' % comment, filename, archive_name ] - proc = subprocess.Popen(cmd, + proc = subprocess.Popen(cmd, stderr = subprocess.PIPE) status = proc.wait() @@ -981,7 +981,7 @@ def check_in(dbase, filename, user, cursor_func = None): def bug_fix(column, renderer, model, iter_, data): """ Cell data function to set the status column. - + There is a bug in pygobject which prevents us from setting a value to None using the TreeModel set_value method. Instead we set it to an empty string and convert it to None here. diff --git a/gramps/gui/ddtargets.py b/gramps/gui/ddtargets.py index 4f0613b82..10fdbb519 100644 --- a/gramps/gui/ddtargets.py +++ b/gramps/gui/ddtargets.py @@ -42,7 +42,7 @@ drag_dest_set(Gtk.DestDefaults.ALL, DdTargets.all_targets(), Gdk.DragAction.COPY) - + """ #------------------------------------------------------------------------- @@ -58,10 +58,10 @@ from gi.repository import Gtk class _DdType: """Represents the fields needed by a drag and drop target.""" - + _APP_ID_OFFSET = 40 # Starting value of app_ids - - def __init__(self, container, drag_type, + + def __init__(self, container, drag_type, target_flags=0, app_id=None): """Create a new DdType: @@ -69,7 +69,7 @@ class _DdType: target_flags: int value that will be passed to drop target. app_id: integer target id passed to drop target. """ - + self.drag_type = drag_type self.atom_drag_type = Gdk.atom_intern(drag_type, False) self.target_flags = target_flags @@ -78,14 +78,14 @@ class _DdType: def _calculate_id(self): """Return the next available app_id.""" - + idval = _DdType._APP_ID_OFFSET _DdType._APP_ID_OFFSET += 1 return idval def target(self): """ - Return the full target information in the format required by the + Return the full target information in the format required by the Gtk functions. """ return Gtk.TargetEntry.new(self.drag_type, self.target_flags, @@ -107,23 +107,23 @@ class _DdType: class _DdTargets(object): """A single class that manages all the drag and drop targets.""" - + _instance = None # Singleton instance def __new__(cls): """Ensure that we never have more than one instance.""" - + if _DdTargets._instance: return _DdTargets._instance _DdTargets._instance = object.__new__(cls) - return _DdTargets._instance + return _DdTargets._instance def __init__(self): """Set up the drag and drop targets.""" - + self._type_map = {} self._app_id_map = {} - + self.ADDRESS = _DdType(self, 'paddr') self.ATTRIBUTE = _DdType(self, 'pattr') self.CHILDREF = _DdType(self, 'childref') @@ -159,35 +159,35 @@ class _DdTargets(object): # gramps widgets but should not be exported # to non gramps widgets. self._all_gramps_types = [ - self.ADDRESS, - self.ATTRIBUTE, - self.CHILDREF, - self.EVENT, - self.EVENTREF, - self.LOCATION, - self.MEDIAOBJ, - self.MEDIAREF, - self.NAME, - self.NOTE_LINK, - self.PLACE_LINK, - self.PLACEREF, + self.ADDRESS, + self.ATTRIBUTE, + self.CHILDREF, + self.EVENT, + self.EVENTREF, + self.LOCATION, + self.MEDIAOBJ, + self.MEDIAREF, + self.NAME, + self.NOTE_LINK, + self.PLACE_LINK, + self.PLACEREF, self.PLACENAME, - self.PERSON_LINK, - self.FAMILY_LINK, - self.LINK_LIST, - self.RAW_LIST, - self.HANDLE_LIST, - self.PERSONREF, - self.REPO_LINK, - self.REPOREF, - self.SOURCEREF, - self.SOURCE_LINK, - self.SRCATTRIBUTE, - self.URL, + self.PERSON_LINK, + self.FAMILY_LINK, + self.LINK_LIST, + self.RAW_LIST, + self.HANDLE_LIST, + self.PERSONREF, + self.REPO_LINK, + self.REPOREF, + self.SOURCEREF, + self.SOURCE_LINK, + self.SRCATTRIBUTE, + self.URL, self.SURNAME, self.CITATION_LINK ] - + self.CHILD = _DdType(self, 'child') self.SPOUSE = _DdType(self, 'spouse') self.TEXT_MIME = _DdType(self, 'text/plain', 0, 0) @@ -200,10 +200,10 @@ class _DdTargets(object): # List of all the text types. These are types # that can be interpreted as text. - self._all_text_types = (self.UTF8_STRING, - self.TEXT, - self.TEXT_MIME, - self.STRING, + self._all_text_types = (self.UTF8_STRING, + self.TEXT, + self.TEXT_MIME, + self.STRING, self.COMPOUND_TEXT) def insert(self, dd_type): @@ -211,7 +211,7 @@ class _DdTargets(object): Add a target to the lookup lists. These lists are used purely for performance reasons. """ - + self._type_map[dd_type.drag_type] = dd_type self._app_id_map[dd_type.app_id] = dd_type @@ -226,15 +226,15 @@ class _DdTargets(object): def all_text(self): return self._all_text_types - + def all_text_types(self): """ Return a list of all the type names that could be used as the type of a string. """ - + return tuple([t.drag_type for t in self._all_text_types]) - + def is_gramps_type(self, type_name): return type_name in self.all_gramps_types() @@ -245,7 +245,7 @@ class _DdTargets(object): def all_text_targets(self): """Return a list of all the targets that could be used for text.""" - + return tuple([t.target() for t in self._all_text_types]) def all_gramps_targets(self): diff --git a/gramps/gui/dialog.py b/gramps/gui/dialog.py index 5ffd7a6a0..4d0ff7b08 100644 --- a/gramps/gui/dialog.py +++ b/gramps/gui/dialog.py @@ -55,19 +55,19 @@ except: class SaveDialog(object): def __init__(self, msg1, msg2, task1, task2, parent=None): self.xml = Glade(toplevel='savedialog') - + self.top = self.xml.toplevel self.top.set_icon(ICON) self.top.set_title("%s - Gramps" % msg1) - + self.dontask = self.xml.get_object('dontask') self.task1 = task1 self.task2 = task2 - + label1 = self.xml.get_object('sd_label1') label1.set_text('%s' % msg1) label1.set_use_markup(True) - + label2 = self.xml.get_object('sd_label2') label2.set_text(msg2) label2.set_use_markup(True) @@ -86,7 +86,7 @@ class SaveDialog(object): class QuestionDialog(object): def __init__(self, msg1, msg2, label, task, parent=None): self.xml = Glade(toplevel='questiondialog') - + self.top = self.xml.toplevel self.top.set_icon(ICON) self.top.set_title("%s - Gramps" % msg1) @@ -94,7 +94,7 @@ class QuestionDialog(object): label1 = self.xml.get_object('qd_label1') label1.set_text('%s' % msg1) label1.set_use_markup(True) - + label2 = self.xml.get_object('qd_label2') label2.set_text(msg2) label2.set_use_markup(True) @@ -118,7 +118,7 @@ def on_activate_link(label, uri): class QuestionDialog2(object): def __init__(self, msg1, msg2, label_msg1, label_msg2, parent=None): self.xml = Glade(toplevel='questiondialog') - + self.top = self.xml.toplevel self.top.set_icon(ICON) self.top.set_title("%s - Gramps" % msg1) @@ -126,7 +126,7 @@ class QuestionDialog2(object): label1 = self.xml.get_object('qd_label1') label1.set_text('%s' % msg1) label1.set_use_markup(True) - + label2 = self.xml.get_object('qd_label2') # see https://github.com/emesene/emesene/issues/723 label2.connect('activate-link', on_activate_link) @@ -137,7 +137,7 @@ class QuestionDialog2(object): self.xml.get_object('okbutton').set_use_underline(True) self.xml.get_object('no').set_label(label_msg2) self.xml.get_object('no').set_use_underline(True) - + if parent: self.top.set_transient_for(parent) self.top.show() @@ -150,7 +150,7 @@ class QuestionDialog2(object): class OptionDialog(object): def __init__(self, msg1, msg2, btnmsg1, task1, btnmsg2, task2, parent=None): self.xml = Glade(toplevel='optiondialog') - + self.top = self.xml.toplevel self.top.set_icon(ICON) self.top.set_title("%s - Gramps" % msg1) @@ -158,7 +158,7 @@ class OptionDialog(object): label1 = self.xml.get_object('od_label1') label1.set_text('%s' % msg1) label1.set_use_markup(True) - + label2 = self.xml.get_object('od_label2') label2.set_text(msg2) label2.set_use_markup(True) @@ -182,7 +182,7 @@ class OptionDialog(object): class ErrorDialog(Gtk.MessageDialog): def __init__(self, msg1, msg2="", parent=None): - + Gtk.MessageDialog.__init__(self, parent, flags=Gtk.DialogFlags.MODAL, type=Gtk.MessageType.ERROR, @@ -258,7 +258,7 @@ class InfoDialog(object): """ def __init__(self, msg1, infotext, parent=None, monospaced=False): self.xml = Glade(toplevel='infodialog') - + self.top = self.xml.toplevel self.top.set_icon(ICON) self.top.set_title("%s - Gramps" % msg1) @@ -266,7 +266,7 @@ class InfoDialog(object): label = self.xml.get_object('toplabel') label.set_text('%s' % msg1) label.set_use_markup(True) - + infoview = self.xml.get_object('infoview') infobuffer = Gtk.TextBuffer() infobuffer.set_text(infotext) @@ -288,7 +288,7 @@ class InfoDialog(object): class MissingMediaDialog(object): def __init__(self, msg1, msg2, task1, task2, task3, parent=None): self.xml = Glade(toplevel='missmediadialog') - + self.top = self.xml.toplevel self.top.set_icon(ICON) self.top.set_title("%s - Gramps" % msg1) @@ -296,11 +296,11 @@ class MissingMediaDialog(object): self.task1 = task1 self.task2 = task2 self.task3 = task3 - + label1 = self.xml.get_object('label4') label1.set_text('%s' % msg1) label1.set_use_markup(True) - + label2 = self.xml.get_object('label3') label2.set_text(msg2) label2.set_use_markup(True) @@ -341,15 +341,15 @@ class MissingMediaDialog(object): class MultiSelectDialog(object): def __init__(self, msg1_func, msg2_func, items, lookup, - cancel_func=None, no_func=None, yes_func=None, + cancel_func=None, no_func=None, yes_func=None, parent=None): """ """ self.xml = Glade(toplevel='multiselectdialog') - + self.top = self.xml.toplevel self.top.set_icon(ICON) - + self.msg1_func = msg1_func self.msg2_func = msg2_func self.items = items @@ -357,7 +357,7 @@ class MultiSelectDialog(object): self.cancel_func = cancel_func self.no_func = no_func self.yes_func = yes_func - + label1 = self.xml.get_object('label6') label2 = self.xml.get_object('label5') check_button = self.xml.get_object('apply_to_rest') @@ -372,14 +372,14 @@ class MultiSelectDialog(object): if default_action == 0: msg1 = self.msg1_func(item) msg2 = self.msg2_func(item) - + self.top.set_title("%s - Gramps" % msg1) label1.set_text('%s' % msg1) label1.set_use_markup(True) label2.set_text(msg2) label2.set_use_markup(True) self.top.show() - + # Need some magic here, because an attempt to close the dialog # with the X button not only emits the 'delete_event' signal # but also exits with the RESPONSE_DELETE_EVENT @@ -413,10 +413,10 @@ class MultiSelectDialog(object): return True class MessageHideDialog(object): - + def __init__(self, title, message, key, parent=None): self.xml = Glade(toplevel='hidedialog') - + self.top = self.xml.toplevel self.top.set_icon(ICON) self.top.set_title("%s - Gramps" % title) @@ -427,9 +427,9 @@ class MessageHideDialog(object): title_label.set_text( '%s' % title) title_label.set_use_markup(True) - + self.xml.get_object('message').set_text(message) - + dont_show.connect('toggled', self.update_checkbox, key) self.top.run() self.top.destroy() @@ -454,11 +454,11 @@ def main(args): vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) win.add(vbox) - + btn1 = Gtk.Button('Info dialog') btn1.connect('clicked', test_info) vbox.pack_start(btn1, True, True, 0) - + win.show_all() Gtk.main() diff --git a/gramps/gui/display.py b/gramps/gui/display.py index 47fa50e49..702618a32 100644 --- a/gramps/gui/display.py +++ b/gramps/gui/display.py @@ -38,7 +38,7 @@ from gramps.gen.config import config from gramps.gui.utils import open_file_with_default_application as run_file #list of manuals on wiki, map locale code to wiki extension, add language codes -#completely, or first part, so pt_BR if Brazilian portugeze wiki manual, and +#completely, or first part, so pt_BR if Brazilian portugeze wiki manual, and #nl for Dutch (nl_BE, nl_NL language code) MANUALS = { 'nl' : '/nl', diff --git a/gramps/gui/displaystate.py b/gramps/gui/displaystate.py index 2f8e3c368..e9de4c64a 100644 --- a/gramps/gui/displaystate.py +++ b/gramps/gui/displaystate.py @@ -11,7 +11,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -73,13 +73,13 @@ DISABLED = -1 # #------------------------------------------------------------------------- class History(Callback): - """ History manages the objects of a certain type that have been viewed, - with ability to go back, or forward. + """ History manages the objects of a certain type that have been viewed, + with ability to go back, or forward. When accessing an object, it should be pushed on the History. """ __signals__ = { - 'active-changed' : (str, ), + 'active-changed' : (str, ), 'mru-changed' : (list, ) } @@ -100,7 +100,7 @@ class History(Callback): """ for sig in self.signal_map: dbstate.connect(sig, self.signal_map[sig]) - + def clear(self): """ Clears the history, resetting the values back to their defaults @@ -128,7 +128,7 @@ class History(Callback): for c in range(history_count): self.history.remove(del_id) self.index -= 1 - + mhc = self.mru.count(del_id) for c in range(mhc): self.mru.remove(del_id) @@ -156,7 +156,7 @@ class History(Callback): if not isinstance(newact, str): newact = str(newact) self.emit('active-changed', (newact,)) - + def forward(self, step=1): """ Moves forward in the history list @@ -191,7 +191,7 @@ class History(Callback): return newact except IndexError: return "" - + def present(self): """ return the person handle that is now active in the history @@ -203,7 +203,7 @@ class History(Callback): return "" except IndexError: return "" - + def at_end(self): """ returns True if we are at the end of the history list @@ -230,7 +230,7 @@ class History(Callback): """ for handle in handle_list: self.remove(handle) - + def history_changed(self): """ Called in response to an object-rebuild signal. @@ -238,7 +238,7 @@ class History(Callback): """ self.clear() self.emit('mru-changed', (self.mru, )) - + #------------------------------------------------------------------------- # # Recent Docs Menu @@ -270,13 +270,13 @@ class RecentDocsMenu(object): gramps_rf = RecentFiles() count = 0 - + if self.active != DISABLED: self.uimanager.remove_ui(self.active) self.uimanager.remove_action_group(self.action_group) self.action_group = Gtk.ActionGroup(name='RecentFiles') self.active = DISABLED - + actions = [] rfiles = gramps_rf.gramps_recent_files rfiles.sort(key=lambda x: x.get_time(), reverse=True) @@ -289,7 +289,7 @@ class RecentDocsMenu(object): filename = os.path.basename(item.get_path()) action_id = "RecentMenu%d" % count buf.write('' % action_id) - actions.append((action_id, None, title, None, None, + actions.append((action_id, None, title, None, None, make_callback(item, self.load))) mitem = Gtk.MenuItem(label=title, use_underline=False) mitem.connect('activate', make_callback(item, self.load)) @@ -298,7 +298,7 @@ class RecentDocsMenu(object): except RuntimeError: _LOG.info("Ignoring the RecentItem %s (%s)" % (title, filename)) pass # ignore no longer existing files - + count += 1 buf.write(_RCT_BTM) self.action_group.add_actions(actions) @@ -367,13 +367,13 @@ class WarnHandler(RotateHandler): class DisplayState(Callback): __signals__ = { - 'filters-changed' : (str, ), - 'filter-name-changed' : (str, str, str), - 'nameformat-changed' : None, - 'grampletbar-close-changed' : None, - 'update-available' : (list, ), + 'filters-changed' : (str, ), + 'filter-name-changed' : (str, str, str), + 'nameformat-changed' : None, + 'grampletbar-close-changed' : None, + 'update-available' : (list, ), } - + #nav_type to message NAV2MES = { 'Person': _("No active person"), @@ -416,7 +416,7 @@ class DisplayState(Callback): self.rhandler.setLevel(logging.WARNING) self.log = logging.getLogger() self.log.addHandler(self.rhandler) - # This call has been moved one level up, + # This call has been moved one level up, # but this connection is still made! # self.dbstate.connect('database-changed', self.db_changed) @@ -473,7 +473,7 @@ class DisplayState(Callback): def set_sensitive(self, state): self.window.set_sensitive(state) - + def db_changed(self, db): db.connect('long-op-start', self.progress_monitor.add_op) self.clear_history() @@ -488,10 +488,10 @@ class DisplayState(Callback): """ Set the generations we search back for showing relationships on GRAMPS interface. Value must be integer > 0 This method will be used by the preference editor when user changes - the generations. + the generations. """ self.relationship.set_depth(value) - + def display_relationship(self, dbstate, active_handle): """ Construct the relationship in order to show it in the statusbar This can be a time intensive calculation, so we only want to do @@ -539,7 +539,7 @@ class DisplayState(Callback): else: self.window.get_window().set_cursor(self.cursor) if self.window.get_window().is_visible(): - #avoid critical gdk error: + #avoid critical gdk error: #Gdk-CRITICAL **: gdk_error_trap_pop_internal: assertion `trap != NULL' failed #only process events if window is actually visible process_pending_events() @@ -556,7 +556,7 @@ class DisplayState(Callback): def show_filter_results(self, dbstate, matched, total): #nav_type = self.viewmanager.active_page.navigation_type() - #text = ((_("%(nav_type)s View") % {"nav_type": _(nav_type)}) + + #text = ((_("%(nav_type)s View") % {"nav_type": _(nav_type)}) + text = (self.viewmanager.active_page.get_title() + (": %d/%d" % (matched, total))) self.status.set_filter(text) @@ -571,7 +571,7 @@ class DisplayState(Callback): nav_type = view.navigation_type() active_handle = self.get_active(nav_type, view.navigation_group()) - + self.status.pop(self.status_id) name, obj = navigation_label(dbstate.db, nav_type, active_handle) diff --git a/gramps/gui/editors/__init__.py b/gramps/gui/editors/__init__.py index 5dfe0521c..42c831cad 100644 --- a/gramps/gui/editors/__init__.py +++ b/gramps/gui/editors/__init__.py @@ -62,7 +62,7 @@ EDITORS = { def EditObject(dbstate, uistate, track, obj_class, prop=None, value=None, callback=None): """ - Generic Object Editor. + Generic Object Editor. obj_class is Person, Source, Repository, etc. prop is 'handle', 'gramps_id', or None (for new object) value is string handle, string gramps_id, or None (for new object) @@ -75,16 +75,16 @@ def EditObject(dbstate, uistate, track, obj_class, prop=None, value=None, callba try: EDITORS[obj_class](dbstate, uistate, track, obj, callback=callback) except Exception as msg: - LOG.warn(str(msg)) + LOG.warn(str(msg)) elif prop in ("gramps_id", "handle"): obj = dbstate.db.get_table_metadata(obj_class)[prop + "_func"](value) if obj: try: EDITORS[obj_class](dbstate, uistate, track, obj, callback=callback) except Exception as msg: - LOG.warn(str(msg)) + LOG.warn(str(msg)) else: - LOG.warn("gramps://%s/%s/%s not found" % + LOG.warn("gramps://%s/%s/%s not found" % (obj_class, prop, value)) else: LOG.warn("unknown property to edit '%s'; " diff --git a/gramps/gui/editors/addmedia.py b/gramps/gui/editors/addmedia.py index 432484628..13a26bfbe 100644 --- a/gramps/gui/editors/addmedia.py +++ b/gramps/gui/editors/addmedia.py @@ -71,13 +71,13 @@ class AddMediaObject(ManagedWindow): Displays the Add Media Dialog window, allowing the user to select a file from the file system, while providing a description. """ - + def __init__(self, dbstate, uistate, track, mediaobj, callback=None): """ Create and displays the dialog box db - the database in which the new object is to be stored - The mediaobject is updated with the information, and on save, the + The mediaobject is updated with the information, and on save, the callback function is called """ ManagedWindow.__init__(self, uistate, track, self) @@ -88,13 +88,13 @@ class AddMediaObject(ManagedWindow): self.last_directory = config.get('behavior.addmedia-image-dir') self.relative_path = config.get('behavior.addmedia-relative-path') - + self.glade = Glade() self.set_window( self.glade.toplevel, self.glade.get_object('title'), _('Select a media object')) - + self.description = self.glade.get_object("photoDescription") self.image = self.glade.get_object("image") self.file_text = self.glade.get_object("fname") @@ -170,7 +170,7 @@ class AddMediaObject(ManagedWindow): self.obj.set_mime_type(mtype) name = filename self.obj.set_path(name) - + self.last_directory = os.path.dirname(full_file) self.relative_path = self.relpath.get_active() @@ -195,7 +195,7 @@ class AddMediaObject(ManagedWindow): if old_title == '' or old_title == self.temp_name: self.description.set_text(root) self.temp_name = root - + filename = find_file( filename) if filename: mtype = get_type(filename) @@ -223,12 +223,12 @@ def scale_image(path, size): title_msg = _("Cannot display %s") % path detail_msg = _('Gramps is not able to display the image file. ' 'This may be caused by a corrupt file.') - + try: image1 = GdkPixbuf.Pixbuf.new_from_file(path) width = image1.get_width() height = image1.get_height() - + scale = size / float(max(width, height)) return image1.scale_simple(int(scale*width), int(scale*height), GdkPixbuf.InterpType.BILINEAR) diff --git a/gramps/gui/editors/displaytabs/__init__.py b/gramps/gui/editors/displaytabs/__init__.py index 2a180ed1f..d25e6a1b7 100644 --- a/gramps/gui/editors/displaytabs/__init__.py +++ b/gramps/gui/editors/displaytabs/__init__.py @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # - + #------------------------------------------------------------------------- # # set up logging diff --git a/gramps/gui/editors/displaytabs/addrembedlist.py b/gramps/gui/editors/displaytabs/addrembedlist.py index cb98c92e7..d1c18e5c5 100644 --- a/gramps/gui/editors/displaytabs/addrembedlist.py +++ b/gramps/gui/editors/displaytabs/addrembedlist.py @@ -44,13 +44,13 @@ from .embeddedlist import EmbeddedList, TEXT_COL, MARKUP_COL, ICON_COL #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class AddrEmbedList(EmbeddedList): """ - Address List display tab for edit dialogs. - + Address List display tab for edit dialogs. + Derives from the EmbeddedList class. """ @@ -76,12 +76,12 @@ class AddrEmbedList(EmbeddedList): (_('Country'), 5, 75, TEXT_COL, -1, None), (_('Private'), 6, 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, data): self.data = data - EmbeddedList.__init__(self, dbstate, uistate, track, _('_Addresses'), + EmbeddedList.__init__(self, dbstate, uistate, track, _('_Addresses'), AddressModel, move_buttons=True) - + def get_icon_name(self): """ Return the stock-id icon name associated with the display tab @@ -104,13 +104,13 @@ class AddrEmbedList(EmbeddedList): """ Called when the Add button is clicked. Creates a new Address instance and calls the EditAddress editor with the new address. If the window - already exists (WindowActiveError), we ignore it. This prevents + already exists (WindowActiveError), we ignore it. This prevents the dialog from coming up twice on the same object. """ addr = Address() try: from .. import EditAddress - EditAddress(self.dbstate, self.uistate, self.track, + EditAddress(self.dbstate, self.uistate, self.track, addr, self.add_callback) except WindowActiveError: return @@ -128,14 +128,14 @@ class AddrEmbedList(EmbeddedList): """ Called with the Edit button is clicked. Gets the selected Address instance and calls the EditAddress editor with the address. If the window - already exists (WindowActiveError), we ignore it. This prevents + already exists (WindowActiveError), we ignore it. This prevents the dialog from coming up twice on the same object. """ addr = self.get_selected() if addr: try: from .. import EditAddress - EditAddress(self.dbstate, self.uistate, self.track, + EditAddress(self.dbstate, self.uistate, self.track, addr, self.edit_callback) except WindowActiveError: return diff --git a/gramps/gui/editors/displaytabs/addressmodel.py b/gramps/gui/editors/displaytabs/addressmodel.py index bc59f7834..d778ba7c2 100644 --- a/gramps/gui/editors/displaytabs/addressmodel.py +++ b/gramps/gui/editors/displaytabs/addressmodel.py @@ -54,12 +54,12 @@ class AddressModel(Gtk.ListStore): self.db = dbase for obj in obj_list: self.append(row=[ - get_date(obj), - obj.street, - obj.locality, - obj.city, - obj.state, + get_date(obj), + obj.street, + obj.locality, + obj.city, + obj.state, obj.country, obj.get_privacy(), - obj, + obj, ]) diff --git a/gramps/gui/editors/displaytabs/attrembedlist.py b/gramps/gui/editors/displaytabs/attrembedlist.py index 7c875a00d..856f4cd75 100644 --- a/gramps/gui/editors/displaytabs/attrembedlist.py +++ b/gramps/gui/editors/displaytabs/attrembedlist.py @@ -40,7 +40,7 @@ from .embeddedlist import EmbeddedList, TEXT_COL, MARKUP_COL, ICON_COL #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class AttrEmbedList(EmbeddedList): @@ -63,7 +63,7 @@ class AttrEmbedList(EmbeddedList): (_('Value'), 1, 200, TEXT_COL, -1, None), (_('Private'), 2, 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, data): """ Initialize the displaytab. The dbstate and uistate is needed @@ -72,7 +72,7 @@ class AttrEmbedList(EmbeddedList): edit """ self.data = data - EmbeddedList.__init__(self, dbstate, uistate, track, _('_Attributes'), + EmbeddedList.__init__(self, dbstate, uistate, track, _('_Attributes'), AttrModel, move_buttons=True) def get_editor(self): @@ -80,11 +80,11 @@ class AttrEmbedList(EmbeddedList): return EditAttribute def get_user_values(self): - return self.dbstate.db.get_person_attribute_types() + return self.dbstate.db.get_person_attribute_types() def get_icon_name(self): return 'gramps-attribute' - + def get_data(self): return self.data @@ -96,7 +96,7 @@ class AttrEmbedList(EmbeddedList): attr = Attribute() try: self.get_editor()( - self.dbstate, self.uistate, self.track, attr, + self.dbstate, self.uistate, self.track, attr, pname, self.get_user_values(), self.add_callback) except WindowActiveError: pass @@ -114,7 +114,7 @@ class AttrEmbedList(EmbeddedList): pname = '' try: self.get_editor()( - self.dbstate, self.uistate, self.track, attr, + self.dbstate, self.uistate, self.track, attr, pname, self.get_user_values(), self.edit_callback) except WindowActiveError: pass diff --git a/gramps/gui/editors/displaytabs/attrmodel.py b/gramps/gui/editors/displaytabs/attrmodel.py index 1f84adbf5..e1b25638d 100644 --- a/gramps/gui/editors/displaytabs/attrmodel.py +++ b/gramps/gui/editors/displaytabs/attrmodel.py @@ -44,8 +44,8 @@ class AttrModel(Gtk.ListStore): self.db = db for attr in attr_list: self.append(row=[ - str(attr.get_type()), - attr.get_value(), + str(attr.get_type()), + attr.get_value(), attr.get_privacy(), attr, ]) diff --git a/gramps/gui/editors/displaytabs/backreflist.py b/gramps/gui/editors/displaytabs/backreflist.py index 90504ab67..5b5e30041 100644 --- a/gramps/gui/editors/displaytabs/backreflist.py +++ b/gramps/gui/editors/displaytabs/backreflist.py @@ -60,10 +60,10 @@ class BackRefList(EmbeddedList): (_('ID'), 1, 75, TEXT_COL, -1, None), (_('Name'), 2, 250, TEXT_COL, -1, None), ] - + def __init__(self, dbstate, uistate, track, obj, refmodel, callback=None): self.obj = obj - EmbeddedList.__init__(self, dbstate, uistate, track, + EmbeddedList.__init__(self, dbstate, uistate, track, _('_References'), refmodel) self._callback = callback self.connectid = self.model.connect('row-inserted', self.update_label) @@ -91,7 +91,7 @@ class BackRefList(EmbeddedList): def _create_buttons(self, share=False, move=False, jump=False, top_label=None): """ - Create a button box consisting of one button: Edit. + Create a button box consisting of one button: Edit. This button box is then appended hbox (self). Method has signature of, and overrides create_buttons from _ButtonTab.py """ @@ -103,7 +103,7 @@ class BackRefList(EmbeddedList): hbox.pack_start(self.edit_btn, False, True, 0) hbox.show_all() self.pack_start(hbox, False, True, 0) - + self.add_btn = None self.del_btn = None @@ -131,7 +131,7 @@ class BackRefList(EmbeddedList): return (model.get_value(node, 4), model.get_value(node, 3)) except: return (None, None) - + def edit_button_clicked(self, obj): (reftype, ref) = self.find_node() edit_object(self.dbstate, self.uistate, reftype, ref) diff --git a/gramps/gui/editors/displaytabs/backrefmodel.py b/gramps/gui/editors/displaytabs/backrefmodel.py index d0b24f72e..7d34ef463 100644 --- a/gramps/gui/editors/displaytabs/backrefmodel.py +++ b/gramps/gui/editors/displaytabs/backrefmodel.py @@ -46,7 +46,7 @@ from gramps.gen.utils.db import family_name, get_participant_from_event # #------------------------------------------------------------------------- class BackRefModel(Gtk.ListStore): - + dispstr = _('%(part1)s - %(part2)s') def __init__(self, sref_list, db): @@ -63,8 +63,8 @@ class BackRefModel(Gtk.ListStore): def load_model(self): """ - Objects can have very large backreferences. To avoid blocking the - interface up to the moment that the model is created, this method is + Objects can have very large backreferences. To avoid blocking the + interface up to the moment that the model is created, this method is called via GLib.idle_add. WARNING: a consequence of above is that loading can still be happening while the GUI using this model is no longer used. Disconnect any diff --git a/gramps/gui/editors/displaytabs/buttontab.py b/gramps/gui/editors/displaytabs/buttontab.py index 047b28d27..8acdb290f 100644 --- a/gramps/gui/editors/displaytabs/buttontab.py +++ b/gramps/gui/editors/displaytabs/buttontab.py @@ -73,12 +73,12 @@ class ButtonTab(GrampsTab): 'up' : _('Move Up'), 'down' : _('Move Down'), } - + def __init__(self, dbstate, uistate, track, name, share_button=False, move_buttons=False, jump_button=False, top_label=None): """ Similar to the base class, except after Build. - + @param dbstate: The database state. Contains a reference to the database, along with other state information. The GrampsTab uses this to access the database and to pass to and created @@ -105,13 +105,13 @@ class ButtonTab(GrampsTab): GrampsTab.__init__(self,dbstate, uistate, track, name) self._create_buttons(share_button, move_buttons, jump_button, top_label) - def _create_buttons(self, share_button, move_buttons, jump_button, + def _create_buttons(self, share_button, move_buttons, jump_button, top_label): """ Create a button box consisting of three buttons, one for Add, - one for Edit, and one for Delete. - - Add buttons for Share, Move and Jump depending on parameters. This + one for Edit, and one for Delete. + + Add buttons for Share, Move and Jump depending on parameters. This button box is then appended hbox (self). Prepend a label if top_label given @@ -132,14 +132,14 @@ class ButtonTab(GrampsTab): self.add_btn.set_tooltip_text(self._MSG['add']) self.edit_btn.set_tooltip_text(self._MSG['edit']) self.del_btn.set_tooltip_text(self._MSG['del']) - + if share_button: self.share_btn = SimpleButton('gtk-index', self.share_button_clicked) self.share_btn.set_tooltip_text(self._MSG['share']) self.track_ref_for_deletion("share_btn") else: self.share_btn = None - + if move_buttons: self.up_btn = SimpleButton('go-up', self.up_button_clicked) self.up_btn.set_tooltip_text(self._MSG['up']) @@ -266,17 +266,17 @@ class ButtonTab(GrampsTab): class. """ print("Uncaught Edit clicked") - + def up_button_clicked(self, obj): """ - Function called with the Up button is clicked. + Function called with the Up button is clicked. This function should be overridden by the derived class. """ print("Uncaught Up clicked") - + def down_button_clicked(self, obj): """ - Function called with the Down button is clicked. + Function called with the Down button is clicked. This function should be overridden by the derived class. """ print("Uncaught Down clicked") @@ -289,7 +289,7 @@ class ButtonTab(GrampsTab): """ # Comparing to None is important, as empty strings # and 0 can be returned - # This method is called as callback on change, and can be called + # This method is called as callback on change, and can be called # explicitly, dirty_selection must make sure they do not interact if self.dirty_selection: return diff --git a/gramps/gui/editors/displaytabs/childmodel.py b/gramps/gui/editors/displaytabs/childmodel.py index 2458ee71b..6654a3f95 100644 --- a/gramps/gui/editors/displaytabs/childmodel.py +++ b/gramps/gui/editors/displaytabs/childmodel.py @@ -46,25 +46,25 @@ from gramps.gen.utils.db import get_birth_or_fallback, get_death_or_fallback class ChildModel(Gtk.ListStore): def __init__(self, child_ref_list, db): - Gtk.ListStore.__init__(self, int, str, str, str, str, str, + Gtk.ListStore.__init__(self, int, str, str, str, str, str, str, str, str, str, str, str, str, bool, object) self.db = db for index, child_ref in enumerate(child_ref_list): child = db.get_person_from_handle(child_ref.ref) if child: self.append(row=[ - index + 1, - child.get_gramps_id(), - name_displayer.display(child), - gender_map[child.get_gender()], - str(child_ref.get_father_relation()), + index + 1, + child.get_gramps_id(), + name_displayer.display(child), + gender_map[child.get_gender()], + str(child_ref.get_father_relation()), str(child_ref.get_mother_relation()), - self.column_birth_day(child), - self.column_death_day(child), - self.column_birth_place(child), - self.column_death_place(child), - name_displayer.sort_string(child.primary_name), - self.column_birth_sort(child), + self.column_birth_day(child), + self.column_death_day(child), + self.column_birth_place(child), + self.column_death_place(child), + name_displayer.sort_string(child.primary_name), + self.column_birth_sort(child), self.column_death_sort(child), child_ref.get_privacy(), child_ref @@ -81,9 +81,9 @@ class ChildModel(Gtk.ListStore): return "" def column_birth_sort(self, data): - """ - Return a sort key to use for the birth column. - As python int can be larger than C int, we cast int + """ + Return a sort key to use for the birth column. + As python int can be larger than C int, we cast int to a string of 10 long prepended with 0 as needed. This gives correct string sort for years in the millenia around today """ @@ -104,9 +104,9 @@ class ChildModel(Gtk.ListStore): return "" def column_death_sort(self, data): - """ - Return a sort key to use for the death column. - As python int can be larger than C int, we cast int + """ + Return a sort key to use for the death column. + As python int can be larger than C int, we cast int to a string of 10 long prepended with 0 as needed. This gives correct string sort for years in the millenia around today """ @@ -115,7 +115,7 @@ class ChildModel(Gtk.ListStore): return '%012d' % death.get_date_object().get_sort_value() else: return '%012d' % 0 - + def column_birth_place(self, data): event_ref = data.get_birth_ref() if event_ref and event_ref.ref: diff --git a/gramps/gui/editors/displaytabs/citationbackreflist.py b/gramps/gui/editors/displaytabs/citationbackreflist.py index 045fdba34..55d795088 100644 --- a/gramps/gui/editors/displaytabs/citationbackreflist.py +++ b/gramps/gui/editors/displaytabs/citationbackreflist.py @@ -30,7 +30,7 @@ from .backreflist import BackRefList class CitationBackRefList(BackRefList): def __init__(self, dbstate, uistate, track, obj, callback=None): - BackRefList.__init__(self, dbstate, uistate, track, obj, + BackRefList.__init__(self, dbstate, uistate, track, obj, BackRefModel, callback=callback) def get_icon_name(self): diff --git a/gramps/gui/editors/displaytabs/citationembedlist.py b/gramps/gui/editors/displaytabs/citationembedlist.py index 804e5ec41..7823a15bb 100644 --- a/gramps/gui/editors/displaytabs/citationembedlist.py +++ b/gramps/gui/editors/displaytabs/citationembedlist.py @@ -57,8 +57,8 @@ from ...ddtargets import DdTargets #------------------------------------------------------------------------- class CitationEmbedList(EmbeddedList, DbGUIElement): """ - Citation List display tab for edit dialogs. - + Citation List display tab for edit dialogs. + Derives from the EmbeddedList class. """ @@ -88,8 +88,8 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): def __init__(self, dbstate, uistate, track, data, callertitle=None): self.data = data self.callertitle = callertitle - EmbeddedList.__init__(self, dbstate, uistate, track, - _("_Source Citations"), CitationRefModel, + EmbeddedList.__init__(self, dbstate, uistate, track, + _("_Source Citations"), CitationRefModel, share_button=True, move_buttons=True) DbGUIElement.__init__(self, dbstate.db) self.callman.register_handles({'citation': self.data}) @@ -98,7 +98,7 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): """ Implement base class DbGUIElement method """ - #citation: citation-rebuild closes the editors, so no need to connect + #citation: citation-rebuild closes the editors, so no need to connect # to it self.callman.register_callbacks( {'citation-delete': self.citation_delete, @@ -111,7 +111,7 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): Return the stock-id icon name associated with the display tab """ return 'gramps-source' - + def get_data(self): """ Return the data associated with display tab @@ -126,11 +126,11 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): def add_button_clicked(self, obj): """ - Create a new Citation instance and call the EditCitation editor with - the new citation. - - Called when the Add button is clicked. - If the window already exists (WindowActiveError), we ignore it. + Create a new Citation instance and call the EditCitation editor with + the new citation. + + Called when the Add button is clicked. + If the window already exists (WindowActiveError), we ignore it. This prevents the dialog from coming up twice on the same object. """ try: @@ -163,9 +163,9 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): if isinstance(object, Source): try: from .. import EditCitation - EditCitation(self.dbstate, self.uistate, self.track, - Citation(), object, - callback=self.add_callback, + EditCitation(self.dbstate, self.uistate, self.track, + Citation(), object, + callback=self.add_callback, callertitle=self.callertitle) except WindowActiveError: from ...dialog import WarningDialog @@ -174,8 +174,8 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): elif isinstance(object, Citation): try: from .. import EditCitation - EditCitation(self.dbstate, self.uistate, self.track, - object, callback=self.add_callback, + EditCitation(self.dbstate, self.uistate, self.track, + object, callback=self.add_callback, callertitle=self.callertitle) except WindowActiveError: from ...dialog import WarningDialog @@ -183,7 +183,7 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): self.__blocked_text()) else: raise ValueError("selection must be either source or citation") - + def __blocked_text(self): """ Return the common text used when citation cannot be edited @@ -196,11 +196,11 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): def edit_button_clicked(self, obj): """ - Get the selected Citation instance and call the EditCitation editor - with the citation. - - Called when the Edit button is clicked. - If the window already exists (WindowActiveError), we ignore it. + Get the selected Citation instance and call the EditCitation editor + with the citation. + + Called when the Edit button is clicked. + If the window already exists (WindowActiveError), we ignore it. This prevents the dialog from coming up twice on the same object. """ handle = self.get_selected() @@ -212,7 +212,7 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): callertitle = self.callertitle) except WindowActiveError: pass - + def citation_delete(self, del_citation_handle_list): """ Outside of this tab citation objects have been deleted. Check if tab @@ -227,7 +227,7 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): rebuild = True if rebuild: self.rebuild() - + def citation_update(self, upd_citation_handle_list): """ Outside of this tab citation objects have been updated. Check if tab @@ -247,8 +247,8 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): if isinstance(object, Citation): try: from .. import EditCitation - EditCitation(self.dbstate, self.uistate, self.track, - object, callback=self.add_callback, + EditCitation(self.dbstate, self.uistate, self.track, + object, callback=self.add_callback, callertitle=self.callertitle) except WindowActiveError: from ...dialog import WarningDialog @@ -266,9 +266,9 @@ class CitationEmbedList(EmbeddedList, DbGUIElement): if isinstance(object, Source): try: from .. import EditCitation - EditCitation(self.dbstate, self.uistate, self.track, - Citation(), object, - callback=self.add_callback, + EditCitation(self.dbstate, self.uistate, self.track, + Citation(), object, + callback=self.add_callback, callertitle=self.callertitle) except WindowActiveError: from ...dialog import WarningDialog diff --git a/gramps/gui/editors/displaytabs/citationrefmodel.py b/gramps/gui/editors/displaytabs/citationrefmodel.py index cb7a27e7c..28902b4c5 100644 --- a/gramps/gui/editors/displaytabs/citationrefmodel.py +++ b/gramps/gui/editors/displaytabs/citationrefmodel.py @@ -37,7 +37,7 @@ class CitationRefModel(Gtk.ListStore): Gtk.ListStore.__init__(self, str, str, str, str, bool, str) self.db = db for handle in citation_list: - citation = self.db.get_citation_from_handle(handle) + citation = self.db.get_citation_from_handle(handle) src = self.db.get_source_from_handle(citation.get_reference_handle()) self.append(row=[src.title, src.author, citation.page, citation.gramps_id, citation.get_privacy(), diff --git a/gramps/gui/editors/displaytabs/embeddedlist.py b/gramps/gui/editors/displaytabs/embeddedlist.py index f6ed07320..91e2ab5d0 100644 --- a/gramps/gui/editors/displaytabs/embeddedlist.py +++ b/gramps/gui/editors/displaytabs/embeddedlist.py @@ -54,7 +54,7 @@ from .buttontab import ButtonTab # #---------------------------------------------------------------- TEXT_COL = 0 -MARKUP_COL = 1 +MARKUP_COL = 1 ICON_COL = 2 TEXT_EDIT_COL = 3 @@ -65,22 +65,22 @@ TEXT_EDIT_COL = 3 #------------------------------------------------------------------------- class EmbeddedList(ButtonTab): """ - This class provides the base class for all the list tabs. - + This class provides the base class for all the list tabs. + It maintains a Gtk.TreeView, including the selection and button sensitivity. """ - + _HANDLE_COL = -1 _DND_TYPE = None _DND_EXTRA = None - + def __init__(self, dbstate, uistate, track, name, build_model, share_button=False, move_buttons=False, jump_button=False, top_label=None): """ Create a new list, using the passed build_model to populate the list. """ - ButtonTab.__init__(self, dbstate, uistate, track, name, share_button, + ButtonTab.__init__(self, dbstate, uistate, track, name, share_button, move_buttons, jump_button, top_label) self.changed = False @@ -143,7 +143,7 @@ class EmbeddedList(ButtonTab): If image == False, then only text label with title is shown If image == True, and image is a tuple (stock_id, text), the image of the stock id (eg 'gramps-family') is shown, and the label text - If image is not a tuple, then it should be a stock_id, and the + If image is not a tuple, then it should be a stock_id, and the image is shown, with label the default stock_id label. """ if self.share_btn: @@ -200,13 +200,13 @@ class EmbeddedList(ButtonTab): """ if self._DND_EXTRA: - dnd_types = [self._DND_TYPE, + dnd_types = [self._DND_TYPE, self._DND_EXTRA] else: dnd_types = [self._DND_TYPE] - + #TODO GTK3: wourkaround here for bug https://bugzilla.gnome.org/show_bug.cgi?id=680638 - self.tree.enable_model_drag_dest([], Gdk.DragAction.COPY) + self.tree.enable_model_drag_dest([], Gdk.DragAction.COPY) self.tree.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, [], Gdk.DragAction.COPY) tglist = Gtk.TargetList.new([]) @@ -222,7 +222,7 @@ class EmbeddedList(ButtonTab): if not self.dbstate.db.readonly: self.tree.connect('drag_data_received', self.drag_data_received) self.tree.connect('drag_motion', self.tree_drag_motion) - + def drag_data_get(self, widget, context, sel_data, info, time): """ Provide the drag_data_get function, which passes a tuple consisting of: @@ -261,20 +261,20 @@ class EmbeddedList(ButtonTab): data = pickle.loads(sel_data.get_data()) if isinstance(data, list): data = [pickle.loads(x) for x in data] - else: + else: data = [data] for value in data: (mytype, selfid, obj, row_from) = value # make sure this is the correct DND type for this object if mytype == self._DND_TYPE.drag_type: - + # determine the destination row row = self._find_row(x, y) # if the is same object, we have a move, otherwise, # it is a standard drag-n-drop - + if id(self) == selfid and self.get_selected() is not None: self._move(row_from, row, obj) else: @@ -285,7 +285,7 @@ class EmbeddedList(ButtonTab): def tree_drag_motion(self, *args): """ - On drag motion one wants the list to show as the database + On drag motion one wants the list to show as the database representation so it is clear how save will change the data. """ pass @@ -318,9 +318,9 @@ class EmbeddedList(ButtonTab): del dlist[row_from] dlist.insert(row_to, obj) self.changed = True - + def _move_up(self, row_from, obj, selmethod=None): - """ + """ Move the item a position up in the EmbeddedList. Eg: 0,1,2,3 needs to become 0,2,1,3, here row_from = 2 """ @@ -333,14 +333,14 @@ class EmbeddedList(ButtonTab): self.changed = True self.rebuild() #select the row - path = '%d' % (row_from-1) + path = '%d' % (row_from-1) self.tree.get_selection().select_path(path) # The height/location of Gtk.treecells is calculated in an idle handler # so use idle_add to scroll cell into view. GLib.idle_add(self.tree.scroll_to_cell, path) - + def _move_down(self, row_from, obj, selmethod=None): - """ + """ Move the item a position down in the EmbeddedList. Eg: 0,1,2,3 needs to become 0,2,1,3, here row_from = 1 """ @@ -353,7 +353,7 @@ class EmbeddedList(ButtonTab): self.changed = True self.rebuild() #select the row - path = '%d' % (row_from+1) + path = '%d' % (row_from+1) self.tree.get_selection().select_path(path) GLib.idle_add(self.tree.scroll_to_cell, path) @@ -373,14 +373,14 @@ class EmbeddedList(ButtonTab): ref_list.remove(ref) self.changed = True self.rebuild() - + def up_button_clicked(self, obj): ref = self.get_selected() if ref: pos = self.find_index(ref) if pos > 0 : self._move_up(pos, ref) - + def down_button_clicked(self, obj): ref = self.get_selected() if ref: @@ -396,7 +396,7 @@ class EmbeddedList(ButtonTab): # create the tree, turn on rule hinting and connect the # button press to the double click function. - + self.tree = Gtk.TreeView() self.tree.set_reorderable(True) self.tree.connect('button_press_event', self.double_click) @@ -428,7 +428,7 @@ class EmbeddedList(ButtonTab): 0. Typically, get_data returns the list of associated data. """ return len(self.get_data()) == 0 - + def get_data(self): """ Return the data associated with the list. This is typically @@ -453,7 +453,7 @@ class EmbeddedList(ButtonTab): """ inherit this and set the variables needed for editable columns Variable edit_col_funcs needs to be a dictionary from model col_nr to - function to call for + function to call for Example: self.edit_col_funcs ={1: {'edit_start': self.on_edit_start, 'edited': self.on_edited @@ -465,12 +465,12 @@ class EmbeddedList(ButtonTab): """ Builds the columns and inserts them into the TreeView. Any previous columns exist, they will be in the self.columns array, - and removed. + and removed. """ # remove any existing columns, which would be stored in # self.columns - + list(map(self.tree.remove_column, self.columns)) self.columns = [] self.setup_editable_col() @@ -489,7 +489,7 @@ class EmbeddedList(ButtonTab): col_icon = self._column_names[pair[1]][5] model_col = self._column_names[pair[1]][1] type_col = self._column_names[pair[1]][3] - + if (type_col in [TEXT_COL, MARKUP_COL, TEXT_EDIT_COL]): renderer = Gtk.CellRendererText() renderer.set_property('ellipsize', Pango.EllipsizeMode.END) @@ -499,7 +499,7 @@ class EmbeddedList(ButtonTab): column = Gtk.TreeViewColumn(name, renderer, markup=pair[1]) if not self._column_names[pair[1]][4] == -1: #apply weight attribute - column.add_attribute(renderer, "weight", + column.add_attribute(renderer, "weight", self._column_names[pair[1]][4]) #set up editable if type_col == TEXT_EDIT_COL: @@ -507,7 +507,7 @@ class EmbeddedList(ButtonTab): callbacks = self.edit_col_funcs[model_col] for renderer in column.get_cells(): renderer.set_property('editable', not self.dbstate.db.readonly) - renderer.connect('editing_started', + renderer.connect('editing_started', callbacks['edit_start'], model_col) renderer.connect('edited', callbacks['edited'], model_col) elif self._column_names[pair[1]][3] == ICON_COL: @@ -548,13 +548,13 @@ class EmbeddedList(ButtonTab): elif icon_name == True: icon_name = self.col_icons[col_num] renderer.set_property('icon-name', icon_name) - + def construct_model(self): """ Method that creates the model using the passed build_model parameter """ return self.build_model(self.get_data(), self.dbstate.db) - + def rebuild(self): """ Rebuilds the data in the database by creating a new model, @@ -591,19 +591,19 @@ class EmbeddedList(ButtonTab): if self.tree.get_realized(): GLib.idle_add(self.tree.scroll_to_point, offset.x, offset.y) self.post_rebuild(selectedpath) - + def post_rebuild(self, prebuildpath): """ - Allow post rebuild embeddedlist specific handling. + Allow post rebuild embeddedlist specific handling. @param prebuildpath: path selected before rebuild, None if none @type prebuildpath: tree path """ pass - + def rebuild_callback(self): """ The view must be remade when data changes outside this tab. - Use this method to connect to after a db change. It makes sure the + Use this method to connect to after a db change. It makes sure the data is obtained again from the present object and the db what is not present in the obj, and the view rebuild """ diff --git a/gramps/gui/editors/displaytabs/eventbackreflist.py b/gramps/gui/editors/displaytabs/eventbackreflist.py index 609386425..ee01683be 100644 --- a/gramps/gui/editors/displaytabs/eventbackreflist.py +++ b/gramps/gui/editors/displaytabs/eventbackreflist.py @@ -29,7 +29,7 @@ from .backreflist import BackRefList class EventBackRefList(BackRefList): def __init__(self, dbstate, uistate, track, obj, callback=None): - BackRefList.__init__(self, dbstate, uistate, track, obj, + BackRefList.__init__(self, dbstate, uistate, track, obj, BackRefModel, callback) def get_icon_name(self): diff --git a/gramps/gui/editors/displaytabs/eventembedlist.py b/gramps/gui/editors/displaytabs/eventembedlist.py index e3efb410b..0cf4396db 100644 --- a/gramps/gui/editors/displaytabs/eventembedlist.py +++ b/gramps/gui/editors/displaytabs/eventembedlist.py @@ -55,7 +55,7 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): _DND_TYPE = DdTargets.EVENTREF _DND_EXTRA = DdTargets.EVENT _WORKGROUP = EventRefModel._ROOTINDEX - + _WORKNAME = _("Family") _FATHNAME = _("Father") _MOTHNAME = _("Mother") @@ -95,10 +95,10 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): self._groups = [] self._data = [] DbGUIElement.__init__(self, dbstate.db) - GroupEmbeddedList.__init__(self, dbstate, uistate, track, _('_Events'), - build_model, share_button=True, + GroupEmbeddedList.__init__(self, dbstate, uistate, track, _('_Events'), + build_model, share_button=True, move_buttons=True, **kwargs) - + def _connect_db_signals(self): """ called on init of DbGUIElement, connect to db as required. @@ -114,15 +114,15 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): """ Callback method called when a tracked event changes (description changes, source added, ...) - Note that adding an event + Note that adding an event """ self.rebuild_callback() - + def event_delete(self, obj): """ - Callback method called when a tracked event is deleted. - There are two possibilities: - * a tracked non-workgroup event is deleted, just rebuilding the view + Callback method called when a tracked event is deleted. + There are two possibilities: + * a tracked non-workgroup event is deleted, just rebuilding the view will correct this. * a workgroup event is deleted. The event must be removed from the obj so that no inconsistent data is shown. @@ -188,7 +188,7 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): def column_order(self): """ - The columns to show as a tuple containing + The columns to show as a tuple containing tuples (show/noshow, model column) """ return ((1, 1), # type @@ -249,7 +249,7 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): "or another event reference that is associated with " "the same event is being edited.\n\nTo edit this event " "reference, you need to close the event.") - + def share_button_clicked(self, obj): SelectEvent = SelectorFactory('Event') @@ -288,7 +288,7 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): reference.ref = primary.handle data = self.get_data()[self._WORKGROUP] data.append(reference) - self.callman.register_handles({'event': [primary.handle]}) + self.callman.register_handles({'event': [primary.handle]}) self.changed = True self.rebuild() GLib.idle_add(self.tree.scroll_to_cell, @@ -296,8 +296,8 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): def object_edited(self, ref, event): """ - Called as callback after eventref has been edited. - Note that if the event changes too (so not only the ref data), then + Called as callback after eventref has been edited. + Note that if the event changes too (so not only the ref data), then an event-update signal from the database will also be raised, and the rebuild done here will not be needed. There is no way to avoid this ... """ @@ -366,7 +366,7 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): def editnotworkgroup(self, key): """ Edit non native event in own editor - """ + """ person = self.dbstate.db.get_person_from_handle(key) try: from .. import EditPerson @@ -386,7 +386,7 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): we allow to change the default name like this """ self.dropnotworkgroup(None, None) - + def move_to_work(self, row_from, row_to, obj): """ move from a non workgroup to the workgroup @@ -408,7 +408,7 @@ class EventEmbedList(DbGUIElement, GroupEmbeddedList): def post_rebuild(self, prebuildpath): """ - Allow post rebuild specific handling. + Allow post rebuild specific handling. @param prebuildpath: path selected before rebuild, None if none @type prebuildpath: tree path """ diff --git a/gramps/gui/editors/displaytabs/eventrefmodel.py b/gramps/gui/editors/displaytabs/eventrefmodel.py index a03df98b3..5ceb23017 100644 --- a/gramps/gui/editors/displaytabs/eventrefmodel.py +++ b/gramps/gui/editors/displaytabs/eventrefmodel.py @@ -67,9 +67,9 @@ age_precision = config.get('preferences.age-display-precision') #------------------------------------------------------------------------- class EventRefModel(Gtk.TreeStore): #index of the working group - _ROOTINDEX = 0 + _ROOTINDEX = 0 _GROUPSTRING = _('%(groupname)s - %(groupnumber)d') - + COL_DESCR = (0, str) COL_TYPE = (1, str) COL_GID = (2, str) @@ -83,15 +83,15 @@ class EventRefModel(Gtk.TreeStore): COL_AGE = (10, str) COL_SORTAGE = (11, str) COL_PRIVATE = (12, bool) - - COLS = (COL_DESCR, COL_TYPE, COL_GID, COL_DATE, COL_PLACE, COL_ROLE, + + COLS = (COL_DESCR, COL_TYPE, COL_GID, COL_DATE, COL_PLACE, COL_ROLE, COL_PARTIC, COL_SORTDATE, COL_EVENTREF, COL_FONTWEIGHT, COL_AGE, COL_SORTAGE, COL_PRIVATE) def __init__(self, event_list, db, groups, **kwargs): """ @param event_list: A list of lists, every entry is a group, the entries - in a group are the data that needs to be shown subordinate to the + in a group are the data that needs to be shown subordinate to the group @param db: a database objects that can be used to obtain info @param groups: a list of (key, name) tuples. key is a key for the group @@ -122,10 +122,10 @@ class EventRefModel(Gtk.TreeStore): def row(self, index, eventref, event): return [event.get_description(), str(event.get_type()), - event.get_gramps_id(), - self.column_date(eventref), - self.column_place(eventref), - self.column_role(eventref), + event.get_gramps_id(), + self.column_date(eventref), + self.column_place(eventref), + self.column_role(eventref), self.column_participant(eventref), self.column_sort_date(eventref), (index, eventref), @@ -134,7 +134,7 @@ class EventRefModel(Gtk.TreeStore): self.column_sort_age(event), eventref.get_privacy(), ] - + def colweight(self, index): return WEIGHT_NORMAL diff --git a/gramps/gui/editors/displaytabs/familyattrembedlist.py b/gramps/gui/editors/displaytabs/familyattrembedlist.py index bffb723dd..86a5d8c5b 100644 --- a/gramps/gui/editors/displaytabs/familyattrembedlist.py +++ b/gramps/gui/editors/displaytabs/familyattrembedlist.py @@ -27,7 +27,7 @@ from .attrembedlist import AttrEmbedList #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class FamilyAttrEmbedList(AttrEmbedList): @@ -40,4 +40,4 @@ class FamilyAttrEmbedList(AttrEmbedList): return EditAttribute def get_user_values(self): - return self.dbstate.db.get_family_attribute_types() + return self.dbstate.db.get_family_attribute_types() diff --git a/gramps/gui/editors/displaytabs/familyldsembedlist.py b/gramps/gui/editors/displaytabs/familyldsembedlist.py index 8bde5a2e5..397282dc0 100644 --- a/gramps/gui/editors/displaytabs/familyldsembedlist.py +++ b/gramps/gui/editors/displaytabs/familyldsembedlist.py @@ -37,7 +37,7 @@ from gramps.gen.lib import LdsOrd #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class FamilyLdsEmbedList(LdsEmbedList): @@ -55,14 +55,14 @@ class FamilyLdsEmbedList(LdsEmbedList): (_('Place'), 3, 100, TEXT_COL, -1, None), (_('Private'), 5, 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, data): LdsEmbedList.__init__(self, dbstate, uistate, track, data) def get_editor(self): from .. import EditFamilyLdsOrd return EditFamilyLdsOrd - + def new_data(self): lds = LdsOrd() lds.set_type(LdsOrd.SEAL_TO_SPOUSE) diff --git a/gramps/gui/editors/displaytabs/gallerytab.py b/gramps/gui/editors/displaytabs/gallerytab.py index bd9186f31..269a12605 100644 --- a/gramps/gui/editors/displaytabs/gallerytab.py +++ b/gramps/gui/editors/displaytabs/gallerytab.py @@ -64,7 +64,7 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- def make_launcher(path): @@ -86,7 +86,7 @@ class GalleryTab(ButtonTab, DbGUIElement): DbGUIElement.__init__(self, dbstate.db) self.track_ref_for_deletion("iconlist") self.media_list = media_list - self.callman.register_handles({'media': [mref.ref for mref + self.callman.register_handles({'media': [mref.ref for mref in self.media_list]}) self.update = update @@ -94,7 +94,7 @@ class GalleryTab(ButtonTab, DbGUIElement): self.rebuild() self.show_all() - + def _connect_db_signals(self): """ Implement base class DbGUIElement method @@ -108,7 +108,7 @@ class GalleryTab(ButtonTab, DbGUIElement): def double_click(self, obj, event): """ - Handle the button press event: double click or right click on iconlist. + Handle the button press event: double click or right click on iconlist. If the double click occurs, the Edit button handler is called. """ if event.type == Gdk.EventType._2BUTTON_PRESS and event.button == 1: @@ -151,7 +151,7 @@ class GalleryTab(ButtonTab, DbGUIElement): item = Gtk.SeparatorMenuItem() item.show() self.menu.append(item) - + item = Gtk.MenuItem(_('Make Active Media')) item.connect('activate', lambda obj: self.uistate.set_active(ref_obj.handle, "Media")) item.show() @@ -159,7 +159,7 @@ class GalleryTab(ButtonTab, DbGUIElement): item = Gtk.SeparatorMenuItem() item.show() self.menu.append(item) - + for (needs_write_access, image, title, func) in itemlist: if image: item = Gtk.ImageMenuItem() @@ -173,7 +173,7 @@ class GalleryTab(ButtonTab, DbGUIElement): item.show() self.menu.append(item) self.menu.popup(None, None, None, None, event.button, event.time) - + def get_icon_name(self): return 'gramps-media' @@ -181,7 +181,7 @@ class GalleryTab(ButtonTab, DbGUIElement): return len(self.media_list)==0 def _build_icon_model(self): - self.iconmodel = Gtk.ListStore(GdkPixbuf.Pixbuf, GObject.TYPE_STRING, + self.iconmodel = Gtk.ListStore(GdkPixbuf.Pixbuf, GObject.TYPE_STRING, object) self.track_ref_for_deletion("iconmodel") @@ -192,16 +192,16 @@ class GalleryTab(ButtonTab, DbGUIElement): def build_interface(self): """Setup the GUI. - + It includes an IconView placed inside of a ScrolledWindow. - + """ # create the model used with the icon view self._build_icon_model() # pixels to pad the image padding = 6 - + # build the icon view self.iconlist.set_pixbuf_column(0) self.iconlist.set_item_width(int(THUMBSCALE) + padding * 2) @@ -212,23 +212,23 @@ class GalleryTab(ButtonTab, DbGUIElement): text_renderer.set_property('alignment', Pango.Alignment.CENTER) self.iconlist.pack_end(text_renderer, True) self.iconlist.add_attribute(text_renderer, "text", 1) - + # set basic properties of the icon view self.iconlist.set_margin(padding) self.iconlist.set_column_spacing(padding) self.iconlist.set_reorderable(True) self.iconlist.set_selection_mode(Gtk.SelectionMode.SINGLE) - + # connect the signals self.__id_connect_sel = self.iconlist.connect('selection-changed', self._selection_changed) self.iconlist.connect('button_press_event', self.double_click) self.iconlist.connect('key_press_event', self.key_pressed) self._connect_icon_model() - + # create the scrolled window scroll = Gtk.ScrolledWindow() scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) - + # put everything together scroll.add(self.iconlist) self.pack_end(scroll, True, True, 0) @@ -264,8 +264,8 @@ class GalleryTab(ButtonTab, DbGUIElement): _('Non existing media found in the Gallery')) else : pixbuf = get_thumbnail_image( - media_path_full(self.dbstate.db, - obj.get_path()), + media_path_full(self.dbstate.db, + obj.get_path()), obj.get_mime_type(), ref.get_rectangle()) self.iconmodel.append(row=[pixbuf, obj.get_description(), ref]) @@ -274,7 +274,7 @@ class GalleryTab(ButtonTab, DbGUIElement): self._selection_changed() if self.update: self.update() - + def get_selected(self): node = self.iconlist.get_selected_items() if len(node) > 0: @@ -285,7 +285,7 @@ class GalleryTab(ButtonTab, DbGUIElement): def add_button_clicked(self, obj): try: from .. import EditMediaRef - EditMediaRef(self.dbstate, self.uistate, self.track, + EditMediaRef(self.dbstate, self.uistate, self.track, MediaObject(), MediaRef(), self.add_callback) except WindowActiveError: @@ -318,10 +318,10 @@ class GalleryTab(ButtonTab, DbGUIElement): def share_button_clicked(self, obj): """ - Function called when the Share button is clicked. - + Function called when the Share button is clicked. + This function should be overridden by the derived class. - + """ SelectObject = SelectorFactory('MediaObject') @@ -331,7 +331,7 @@ class GalleryTab(ButtonTab, DbGUIElement): sref = MediaRef() try: from .. import EditMediaRef - EditMediaRef(self.dbstate, self.uistate, self.track, + EditMediaRef(self.dbstate, self.uistate, self.track, src, sref, self.add_callback) except WindowActiveError: from ...dialog import WarningDialog @@ -351,7 +351,7 @@ class GalleryTab(ButtonTab, DbGUIElement): ref.get_reference_handle()) try: from .. import EditMediaRef - EditMediaRef(self.dbstate, self.uistate, self.track, + EditMediaRef(self.dbstate, self.uistate, self.track, obj, ref, self.edit_callback) except WindowActiveError: from ...dialog import WarningDialog @@ -381,7 +381,7 @@ class GalleryTab(ButtonTab, DbGUIElement): pos = ref_handles.index(handle) except ValueError : break - + if pos is not None: #oeps, we need to remove this reference, and rebuild tab del self.media_list[pos] @@ -427,7 +427,7 @@ class GalleryTab(ButtonTab, DbGUIElement): self.iconlist.connect('drag_data_get', self.drag_data_get) if not self.dbstate.db.readonly: self.iconlist.connect('drag_data_received', self.drag_data_received) - + def drag_data_get(self, widget, context, sel_data, info, time): """ Provide the drag_data_get function, which passes a tuple consisting of: @@ -452,9 +452,9 @@ class GalleryTab(ButtonTab, DbGUIElement): if not obj: return - + # pickle the data, and build the tuple to be passed - value = (self._DND_TYPE.drag_type, id(self), obj, + value = (self._DND_TYPE.drag_type, id(self), obj, self.find_index(obj)) data = pickle.dumps(value) @@ -476,7 +476,7 @@ class GalleryTab(ButtonTab, DbGUIElement): # make sure this is the correct DND type for this object if mytype == self._DND_TYPE.drag_type: - + # determine the destination row data = self.iconlist.get_dest_item_at_pos(x, y) if data: @@ -490,10 +490,10 @@ class GalleryTab(ButtonTab, DbGUIElement): row = min(row+1, len(self.get_data())) else: row = len(self.get_data()) - + # if the is same object, we have a move, otherwise, # it is a standard drag-n-drop - + if id(self) == selfid: self._move(row_from, row, obj) else: diff --git a/gramps/gui/editors/displaytabs/grampstab.py b/gramps/gui/editors/displaytabs/grampstab.py index fafe0804a..d7cb152f2 100644 --- a/gramps/gui/editors/displaytabs/grampstab.py +++ b/gramps/gui/editors/displaytabs/grampstab.py @@ -40,9 +40,9 @@ _RIGHT = Gdk.keyval_from_name("Right") class GrampsTab(Gtk.Box): """ This class provides the base level class for 'tabs', which are used to - fill in notebook tabs for GRAMPS edit dialogs. - - Each tab returns a gtk container widget which can be inserted into a + fill in notebook tabs for GRAMPS edit dialogs. + + Each tab returns a gtk container widget which can be inserted into a Gtk.Notebook by the instantiating object. All tab classes should inherit from GrampsTab @@ -72,10 +72,10 @@ class GrampsTab(Gtk.Box): self.track = track self.changed = False self.__refs_for_deletion = [] - + # save name used for notebook label, and build the widget used # for the label - + self.tab_name = name self.track_ref_for_deletion("tab_name") self.label_container = self.build_label_widget() @@ -111,7 +111,7 @@ class GrampsTab(Gtk.Box): name = icon[1] else: name = icon - + self.tab_image = Gtk.Image.new_from_icon_name(name, Gtk.IconSize.MENU) self.track_ref_for_deletion("tab_image") self.label = Gtk.Label(label=self.tab_name) @@ -144,7 +144,7 @@ class GrampsTab(Gtk.Box): def key_pressed(self, obj, event): """ - Handles the key being pressed. + Handles the key being pressed. The inheriting object must contain a widget that connects at mimimum to this method, eg an eventbox, tree, ... """ @@ -212,6 +212,6 @@ class GrampsTab(Gtk.Box): Remove any instance variables from scope which point to non-glade GTK objects so that the class can be garbage collected. """ - while len(self.__refs_for_deletion): + while len(self.__refs_for_deletion): attr = self.__refs_for_deletion.pop() delattr(self, attr) diff --git a/gramps/gui/editors/displaytabs/groupembeddedlist.py b/gramps/gui/editors/displaytabs/groupembeddedlist.py index b9d451f3f..245531dd0 100644 --- a/gramps/gui/editors/displaytabs/groupembeddedlist.py +++ b/gramps/gui/editors/displaytabs/groupembeddedlist.py @@ -52,13 +52,13 @@ from .embeddedlist import EmbeddedList, TEXT_COL, MARKUP_COL, ICON_COL class GroupEmbeddedList(EmbeddedList): """ This class provides the base class for all the list tabs that show - grouped data. - + grouped data. + It maintains a Gtk.TreeView, including the selection and button sensitivity. """ - + _WORKGROUP = 0 - + def __init__(self, dbstate, uistate, track, name, build_model, share_button=False, move_buttons=False, jump_button=False, **kwargs): """ @@ -72,14 +72,14 @@ class GroupEmbeddedList(EmbeddedList): for col in self.columns[1:]: col.connect('clicked', self.col_click) self.dbsort = True - + def construct_model(self): """ Method that creates the model using the passed build_model parameter Overwrites the EmbeddedList calling sequence by adding the different groups """ - return self.build_model(self.get_data(), self.dbstate.db, + return self.build_model(self.get_data(), self.dbstate.db, self.groups(), **self.kwargs) def groups(self): @@ -95,7 +95,7 @@ class GroupEmbeddedList(EmbeddedList): self.columns[0].set_sort_order(Gtk.SortType.ASCENDING) self.rebuild() self.dbsort = True - + def col_click(self, obj): self.dbsort = False @@ -146,7 +146,7 @@ class GroupEmbeddedList(EmbeddedList): return # pickle the data, and build the tuple to be passed - value = (self._DND_TYPE.drag_type, id(self), obj[1], + value = (self._DND_TYPE.drag_type, id(self), obj[1], self.find_index(obj)) data = pickle.dumps(value) @@ -171,13 +171,13 @@ class GroupEmbeddedList(EmbeddedList): # make sure this is the correct DND type for this object if mytype == self._DND_TYPE.drag_type: - + # determine the destination row row = self._find_row(x, y) # if this is same object, we have a move, otherwise, # it is a standard drag-n-drop - + if id(self) == selfid and self.get_selected() is not None: self._move(row_from, row, obj) else: @@ -188,7 +188,7 @@ class GroupEmbeddedList(EmbeddedList): def tree_drag_motion(self, *args): """ - On drag motion one wants the list to show as the database + On drag motion one wants the list to show as the database representation so it is clear how save will change the data """ if not self.dbsort: @@ -203,7 +203,7 @@ class GroupEmbeddedList(EmbeddedList): groupindex = None index = None for groupindex, group in enumerate(data): - try: + try: index = group.index(obj[1]) break except ValueError: @@ -212,7 +212,7 @@ class GroupEmbeddedList(EmbeddedList): def _find_row(self, x, y): """ - Return a path as [groupindex, index] of the row on x,y. + Return a path as [groupindex, index] of the row on x,y. If no row, then a new line in the working group is returned """ dest = self.tree.get_dest_row_at_pos(x, y) @@ -292,7 +292,7 @@ class GroupEmbeddedList(EmbeddedList): pass def _move_up(self, row_from, obj, selmethod=None): - """ + """ Move the item a position up in the EmbeddedList. Eg: 0,1,2,3 needs to become 0,2,1,3, here row_from = 2 """ @@ -317,15 +317,15 @@ class GroupEmbeddedList(EmbeddedList): move up outside of workgroup """ pass - + def _move_up_group(self, groupindex): """ move up pressed on the group """ pass - + def _move_down(self, row_from, obj, selmethod=None): - """ + """ Move the item a position down in the EmbeddedList. Eg: 0,1,2,3 needs to become 0,2,1,3, here row_from = 1 """ @@ -376,7 +376,7 @@ class GroupEmbeddedList(EmbeddedList): self.rebuild() else: self.del_notwork(ref) - + def del_notwork(self, ref): """ delete of ref asked that is not part of workgroup @@ -391,7 +391,7 @@ class GroupEmbeddedList(EmbeddedList): self._move_up(pos, ref[1]) elif ref and ref[1] is None: self._move_up_group(ref[0]) - + def down_button_clicked(self, obj): ref = self.get_selected() if ref and ref[1] is not None: diff --git a/gramps/gui/editors/displaytabs/ldsembedlist.py b/gramps/gui/editors/displaytabs/ldsembedlist.py index 231bbc66f..02bd6e306 100644 --- a/gramps/gui/editors/displaytabs/ldsembedlist.py +++ b/gramps/gui/editors/displaytabs/ldsembedlist.py @@ -39,7 +39,7 @@ from .embeddedlist import EmbeddedList, TEXT_COL, MARKUP_COL, ICON_COL #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class LdsEmbedList(EmbeddedList): @@ -58,17 +58,17 @@ class LdsEmbedList(EmbeddedList): #index = column in model. Value = # (name, sortcol in model, width, markup/text, weigth_col _column_names = [ - (_('Type'), 0, 150, TEXT_COL, -1, None), - (_('Date'), 1, 150, MARKUP_COL, -1, None), - (_('Status'), 3, 75, TEXT_COL, -1, None), - (_('Temple'), 2, 200, TEXT_COL, -1, None), + (_('Type'), 0, 150, TEXT_COL, -1, None), + (_('Date'), 1, 150, MARKUP_COL, -1, None), + (_('Status'), 3, 75, TEXT_COL, -1, None), + (_('Temple'), 2, 200, TEXT_COL, -1, None), (_('Place'), 3, 100, TEXT_COL, -1, None), (_('Private'), 5, 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, data): self.data = data - EmbeddedList.__init__(self, dbstate, uistate, track, _('_LDS'), + EmbeddedList.__init__(self, dbstate, uistate, track, _('_LDS'), LdsModel, move_buttons=True) def get_editor(self): @@ -77,7 +77,7 @@ class LdsEmbedList(EmbeddedList): def new_data(self): return LdsOrd() - + def get_data(self): return self.data @@ -86,7 +86,7 @@ class LdsEmbedList(EmbeddedList): def add_button_clicked(self, obj): try: - self.get_editor()(self.dbstate, self.uistate, self.track, + self.get_editor()(self.dbstate, self.uistate, self.track, self.new_data(), self.add_callback) except WindowActiveError: pass @@ -101,7 +101,7 @@ class LdsEmbedList(EmbeddedList): lds = self.get_selected() if lds: try: - self.get_editor()(self.dbstate, self.uistate, self.track, + self.get_editor()(self.dbstate, self.uistate, self.track, lds, self.edit_callback) except WindowActiveError: pass diff --git a/gramps/gui/editors/displaytabs/ldsmodel.py b/gramps/gui/editors/displaytabs/ldsmodel.py index f7f49fad7..a3923febb 100644 --- a/gramps/gui/editors/displaytabs/ldsmodel.py +++ b/gramps/gui/editors/displaytabs/ldsmodel.py @@ -54,11 +54,11 @@ class LdsModel(Gtk.ListStore): for lds_ord in lds_list: self.append(row=[ - lds_ord.type2str(), - get_date(lds_ord), - lds_ord.status2str(), + lds_ord.type2str(), + get_date(lds_ord), + lds_ord.status2str(), TEMPLES.name(lds_ord.get_temple()), place_displayer.display_event(db, lds_ord), lds_ord.get_privacy(), - lds_ord, + lds_ord, ]) diff --git a/gramps/gui/editors/displaytabs/locationembedlist.py b/gramps/gui/editors/displaytabs/locationembedlist.py index d5ea9d9ae..6095b9c9f 100644 --- a/gramps/gui/editors/displaytabs/locationembedlist.py +++ b/gramps/gui/editors/displaytabs/locationembedlist.py @@ -40,29 +40,29 @@ from .embeddedlist import EmbeddedList, TEXT_COL, MARKUP_COL, ICON_COL #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class LocationEmbedList(EmbeddedList): _HANDLE_COL = 6 _DND_TYPE = DdTargets.LOCATION - + #index = column in model. Value = # (name, sortcol in model, width, markup/text, weigth_col _column_names = [ - (_('Street'), 0, 150, TEXT_COL, -1, None), - (_('Locality'), 1, 100, TEXT_COL, -1, None), - (_('City'), 2, 100, TEXT_COL, -1, None), - (_('County'), 3, 100, TEXT_COL, -1, None), - (_('State'), 4, 100, TEXT_COL, -1, None), - (_('Country'), 5, 75, TEXT_COL, -1, None), + (_('Street'), 0, 150, TEXT_COL, -1, None), + (_('Locality'), 1, 100, TEXT_COL, -1, None), + (_('City'), 2, 100, TEXT_COL, -1, None), + (_('County'), 3, 100, TEXT_COL, -1, None), + (_('State'), 4, 100, TEXT_COL, -1, None), + (_('Country'), 5, 75, TEXT_COL, -1, None), ] - + def __init__(self, dbstate, uistate, track, data): self.data = data - EmbeddedList.__init__(self, dbstate, uistate, track, - _('Alternate _Locations'), LocationModel, + EmbeddedList.__init__(self, dbstate, uistate, track, + _('Alternate _Locations'), LocationModel, move_buttons=True) def get_data(self): @@ -75,7 +75,7 @@ class LocationEmbedList(EmbeddedList): loc = Location() try: from .. import EditLocation - EditLocation(self.dbstate, self.uistate, self.track, + EditLocation(self.dbstate, self.uistate, self.track, loc, self.add_callback) except WindowActiveError: pass @@ -91,7 +91,7 @@ class LocationEmbedList(EmbeddedList): if loc: try: from .. import EditLocation - EditLocation(self.dbstate, self.uistate, self.track, + EditLocation(self.dbstate, self.uistate, self.track, loc, self.edit_callback) except WindowActiveError: pass diff --git a/gramps/gui/editors/displaytabs/locationmodel.py b/gramps/gui/editors/displaytabs/locationmodel.py index 26dc5d5a2..0d37f5c07 100644 --- a/gramps/gui/editors/displaytabs/locationmodel.py +++ b/gramps/gui/editors/displaytabs/locationmodel.py @@ -43,5 +43,5 @@ class LocationModel(Gtk.ListStore): Gtk.ListStore.__init__(self, str, str, str, str, str, str, object) self.db = db for obj in obj_list: - self.append(row=[obj.street, obj.locality, obj.city, obj.county, + self.append(row=[obj.street, obj.locality, obj.city, obj.county, obj.state, obj.country, obj, ]) diff --git a/gramps/gui/editors/displaytabs/mediabackreflist.py b/gramps/gui/editors/displaytabs/mediabackreflist.py index a97a34ab7..47c7f5601 100644 --- a/gramps/gui/editors/displaytabs/mediabackreflist.py +++ b/gramps/gui/editors/displaytabs/mediabackreflist.py @@ -29,7 +29,7 @@ from .backreflist import BackRefList class MediaBackRefList(BackRefList): def __init__(self, dbstate, uistate, track, obj, callback=None): - BackRefList.__init__(self, dbstate, uistate, track, obj, + BackRefList.__init__(self, dbstate, uistate, track, obj, BackRefModel, callback=callback) def get_icon_name(self): diff --git a/gramps/gui/editors/displaytabs/nameembedlist.py b/gramps/gui/editors/displaytabs/nameembedlist.py index 9b403ab55..32af04112 100644 --- a/gramps/gui/editors/displaytabs/nameembedlist.py +++ b/gramps/gui/editors/displaytabs/nameembedlist.py @@ -50,7 +50,7 @@ from .groupembeddedlist import GroupEmbeddedList #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class NameEmbedList(GroupEmbeddedList): @@ -70,8 +70,8 @@ class NameEmbedList(GroupEmbeddedList): #index = column in model. Value = # (name, sortcol in model, width, markup/text, weigth_col _column_names = [ - (_('Name'), -1, 250, TEXT_COL, NameModel.COL_FONTWEIGHT[0], None), - (_('Type'), NameModel.COL_TYPE[0], 100, TEXT_COL, -1, None), + (_('Name'), -1, 250, TEXT_COL, NameModel.COL_FONTWEIGHT[0], None), + (_('Type'), NameModel.COL_TYPE[0], 100, TEXT_COL, -1, None), None, None, (_('Group As'), NameModel.COL_GROUPAS[0],100, TEXT_COL, -1, None), @@ -79,15 +79,15 @@ class NameEmbedList(GroupEmbeddedList): (_('Notes Preview'), NameModel.COL_NOTEPREVIEW[0], 250, TEXT_COL, -1, None), (_('Private'), NameModel.COL_PRIVATE[0], 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, data, person, callback): """callback is the function to call when preferred name changes on the namelist """ self.data = data self.person = person self.callback = callback - - GroupEmbeddedList.__init__(self, dbstate, uistate, track, _('_Names'), + + GroupEmbeddedList.__init__(self, dbstate, uistate, track, _('_Names'), NameModel, move_buttons=True) self.tree.expand_all() @@ -100,7 +100,7 @@ class NameEmbedList(GroupEmbeddedList): self.data = None def get_data(self): - return ([self.person.get_primary_name()], + return ([self.person.get_primary_name()], self.data) def groups(self): @@ -111,7 +111,7 @@ class NameEmbedList(GroupEmbeddedList): def column_order(self): """ - The columns to show as a tuple of tuples containing + The columns to show as a tuple of tuples containing tuples (show/noshow, model column) """ return ((1, 0), (1, 7), (1, 1), (1, 4), (1, 5), (1, 6)) @@ -134,7 +134,7 @@ class NameEmbedList(GroupEmbeddedList): name = self.get_selected() if name and name[1]: self.set_default_name(name[1]) - + def set_default_name(self, name): pname = self.person.get_primary_name() self.person.set_primary_name(name) @@ -160,7 +160,7 @@ class NameEmbedList(GroupEmbeddedList): name.set_primary_surname(0) try: from .. import EditName - EditName(self.dbstate, self.uistate, self.track, + EditName(self.dbstate, self.uistate, self.track, name, self.add_callback) except WindowActiveError: pass @@ -178,10 +178,10 @@ class NameEmbedList(GroupEmbeddedList): try: from .. import EditName if name[0] == NameModel.ALTINDEX: - EditName(self.dbstate, self.uistate, self.track, + EditName(self.dbstate, self.uistate, self.track, name[1], self.edit_callback) elif name[0] == NameModel.DEFINDEX: - EditName(self.dbstate, self.uistate, self.track, + EditName(self.dbstate, self.uistate, self.track, name[1], self.editdef_callback) except WindowActiveError: pass @@ -214,7 +214,7 @@ class NameEmbedList(GroupEmbeddedList): def post_rebuild(self, prebuildpath): """ - Allow post rebuild specific handling. + Allow post rebuild specific handling. @param prebuildpath: path selected before rebuild, None if none @type prebuildpath: tree path """ diff --git a/gramps/gui/editors/displaytabs/namemodel.py b/gramps/gui/editors/displaytabs/namemodel.py index 63c6b51b9..ee3d66170 100644 --- a/gramps/gui/editors/displaytabs/namemodel.py +++ b/gramps/gui/editors/displaytabs/namemodel.py @@ -62,9 +62,9 @@ class NameModel(Gtk.TreeStore): DEFNAME = _('Preferred name') ALTINDEX = 1 ALTNAME = _('Alternative names') - + _GROUPSTRING = _('%(groupname)s - %(groupnumber)d') - + COL_NAME = (0, str) COL_TYPE = (1, str) COL_DATA = (2, object) @@ -73,14 +73,14 @@ class NameModel(Gtk.TreeStore): COL_HASSOURCE = (5, str) COL_NOTEPREVIEW = (6, str) COL_PRIVATE = (7, bool) - + COLS = (COL_NAME, COL_TYPE, COL_DATA, COL_FONTWEIGHT, COL_GROUPAS, COL_HASSOURCE, COL_NOTEPREVIEW, COL_PRIVATE) def __init__(self, obj_list, db, groups): """ @param obj_list: A list of lists, every entry is a group, the entries - in a group are the data that needs to be shown subordinate to the + in a group are the data that needs to be shown subordinate to the group @param db: a database objects that can be used to obtain info @param groups: a list of (key, name) tuples. key is a key for the group @@ -101,12 +101,12 @@ class NameModel(Gtk.TreeStore): def row(self, index, name): """ - Returns the row of the model in group index, and name as a + Returns the row of the model in group index, and name as a list """ - return [name_displayer.display_name(name), + return [name_displayer.display_name(name), str(name.get_type()), - (index, name), + (index, name), self.colweight(index), name.get_group_as(), self.hassource(name), @@ -124,14 +124,14 @@ class NameModel(Gtk.TreeStore): return self.DEFNAME return self._GROUPSTRING % {'groupname': self.ALTNAME, 'groupnumber': length} - + def update_defname(self, defname): """ callback if change to the preferred name happens """ #default name is path (0,0) self.remove(self.get_iter((self.DEFINDEX, 0))) - self.insert(self.get_iter(self.DEFINDEX), 0, + self.insert(self.get_iter(self.DEFINDEX), 0, row=self.row(self.DEFINDEX, defname)) def hassource(self, name): diff --git a/gramps/gui/editors/displaytabs/notebackreflist.py b/gramps/gui/editors/displaytabs/notebackreflist.py index e57816a74..f0897c0aa 100644 --- a/gramps/gui/editors/displaytabs/notebackreflist.py +++ b/gramps/gui/editors/displaytabs/notebackreflist.py @@ -30,7 +30,7 @@ from .backreflist import BackRefList class NoteBackRefList(BackRefList): def __init__(self, dbstate, uistate, track, obj, callback=None): - BackRefList.__init__(self, dbstate, uistate, track, obj, + BackRefList.__init__(self, dbstate, uistate, track, obj, BackRefModel, callback=callback) def get_icon_name(self): diff --git a/gramps/gui/editors/displaytabs/notemodel.py b/gramps/gui/editors/displaytabs/notemodel.py index 7ea90753a..ae12ef367 100644 --- a/gramps/gui/editors/displaytabs/notemodel.py +++ b/gramps/gui/editors/displaytabs/notemodel.py @@ -41,8 +41,8 @@ class NoteModel(Gtk.ListStore): if len(text) > 80: text = text[:80]+"..." self.append(row=[ - str(note.get_type()), - text, + str(note.get_type()), + text, note.get_privacy(), - handle, + handle, ]) diff --git a/gramps/gui/editors/displaytabs/notetab.py b/gramps/gui/editors/displaytabs/notetab.py index 93ef36315..d171fc6cc 100644 --- a/gramps/gui/editors/displaytabs/notetab.py +++ b/gramps/gui/editors/displaytabs/notetab.py @@ -54,8 +54,8 @@ from ...ddtargets import DdTargets #------------------------------------------------------------------------- class NoteTab(EmbeddedList, DbGUIElement): """ - Note List display tab for edit dialogs. - + Note List display tab for edit dialogs. + Derives from the EmbeddedList class. """ @@ -79,13 +79,13 @@ class NoteTab(EmbeddedList, DbGUIElement): (_('Private'), 2, 30, ICON_COL, -1, 'gramps-lock') ] - def __init__(self, dbstate, uistate, track, data, callertitle=None, + def __init__(self, dbstate, uistate, track, data, callertitle=None, notetype=None): self.data = data self.callertitle = callertitle self.notetype = notetype - EmbeddedList.__init__(self, dbstate, uistate, track, - _("_Notes"), NoteModel, share_button=True, + EmbeddedList.__init__(self, dbstate, uistate, track, + _("_Notes"), NoteModel, share_button=True, move_buttons=True) DbGUIElement.__init__(self, dbstate.db) self.callman.register_handles({'note': self.data}) @@ -121,11 +121,11 @@ class NoteTab(EmbeddedList, DbGUIElement): def add_button_clicked(self, obj): """ - Create a new Note instance and call the EditNote editor with the new - note. - - Called when the Add button is clicked. - If the window already exists (WindowActiveError), we ignore it. + Create a new Note instance and call the EditNote editor with the new + note. + + Called when the Add button is clicked. + If the window already exists (WindowActiveError), we ignore it. This prevents the dialog from coming up twice on the same object. """ note = Note() @@ -133,7 +133,7 @@ class NoteTab(EmbeddedList, DbGUIElement): note.set_type(self.notetype) try: from .. import EditNote - EditNote(self.dbstate, self.uistate, self.track, + EditNote(self.dbstate, self.uistate, self.track, note, self.add_callback, self.callertitle, extratype = [self.notetype]) except WindowActiveError: @@ -152,11 +152,11 @@ class NoteTab(EmbeddedList, DbGUIElement): def edit_button_clicked(self, obj): """ - Get the selected Note instance and call the EditNote editor with the - note. - - Called when the Edit button is clicked. - If the window already exists (WindowActiveError), we ignore it. + Get the selected Note instance and call the EditNote editor with the + note. + + Called when the Edit button is clicked. + If the window already exists (WindowActiveError), we ignore it. This prevents the dialog from coming up twice on the same object. """ handle = self.get_selected() @@ -169,7 +169,7 @@ class NoteTab(EmbeddedList, DbGUIElement): extratype = [self.notetype] ) except WindowActiveError: pass - + def share_button_clicked(self, obj): SelectNote = SelectorFactory('Note') @@ -177,13 +177,13 @@ class NoteTab(EmbeddedList, DbGUIElement): note = sel.run() if note: self.add_callback(note.handle) - + def get_icon_name(self): """ Return the stock-id icon name associated with the display tab """ return 'gramps-notes' - + def note_delete(self, del_note_handle_list): """ Outside of this tab note objects have been deleted. Check if tab @@ -198,7 +198,7 @@ class NoteTab(EmbeddedList, DbGUIElement): rebuild = True if rebuild: self.rebuild() - + def note_update(self, upd_note_handle_list): """ Outside of this tab note objects have been updated. Check if tab diff --git a/gramps/gui/editors/displaytabs/personbackreflist.py b/gramps/gui/editors/displaytabs/personbackreflist.py index 1a0845878..7db31d184 100644 --- a/gramps/gui/editors/displaytabs/personbackreflist.py +++ b/gramps/gui/editors/displaytabs/personbackreflist.py @@ -29,7 +29,7 @@ from .backreflist import BackRefList class PersonBackRefList(BackRefList): def __init__(self, dbstate, uistate, track, obj, callback=None): - BackRefList.__init__(self, dbstate, uistate, track, obj, + BackRefList.__init__(self, dbstate, uistate, track, obj, BackRefModel, callback=callback) def get_icon_name(self): diff --git a/gramps/gui/editors/displaytabs/personeventembedlist.py b/gramps/gui/editors/displaytabs/personeventembedlist.py index 4aebc24a3..798c3a248 100644 --- a/gramps/gui/editors/displaytabs/personeventembedlist.py +++ b/gramps/gui/editors/displaytabs/personeventembedlist.py @@ -46,12 +46,12 @@ from gramps.gen.errors import WindowActiveError # #------------------------------------------------------------------------- class PersonEventEmbedList(EventEmbedList): - + _WORKNAME = _("Personal") #_FAMNAME = _("With %(namepartner)s (%(famid)s)") _FAMNAME = _("Family") _UNKNOWNNAME = _("") - + _MSG = { 'add' : _('Add a new personal event'), 'del' : _('Remove the selected personal event'), @@ -91,7 +91,7 @@ class PersonEventEmbedList(EventEmbedList): self._groups.append((family_handle, self._FAMNAME, groupname)) self.changed = False - + return self._data def default_role(self): diff --git a/gramps/gui/editors/displaytabs/personrefembedlist.py b/gramps/gui/editors/displaytabs/personrefembedlist.py index 85257e327..abec0a020 100644 --- a/gramps/gui/editors/displaytabs/personrefembedlist.py +++ b/gramps/gui/editors/displaytabs/personrefembedlist.py @@ -41,7 +41,7 @@ from .embeddedlist import EmbeddedList, TEXT_COL, MARKUP_COL, ICON_COL #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class PersonRefEmbedList(EmbeddedList): @@ -66,11 +66,11 @@ class PersonRefEmbedList(EmbeddedList): (_('Association'), 2, 100, TEXT_COL, -1, None), (_('Private'), 3, 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, data): self.data = data - EmbeddedList.__init__(self, dbstate, uistate, track, - _('_Associations'), PersonRefModel, + EmbeddedList.__init__(self, dbstate, uistate, track, + _('_Associations'), PersonRefModel, move_buttons=True) def get_ref_editor(self): diff --git a/gramps/gui/editors/displaytabs/personrefmodel.py b/gramps/gui/editors/displaytabs/personrefmodel.py index d70fd5a39..07a7ec4c4 100644 --- a/gramps/gui/editors/displaytabs/personrefmodel.py +++ b/gramps/gui/editors/displaytabs/personrefmodel.py @@ -45,7 +45,7 @@ class PersonRefModel(Gtk.ListStore): for obj in obj_list: p = self.db.get_person_from_handle(obj.ref) if p: - data = [name_displayer.display(p), p.gramps_id, obj.rel, + data = [name_displayer.display(p), p.gramps_id, obj.rel, obj.get_privacy(), obj] else: data = ['unknown','unknown', obj.rel, obj.get_privacy(), obj] diff --git a/gramps/gui/editors/displaytabs/placebackreflist.py b/gramps/gui/editors/displaytabs/placebackreflist.py index 6ebd0706a..3d8c30283 100644 --- a/gramps/gui/editors/displaytabs/placebackreflist.py +++ b/gramps/gui/editors/displaytabs/placebackreflist.py @@ -29,7 +29,7 @@ from .backreflist import BackRefList class PlaceBackRefList(BackRefList): def __init__(self, dbstate, uistate, track, obj, callback=None): - BackRefList.__init__(self, dbstate, uistate, track, obj, + BackRefList.__init__(self, dbstate, uistate, track, obj, BackRefModel, callback=callback) def get_icon_name(self): diff --git a/gramps/gui/editors/displaytabs/placerefembedlist.py b/gramps/gui/editors/displaytabs/placerefembedlist.py index 4afbbe136..a8d65b50c 100644 --- a/gramps/gui/editors/displaytabs/placerefembedlist.py +++ b/gramps/gui/editors/displaytabs/placerefembedlist.py @@ -43,7 +43,7 @@ from ...selectors import SelectorFactory #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class PlaceRefEmbedList(EmbeddedList): @@ -51,21 +51,21 @@ class PlaceRefEmbedList(EmbeddedList): _HANDLE_COL = 4 _DND_TYPE = DdTargets.PLACEREF _DND_EXTRA = DdTargets.PLACE_LINK - + #index = column in model. Value = # (name, sortcol in model, width, markup/text, weigth_col _column_names = [ - (_('ID'), 0, 75, TEXT_COL, -1, None), - (_('Name'), 1, 250, TEXT_COL, -1, None), - (_('Type'), 2, 100, TEXT_COL, -1, None), - (_('Date'), 3, 150, TEXT_COL, -1, None), + (_('ID'), 0, 75, TEXT_COL, -1, None), + (_('Name'), 1, 250, TEXT_COL, -1, None), + (_('Type'), 2, 100, TEXT_COL, -1, None), + (_('Date'), 3, 150, TEXT_COL, -1, None), ] - + def __init__(self, dbstate, uistate, track, data, handle, callback): self.data = data self.handle = handle self.callback = callback - EmbeddedList.__init__(self, dbstate, uistate, track, + EmbeddedList.__init__(self, dbstate, uistate, track, _('Enclosed By'), PlaceRefModel, share_button=True, move_buttons=True) @@ -92,7 +92,7 @@ class PlaceRefEmbedList(EmbeddedList): place = Place() try: from .. import EditPlaceRef - EditPlaceRef(self.dbstate, self.uistate, self.track, + EditPlaceRef(self.dbstate, self.uistate, self.track, place, ref, self.add_callback) except WindowActiveError: pass @@ -125,7 +125,7 @@ class PlaceRefEmbedList(EmbeddedList): place = self.dbstate.db.get_place_from_handle(ref.ref) try: from .. import EditPlaceRef - EditPlaceRef(self.dbstate, self.uistate, self.track, + EditPlaceRef(self.dbstate, self.uistate, self.track, place, ref, self.edit_callback) except WindowActiveError: pass diff --git a/gramps/gui/editors/displaytabs/placerefmodel.py b/gramps/gui/editors/displaytabs/placerefmodel.py index 534a61ca8..0b066c4af 100644 --- a/gramps/gui/editors/displaytabs/placerefmodel.py +++ b/gramps/gui/editors/displaytabs/placerefmodel.py @@ -47,6 +47,6 @@ class PlaceRefModel(Gtk.ListStore): place = self.db.get_place_from_handle(obj.ref) self.append(row=[place.get_gramps_id(), place.get_name().get_value(), - str(place.get_type()), - displayer.display(obj.date), + str(place.get_type()), + displayer.display(obj.date), obj, ]) diff --git a/gramps/gui/editors/displaytabs/repoembedlist.py b/gramps/gui/editors/displaytabs/repoembedlist.py index 091a9ba08..89e8b340e 100644 --- a/gramps/gui/editors/displaytabs/repoembedlist.py +++ b/gramps/gui/editors/displaytabs/repoembedlist.py @@ -50,7 +50,7 @@ class RepoEmbedList(EmbeddedList, DbGUIElement): _HANDLE_COL = 5 _DND_TYPE = DdTargets.REPOREF _DND_EXTRA = DdTargets.REPO_LINK - + _MSG = { 'add' : _('Create and add a new repository'), 'del' : _('Remove the existing repository'), @@ -69,16 +69,16 @@ class RepoEmbedList(EmbeddedList, DbGUIElement): (_('Type'), 3, 100, TEXT_COL, -1, None), (_('Private'), 4, 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, obj): self.obj = obj - EmbeddedList.__init__(self, dbstate, uistate, track, - _('_Repositories'), RepoRefModel, + EmbeddedList.__init__(self, dbstate, uistate, track, + _('_Repositories'), RepoRefModel, share_button=True, move_buttons=True) DbGUIElement.__init__(self, dbstate.db) - self.callman.register_handles({'repository': [rref.ref for rref + self.callman.register_handles({'repository': [rref.ref for rref in self.obj]}) - + def _connect_db_signals(self): """ Implement base class DbGUIElement method @@ -105,7 +105,7 @@ class RepoEmbedList(EmbeddedList, DbGUIElement): ref = RepoRef() repo = self.dbstate.db.get_repository_from_handle(obj) EditRepoRef( - self.dbstate, self.uistate, self.track, + self.dbstate, self.uistate, self.track, repo, ref, self.add_callback) except WindowActiveError: pass @@ -116,7 +116,7 @@ class RepoEmbedList(EmbeddedList, DbGUIElement): repo = Repository() try: EditRepoRef( - self.dbstate, self.uistate, self.track, + self.dbstate, self.uistate, self.track, repo, ref, self.add_callback) except WindowActiveError: pass @@ -128,7 +128,7 @@ class RepoEmbedList(EmbeddedList, DbGUIElement): self.dbstate, self.uistate, self.track) - + repo = sel.run() if repo: try: @@ -136,11 +136,11 @@ class RepoEmbedList(EmbeddedList, DbGUIElement): ref = RepoRef() EditRepoRef(self.dbstate, self.uistate, - self.track, + self.track, repo, ref, self.add_callback) - + except WindowActiveError: pass @@ -160,7 +160,7 @@ class RepoEmbedList(EmbeddedList, DbGUIElement): try: from .. import EditRepoRef EditRepoRef( - self.dbstate, self.uistate, self.track, repo, + self.dbstate, self.uistate, self.track, repo, ref, self.edit_callback) except WindowActiveError: from ...dialog import WarningDialog @@ -195,7 +195,7 @@ class RepoEmbedList(EmbeddedList, DbGUIElement): pos = ref_handles.index(handle) except ValueError : break - + if pos is not None: #oeps, we need to remove this reference, and rebuild tab del self.obj[pos] diff --git a/gramps/gui/editors/displaytabs/reporefmodel.py b/gramps/gui/editors/displaytabs/reporefmodel.py index ea1332000..a469504ac 100644 --- a/gramps/gui/editors/displaytabs/reporefmodel.py +++ b/gramps/gui/editors/displaytabs/reporefmodel.py @@ -47,7 +47,7 @@ class RepoRefModel(Gtk.ListStore): self.append(row=[ repo.gramps_id, repo.name, - ref.call_number, + ref.call_number, str(repo.get_type()), ref.get_privacy(), ref, ]) diff --git a/gramps/gui/editors/displaytabs/sourcebackreflist.py b/gramps/gui/editors/displaytabs/sourcebackreflist.py index a77a9f4a7..a1102f40f 100644 --- a/gramps/gui/editors/displaytabs/sourcebackreflist.py +++ b/gramps/gui/editors/displaytabs/sourcebackreflist.py @@ -30,7 +30,7 @@ from .backreflist import BackRefList class SourceBackRefList(BackRefList): def __init__(self, dbstate, uistate, track, obj, callback=None): - BackRefList.__init__(self, dbstate, uistate, track, obj, + BackRefList.__init__(self, dbstate, uistate, track, obj, BackRefModel, callback=callback) def get_icon_name(self): diff --git a/gramps/gui/editors/displaytabs/srcattrembedlist.py b/gramps/gui/editors/displaytabs/srcattrembedlist.py index e53e753e9..fc5c59714 100644 --- a/gramps/gui/editors/displaytabs/srcattrembedlist.py +++ b/gramps/gui/editors/displaytabs/srcattrembedlist.py @@ -41,7 +41,7 @@ from .embeddedlist import (EmbeddedList, TEXT_COL, MARKUP_COL, ICON_COL, #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class SrcAttrEmbedList(EmbeddedList): @@ -64,7 +64,7 @@ class SrcAttrEmbedList(EmbeddedList): (_('Value'), 1, 200, TEXT_EDIT_COL, -1, None), (_('Private'), 2, 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, data): """ Initialize the displaytab. The dbstate and uistate is needed @@ -73,7 +73,7 @@ class SrcAttrEmbedList(EmbeddedList): display and edit """ self.data = data - EmbeddedList.__init__(self, dbstate, uistate, track, _('_Attributes'), + EmbeddedList.__init__(self, dbstate, uistate, track, _('_Attributes'), AttrModel, move_buttons=True) def get_editor(self): @@ -85,7 +85,7 @@ class SrcAttrEmbedList(EmbeddedList): def get_icon_name(self): return 'gramps-attribute' - + def get_data(self): return self.data @@ -96,7 +96,7 @@ class SrcAttrEmbedList(EmbeddedList): """ inherit this and set the variables needed for editable columns Variable edit_col_funcs needs to be a dictionary from model col_nr to - function to call for + function to call for Example: self.edit_col_funcs ={1: {'edit_start': self.on_edit_start, 'edited': self.on_edited @@ -106,7 +106,7 @@ class SrcAttrEmbedList(EmbeddedList): 'edited': self.on_value_edited}} def on_value_edit_start(self, cellr, celle, path, colnr): - """ + """ Start of editing. Store stuff so we know when editing ends where we are """ @@ -133,7 +133,7 @@ class SrcAttrEmbedList(EmbeddedList): attr = SrcAttribute() try: self.get_editor()( - self.dbstate, self.uistate, self.track, attr, + self.dbstate, self.uistate, self.track, attr, pname, self.get_user_values(), self.add_callback) except WindowActiveError: pass @@ -151,7 +151,7 @@ class SrcAttrEmbedList(EmbeddedList): pname = '' try: self.get_editor()( - self.dbstate, self.uistate, self.track, attr, + self.dbstate, self.uistate, self.track, attr, pname, self.get_user_values(), self.edit_callback) except WindowActiveError: pass diff --git a/gramps/gui/editors/displaytabs/surnamemodel.py b/gramps/gui/editors/displaytabs/surnamemodel.py index 10199e5fd..cac5e52c1 100644 --- a/gramps/gui/editors/displaytabs/surnamemodel.py +++ b/gramps/gui/editors/displaytabs/surnamemodel.py @@ -42,7 +42,7 @@ class SurnameModel(Gtk.ListStore): def __init__(self, surn_list, db): #setup model for the treeview - Gtk.ListStore.__init__(self, str, str, str, str, + Gtk.ListStore.__init__(self, str, str, str, str, bool, object) for surn in surn_list: # fill the liststore diff --git a/gramps/gui/editors/displaytabs/surnametab.py b/gramps/gui/editors/displaytabs/surnametab.py index 941e431ce..50ab46e1a 100644 --- a/gramps/gui/editors/displaytabs/surnametab.py +++ b/gramps/gui/editors/displaytabs/surnametab.py @@ -59,7 +59,7 @@ class SurnameTab(EmbeddedList): _HANDLE_COL = 5 _DND_TYPE = DdTargets.SURNAME - + _MSG = { 'add' : _('Create and add a new surname'), 'del' : _('Remove the selected surname'), @@ -67,7 +67,7 @@ class SurnameTab(EmbeddedList): 'up' : _('Move the selected surname upwards'), 'down' : _('Move the selected surname downwards'), } - + #index = column in model. Value = # (name, sortcol in model, width, markup/text _column_names = [ @@ -77,7 +77,7 @@ class SurnameTab(EmbeddedList): ] _column_combo = (_('Origin'), -1, 150, 3) # name, sort, width, modelcol _column_toggle = (_('Name|Primary'), -1, 80, 4) - + def __init__(self, dbstate, uistate, track, name, on_change=None, top_label='%s' % _("Multiple Surnames") ): self.obj = name @@ -85,9 +85,9 @@ class SurnameTab(EmbeddedList): self.curr_col = -1 self.curr_cellr = None self.curr_celle = None - - EmbeddedList.__init__(self, dbstate, uistate, track, _('Family Surnames'), - SurnameModel, move_buttons=True, + + EmbeddedList.__init__(self, dbstate, uistate, track, _('Family Surnames'), + SurnameModel, move_buttons=True, top_label=top_label) def build_columns(self): @@ -101,7 +101,7 @@ class SurnameTab(EmbeddedList): renderer.set_property('editable', not self.dbstate.db.readonly) renderer.connect('editing_started', self.on_edit_start, colno) renderer.connect('edited', self.on_edit_inline, self.column_order()[colno][1]) - + # now we add the two special columns # combobox for type colno = len(self.columns) @@ -203,7 +203,7 @@ class SurnameTab(EmbeddedList): prim = False if len(self.obj.get_surname_list()) == 0: prim = True - node = self.model.append(row=['', '', '', str(NameOriginType()), prim, + node = self.model.append(row=['', '', '', str(NameOriginType()), prim, Surname()]) self.selection.select_iter(node) path = self.model.get_path(node) @@ -229,7 +229,7 @@ class SurnameTab(EmbeddedList): self.curr_col = colnr self.curr_cellr = cellr self.curr_celle = celle - + def on_edit_start_cmb(self, cellr, celle, path, colnr): """ An edit starts in the origin type column @@ -279,14 +279,14 @@ class SurnameTab(EmbeddedList): act = cmb.get_active() if act == -1: return - self.on_orig_edited(None, path, + self.on_orig_edited(None, path, self.cmborig.get_value( self.cmborig.get_iter((act,)),1), colnr) def on_prim_toggled(self, cell, path, colnr): """ - Primary surname on path is toggled. colnr must be the col + Primary surname on path is toggled. colnr must be the col in the model """ #obtain current value @@ -318,7 +318,7 @@ class SurnameTab(EmbeddedList): def key_pressed(self, obj, event): """ - Handles the key being pressed. + Handles the key being pressed. Here we make sure tab moves to next or previous value in row on TAB """ if not EmbeddedList.key_pressed(self, obj, event): @@ -338,7 +338,7 @@ class SurnameTab(EmbeddedList): def next_cell(self): """ Move to the next cell to edit it - """ + """ (model, node) = self.selection.get_selected() if node: path = self.model.get_path(node).get_indices()[0] @@ -365,12 +365,12 @@ class SurnameTab(EmbeddedList): self.curr_celle.editing_done() return return True - - + + def prev_cell(self): """ Move to the next cell to edit it - """ + """ (model, node) = self.selection.get_selected() if node: path = self.model.get_path(node).get_indices()[0] diff --git a/gramps/gui/editors/displaytabs/webembedlist.py b/gramps/gui/editors/displaytabs/webembedlist.py index 445866976..f797ab7ad 100644 --- a/gramps/gui/editors/displaytabs/webembedlist.py +++ b/gramps/gui/editors/displaytabs/webembedlist.py @@ -42,7 +42,7 @@ from .embeddedlist import EmbeddedList, TEXT_COL, MARKUP_COL, ICON_COL #------------------------------------------------------------------------- # -# +# # #------------------------------------------------------------------------- class WebEmbedList(EmbeddedList): @@ -67,10 +67,10 @@ class WebEmbedList(EmbeddedList): (_('Description'), 2, 150, TEXT_COL, -1, None), (_('Private'), 3, 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, data): self.data = data - EmbeddedList.__init__(self, dbstate, uistate, track, _('_Internet'), + EmbeddedList.__init__(self, dbstate, uistate, track, _('_Internet'), WebModel, move_buttons=True, jump_button=True) def get_icon_name(self): @@ -86,7 +86,7 @@ class WebEmbedList(EmbeddedList): from .. import EditUrl url = Url() try: - EditUrl(self.dbstate, self.uistate, self.track, + EditUrl(self.dbstate, self.uistate, self.track, '', url, self.add_callback) except WindowActiveError: pass @@ -102,7 +102,7 @@ class WebEmbedList(EmbeddedList): url = self.get_selected() if url: try: - EditUrl(self.dbstate, self.uistate, self.track, + EditUrl(self.dbstate, self.uistate, self.track, '', url, self.edit_callback) except WindowActiveError: pass @@ -111,7 +111,7 @@ class WebEmbedList(EmbeddedList): self.rebuild() def get_popup_menu_items(self): - return [ + return [ (True, _('_Add'), 'list-add', self.add_button_clicked), (False, _('_Edit'), 'gtk-edit', self.edit_button_clicked), (True, _('_Remove'), 'list-remove', self.del_button_clicked), diff --git a/gramps/gui/editors/displaytabs/webmodel.py b/gramps/gui/editors/displaytabs/webmodel.py index 8fc34322f..312e01e07 100644 --- a/gramps/gui/editors/displaytabs/webmodel.py +++ b/gramps/gui/editors/displaytabs/webmodel.py @@ -43,5 +43,5 @@ class WebModel(Gtk.ListStore): Gtk.ListStore.__init__(self, str, str, str, bool, object) self.db = dbase for obj in obj_list: - self.append(row=[str(obj.type), obj.path, obj.desc, + self.append(row=[str(obj.type), obj.path, obj.desc, obj.get_privacy(), obj]) diff --git a/gramps/gui/editors/editaddress.py b/gramps/gui/editors/editaddress.py index 1c5240517..55ce2619f 100644 --- a/gramps/gui/editors/editaddress.py +++ b/gramps/gui/editors/editaddress.py @@ -75,7 +75,7 @@ class EditAddress(EditSecondary): def _local_init(self): self.width_key = 'interface.address-width' self.height_key = 'interface.address-height' - + self.top = Glade() self.set_window(self.top.toplevel, self.top.get_object("title"), @@ -84,12 +84,12 @@ class EditAddress(EditSecondary): def _setup_fields(self): self.addr_start = MonitoredDate( self.top.get_object("date_entry"), - self.top.get_object("date_stat"), + self.top.get_object("date_stat"), self.obj.get_date_object(), self.uistate, self.track, self.db.readonly) - + self.street = MonitoredEntry( self.top.get_object("street"), self.obj.set_street, self.obj.get_street, self.db.readonly) @@ -117,7 +117,7 @@ class EditAddress(EditSecondary): self.phone = MonitoredEntry( self.top.get_object("phone"), self.obj.set_phone, self.obj.get_phone, self.db.readonly) - + self.priv = PrivacyButton(self.top.get_object("private"), self.obj, self.db.readonly) @@ -131,16 +131,16 @@ class EditAddress(EditSecondary): Create the notebook tabs and inserts them into the main window. """ - + notebook = Gtk.Notebook() - - self.srcref_list = CitationEmbedList(self.dbstate, - self.uistate, - self.track, + + self.srcref_list = CitationEmbedList(self.dbstate, + self.uistate, + self.track, self.obj.get_citation_list()) self._add_tab(notebook, self.srcref_list) self.track_ref_for_deletion("srcref_list") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, self.obj.get_note_list(), notetype=NoteType.ADDRESS) diff --git a/gramps/gui/editors/editattribute.py b/gramps/gui/editors/editattribute.py index c5bce36a5..ab0b62557 100644 --- a/gramps/gui/editors/editattribute.py +++ b/gramps/gui/editors/editattribute.py @@ -80,7 +80,7 @@ class EditAttributeRoot(EditSecondary): self.width_key = 'interface.attribute-width' self.height_key = 'interface.attribute-height' self.top = Glade('editattribute.glade') - + self.set_window(self.top.toplevel, self.top.get_object('title'), _('Attribute Editor')) @@ -95,7 +95,7 @@ class EditAttributeRoot(EditSecondary): self.top.get_object("attr_value"), self.obj.set_value, self.obj.get_value, self.db.readonly) - + self.priv = PrivacyButton( self.top.get_object("private"), self.obj, self.db.readonly) @@ -111,11 +111,11 @@ class EditAttributeRoot(EditSecondary): def _create_tabbed_pages(self): notebook = Gtk.Notebook() - + self._setup_notebook_tabs( notebook) notebook.show_all() self.top.get_object('vbox').pack_start(notebook, True, True, 0) - + def build_menu_names(self, attrib): if not attrib: label = _("New Attribute") @@ -132,7 +132,7 @@ class EditAttributeRoot(EditSecondary): form and updates the Attribute data structure. """ t = self.obj.get_type() - + if t.is_custom() and str(t) == '': from ..dialog import ErrorDialog ErrorDialog( @@ -150,10 +150,10 @@ class EditAttributeRoot(EditSecondary): #------------------------------------------------------------------------- class EditSrcAttribute(EditAttributeRoot): """ - Source attribute are minimal attributes. This Displays the editor to + Source attribute are minimal attributes. This Displays the editor to edit these. """ - + def __init__(self, state, uistate, track, attrib, title, data_list, callback): """ Displays the dialog box. @@ -168,7 +168,7 @@ class EditSrcAttribute(EditAttributeRoot): """ EditAttributeRoot.__init__(self, state, uistate, track, attrib, title, data_list, callback) - + #------------------------------------------------------------------------- # # EditAttribute class @@ -202,13 +202,13 @@ class EditAttribute(EditAttributeRoot): self.obj.get_citation_list()) self._add_tab(notebook, self.srcref_list) self.track_ref_for_deletion("srcref_list") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, self.obj.get_note_list(), notetype = NoteType.ATTRIBUTE) self._add_tab(notebook, self.note_tab) self.track_ref_for_deletion("note_tab") - + self._setup_notebook_tabs( notebook) notebook.show_all() self.top.get_object('vbox').pack_start(notebook, True, True, 0) diff --git a/gramps/gui/editors/editchildref.py b/gramps/gui/editors/editchildref.py index 267ddde2c..5c9139f24 100644 --- a/gramps/gui/editors/editchildref.py +++ b/gramps/gui/editors/editchildref.py @@ -105,8 +105,8 @@ class EditChildRef(EditSecondary): # Set the drag action from the label self.label_event_box = self.top.get_object('name_event_box') - self.label_event_box.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, - [], + self.label_event_box.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, + [], Gdk.DragAction.COPY) tglist = Gtk.TargetList.new([]) tglist.add(DdTargets.PERSON_LINK.atom_drag_type, @@ -132,7 +132,7 @@ class EditChildRef(EditSecondary): self.db.readonly, self.db.get_child_reference_types() ) - + self.priv = PrivacyButton( self.top.get_object("private"), self.obj, @@ -144,10 +144,10 @@ class EditChildRef(EditSecondary): self.define_ok_button(self.ok_button, self.save) self.edit_button.connect('button-press-event', self.edit_child) self.edit_button.connect('key-press-event', self.edit_child) - + def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('person-update', self.person_change) @@ -169,9 +169,9 @@ class EditChildRef(EditSecondary): """ notebook = Gtk.Notebook() - self.srcref_list = CitationEmbedList(self.dbstate, - self.uistate, - self.track, + self.srcref_list = CitationEmbedList(self.dbstate, + self.uistate, + self.track, self.obj.get_citation_list()) self._add_tab(notebook, self.srcref_list) self.track_ref_for_deletion("srcref_list") @@ -186,7 +186,7 @@ class EditChildRef(EditSecondary): notebook.show_all() self.top.get_object('vbox').pack_start(notebook, True, True, 0) - def _post_init(self): + def _post_init(self): self.ok_button.grab_focus() def build_menu_names(self, obj): @@ -221,7 +221,7 @@ class EditChildRef(EditSecondary): def check_for_close(self, handles): """ - Callback method for delete signals. + Callback method for delete signals. If there is a delete signal of the primary object we are editing, the editor (and all child windows spawned) should be closed """ diff --git a/gramps/gui/editors/editcitation.py b/gramps/gui/editors/editcitation.py index 0ca190d82..bf88f273c 100644 --- a/gramps/gui/editors/editcitation.py +++ b/gramps/gui/editors/editcitation.py @@ -67,33 +67,33 @@ from ..glade import Glade class EditCitation(EditPrimary): """ Create an EditCitation window. Associate a citation with the window. - + This class is called both to edit the Citation Primary object and to edit references from other objects to citations. It is called from ..editors.__init__ for editing the primary object and is called from CitationEmbedList for editing references - - @param callertitle: Text passed by calling object to add to title + + @param callertitle: Text passed by calling object to add to title @type callertitle: str """ def __init__(self, dbstate, uistate, track, obj, source=None, callback=None, callertitle = None): """ - The obj parameter is mandatory. If the source parameter is not + The obj parameter is mandatory. If the source parameter is not provided, it will be deduced from the obj Citation object. """ if source: obj.set_reference_handle(source.get_handle()) self.callertitle = callertitle - EditPrimary.__init__(self, dbstate, uistate, track, obj, - dbstate.db.get_citation_from_handle, + EditPrimary.__init__(self, dbstate, uistate, track, obj, + dbstate.db.get_citation_from_handle, dbstate.db.get_citation_from_gramps_id, callback) def empty_object(self): """ Return an empty Citation object for comparison for changes. - + It is used by the base class L{EditPrimary}. """ return Citation() @@ -120,32 +120,32 @@ class EditCitation(EditPrimary): 'id' : title, 'context' : self.callertitle }) - else: + else: title = _('New Citation') return title def _local_init(self): """ Local initialization function. - + Perform basic initialization, including setting up widgets and the glade interface. It is called by the base class L{EditPrimary}, and overridden here. """ self.width_key = 'interface.citation-width' self.height_key = 'interface.citation-height' - + self.glade = Glade() - self.set_window(self.glade.toplevel, None, + self.set_window(self.glade.toplevel, None, self.get_menu_title()) - + self.share_btn = self.glade.get_object('select_source') self.add_del_btn = self.glade.get_object('add_del_source') def _connect_signals(self): """ Connects any signals that need to be connected. - + Called by the init routine of the base class L{EditPrimary}. """ self.define_ok_button(self.glade.get_object('ok'), self.save) @@ -154,15 +154,15 @@ class EditCitation(EditPrimary): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). - + What this code does is to check that the object edited is not deleted whilst editing it. If the object is deleted we need to close the editor windows and clean up. If the database emits a rebuild signal for the database object type we also abort the edit. """ - + self._add_db_signal('citation-rebuild', self._do_close) self._add_db_signal('citation-delete', self.check_for_close) @@ -177,10 +177,10 @@ class EditCitation(EditPrimary): self.obj.get_reference_handle, self.add_del_btn, self.share_btn, callback=self.source_changed) - + self.date = MonitoredDate( self.glade.get_object("date_entry"), - self.glade.get_object("date_stat"), + self.glade.get_object("date_stat"), self.obj.get_date_object(), self.uistate, self.track, @@ -193,7 +193,7 @@ class EditCitation(EditPrimary): self.volume = MonitoredEntry( self.glade.get_object("volume"), self.obj.set_page, self.obj.get_page, self.db.readonly) - + self.type_mon = MonitoredMenu( self.glade.get_object('confidence'), self.obj.set_confidence_level, @@ -206,9 +206,9 @@ class EditCitation(EditPrimary): self.db.readonly) self.tags2 = MonitoredTagList( - self.glade.get_object("tag_label"), - self.glade.get_object("tag_button"), - self.obj.set_tag_list, + self.glade.get_object("tag_label"), + self.glade.get_object("tag_button"), + self.obj.set_tag_list, self.obj.get_tag_list, self.db, self.uistate, self.track, @@ -234,13 +234,13 @@ class EditCitation(EditPrimary): self.obj.get_media_list()) self._add_tab(notebook, self.gallery_tab) self.track_ref_for_deletion("gallery_tab") - + self.attr_tab = SrcAttrEmbedList(self.dbstate, self.uistate, self.track, self.obj.get_attribute_list()) self._add_tab(notebook, self.attr_tab) self.track_ref_for_deletion("attr_tab") - - self.citationref_list = CitationBackRefList(self.dbstate, self.uistate, + + self.citationref_list = CitationBackRefList(self.dbstate, self.uistate, self.track, self.db.find_backlink_handles(self.obj.handle)) self._add_tab(notebook, self.citationref_list) @@ -265,7 +265,7 @@ class EditCitation(EditPrimary): Provide the information needed by the base class to define the window management menu entries. """ - return (_('Edit Citation'), self.get_menu_title()) + return (_('Edit Citation'), self.get_menu_title()) def save(self, *obj): """ @@ -283,14 +283,14 @@ class EditCitation(EditPrimary): "'Volume/Page' field.")) self.ok_button.set_sensitive(True) return - + (uses_dupe_id, gramps_id) = self._uses_duplicate_id() if uses_dupe_id: prim_object = self.get_from_gramps_id(gramps_id) name = prim_object.get_page() msg1 = _("Cannot save citation. ID already exists.") msg2 = _("You have attempted to use the existing Gramps ID with " - "value %(id)s. This value is already used by '" + "value %(id)s. This value is already used by '" "%(prim_object)s'. Please enter a different ID or leave " "blank to get the next available ID value.") % { 'id' : gramps_id, 'prim_object' : name } @@ -309,7 +309,7 @@ class EditCitation(EditPrimary): self.db.commit_citation(self.obj, trans) msg = _("Edit Citation (%s)") % self.obj.get_page() trans.set_description(msg) - + if self.callback: self.callback(self.obj.get_handle()) self.close() @@ -345,8 +345,8 @@ class DeleteCitationQuery(object): with DbTxn(_("Delete Citation (%s)") % self.citation.get_page(), self.db) as trans: self.db.disable_signals() - - (person_list, family_list, event_list, place_list, source_list, + + (person_list, family_list, event_list, place_list, source_list, media_list, repo_list) = self.the_lists ctn_handle_list = [self.citation.get_handle()] diff --git a/gramps/gui/editors/editdate.py b/gramps/gui/editors/editdate.py index e087f9edc..6d95a3315 100644 --- a/gramps/gui/editors/editdate.py +++ b/gramps/gui/editors/editdate.py @@ -20,14 +20,14 @@ # """ -Date editing module for Gramps. +Date editing module for Gramps. -The EditDate provides visual feedback to the user to indicate if -the associated GtkEntry box contains a valid date. +The EditDate provides visual feedback to the user to indicate if +the associated GtkEntry box contains a valid date. Red means that the date is not valid, and will be viewed as a text string instead of a date. -The DateEditor provides a dialog in which the date can be +The DateEditor provides a dialog in which the date can be unambiguously built using UI controls such as menus and spin buttons. """ @@ -72,7 +72,7 @@ from ..glade import Glade # Constants # #------------------------------------------------------------------------- -MOD_TEXT = ( +MOD_TEXT = ( (Date.MOD_NONE , _('Regular')), (Date.MOD_BEFORE , _('Before')), (Date.MOD_AFTER , _('After')), @@ -82,8 +82,8 @@ MOD_TEXT = ( (Date.MOD_TEXTONLY , _('Text only')) ) QUAL_TEXT = ( - (Date.QUAL_NONE, _('Regular')), - (Date.QUAL_ESTIMATED, _('Estimated')), + (Date.QUAL_NONE, _('Regular')), + (Date.QUAL_ESTIMATED, _('Estimated')), (Date.QUAL_CALCULATED, _('Calculated')) ) CAL_TO_MONTHS_NAMES = { @@ -105,7 +105,7 @@ WIKI_HELP_SEC = _('manual|Editing_Dates') #------------------------------------------------------------------------- class EditDate(ManagedWindow): """ - Dialog allowing to build the date precisely, to correct possible + Dialog allowing to build the date precisely, to correct possible limitations of parsing and/or underlying structure of :class:`.Date`. """ @@ -114,17 +114,17 @@ class EditDate(ManagedWindow): Initiate and display the dialog. """ ManagedWindow.__init__(self, uistate, track, self) - + # Create self.date as a copy of the given Date object. self.date = Date(date) - + self.top = Glade() self.set_window( self.top.toplevel, self.top.get_object('title'), - _('Date selection')) - + _('Date selection')) + self.statusbar = self.top.get_object('statusbar') self.ok_button = self.top.get_object('ok_button') self.calendar_box = self.top.get_object('calendar_box') @@ -160,7 +160,7 @@ class EditDate(ManagedWindow): self.stop_month_box.append_text(name) self.start_month_box.set_active(self.date.get_month()) self.stop_month_box.set_active(self.date.get_stop_month()) - + self.start_day = self.top.get_object('start_day') self.start_day.set_value(self.date.get_day()) self.start_year = self.top.get_object('start_year') @@ -170,7 +170,7 @@ class EditDate(ManagedWindow): self.stop_day.set_value(self.date.get_stop_day()) self.stop_year = self.top.get_object('stop_year') self.stop_year.set_value(self.date.get_stop_year()) - + self.dual_dated = self.top.get_object('dualdated') # Disable second date controls if not compound date @@ -201,7 +201,7 @@ class EditDate(ManagedWindow): # The dialog is modal -- since dates don't have names, we don't # want to have several open dialogs, since then the user will # loose track of which is which. Much like opening files. - + self.validated_date = self.return_date = None for o in self.top.get_objects(): @@ -240,7 +240,7 @@ class EditDate(ManagedWindow): If anything changed, revalidate the date and enable/disable the "OK" button based on the result. """ - (the_quality, the_modifier, the_calendar, the_value, + (the_quality, the_modifier, the_calendar, the_value, the_text, the_newyear) = self.build_date_from_ui() LOG.debug("revalidate: {0} changed, value: {1}".format( obj, the_value)) @@ -261,10 +261,10 @@ class EditDate(ManagedWindow): self.ok_button.set_sensitive(1) self.calendar_box.set_sensitive(1) return True - except DateError as e: + except DateError as e: self.ok_button.set_sensitive(0) self.calendar_box.set_sensitive(0) - self.statusbar.push(1, + self.statusbar.push(1, _("Correct the date or switch from `{cur_mode}' to `{text_mode}'" ).format( cur_mode = MOD_TEXT[self.type_box.get_active()][1], @@ -279,12 +279,12 @@ class EditDate(ManagedWindow): def build_date_from_ui(self): """ - Collect information from the UI controls and return - 5-tuple of (quality,modifier,calendar,value,text) + Collect information from the UI controls and return + 5-tuple of (quality,modifier,calendar,value,text) """ - # It is important to not set date based on these controls. + # It is important to not set date based on these controls. # For example, changing the caledar makes the date inconsistent - # until the callback of the calendar menu is finished. + # until the callback of the calendar menu is finished. # We need to be able to use this function from that callback, # so here we just report on the state of all widgets, without # actually modifying the date yet. @@ -319,12 +319,12 @@ class EditDate(ManagedWindow): def switch_type(self, obj): """ - Disable/enable various date controls depending on the date + Disable/enable various date controls depending on the date type selected via the menu. """ the_modifier = MOD_TEXT[self.type_box.get_active()][0] - + # Disable/enable second date controls based on whether # the type allows compound dates if the_modifier in (Date.MOD_RANGE, Date.MOD_SPAN): @@ -368,10 +368,10 @@ class EditDate(ManagedWindow): def switch_calendar(self, obj): """ - Change month names and convert the date based on the calendar + Change month names and convert the date based on the calendar selected via the menu. """ - + old_cal = self.date.get_calendar() new_cal = self.calendar_box.get_active() LOG.debug(">>>switch_calendar: {0} changed, {1} -> {2}".format( @@ -379,7 +379,7 @@ class EditDate(ManagedWindow): self.align_newyear_ui_with_calendar(new_cal) - (the_quality, the_modifier, the_calendar, + (the_quality, the_modifier, the_calendar, the_value, the_text, the_newyear) = self.build_date_from_ui() try: self.date.set( @@ -394,7 +394,7 @@ class EditDate(ManagedWindow): else: if not self.date.is_empty(): self.date.convert_calendar(new_cal) - + self.start_month_box.get_model().clear() self.stop_month_box.get_model().clear() month_names = CAL_TO_MONTHS_NAMES[new_cal] diff --git a/gramps/gui/editors/editevent.py b/gramps/gui/editors/editevent.py index 88b31095f..7414bfe34 100644 --- a/gramps/gui/editors/editevent.py +++ b/gramps/gui/editors/editevent.py @@ -48,9 +48,9 @@ from .editprimary import EditPrimary from .objectentries import PlaceEntry from ..glade import Glade from ..dialog import ErrorDialog -from .displaytabs import (CitationEmbedList, NoteTab, GalleryTab, +from .displaytabs import (CitationEmbedList, NoteTab, GalleryTab, EventBackRefList, EventAttrEmbedList) -from ..widgets import (MonitoredEntry, PrivacyButton, MonitoredDataType, +from ..widgets import (MonitoredEntry, PrivacyButton, MonitoredDataType, MonitoredDate, MonitoredTagList) from gramps.gen.utils.db import get_participant_from_event @@ -72,7 +72,7 @@ class EditEvent(EditPrimary): def __init__(self, dbstate, uistate, track, event, callback=None): EditPrimary.__init__(self, dbstate, uistate, track, - event, dbstate.db.get_event_from_handle, + event, dbstate.db.get_event_from_handle, dbstate.db.get_event_from_gramps_id) self._init_event() @@ -108,7 +108,7 @@ class EditEvent(EditPrimary): self.height_key = 'interface.event-height' self.top = Glade() - self.set_window(self.top.toplevel, None, + self.set_window(self.top.toplevel, None, self.get_menu_title()) self.place = self.top.get_object('place') @@ -125,7 +125,7 @@ class EditEvent(EditPrimary): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('event-rebuild', self._do_close) @@ -134,26 +134,26 @@ class EditEvent(EditPrimary): def _setup_fields(self): # place, select_place, add_del_place - + self.place_field = PlaceEntry(self.dbstate, self.uistate, self.track, self.top.get_object("place"), self.top.get_object("place_event_box"), self.obj.set_place_handle, self.obj.get_place_handle, self.add_del_btn, self.share_btn) - + self.descr_field = MonitoredEntry(self.top.get_object("event_description"), self.obj.set_description, - self.obj.get_description, + self.obj.get_description, self.db.readonly) self.gid = MonitoredEntry(self.top.get_object("gid"), self.obj.set_gramps_id, self.obj.get_gramps_id, self.db.readonly) - self.tags = MonitoredTagList(self.top.get_object("tag_label"), - self.top.get_object("tag_button"), - self.obj.set_tag_list, + self.tags = MonitoredTagList(self.top.get_object("tag_label"), + self.top.get_object("tag_button"), + self.obj.set_tag_list, self.obj.get_tag_list, self.db, self.uistate, self.track, @@ -170,7 +170,7 @@ class EditEvent(EditPrimary): self.date_field = MonitoredDate(self.top.get_object("date_entry"), self.top.get_object("date_stat"), self.obj.get_date_object(), - self.uistate, self.track, + self.uistate, self.track, self.db.readonly) def _create_tabbed_pages(self): @@ -183,17 +183,17 @@ class EditEvent(EditPrimary): self.citation_list = CitationEmbedList(self.dbstate, self.uistate, self.track, - self.obj.get_citation_list(), + self.obj.get_citation_list(), self.get_menu_title()) self._add_tab(notebook, self.citation_list) - + self.note_list = NoteTab(self.dbstate, self.uistate, self.track, self.obj.get_note_list(), notetype=NoteType.EVENT) self._add_tab(notebook, self.note_list) - + self.gallery_list = GalleryTab(self.dbstate, self.uistate, @@ -215,7 +215,7 @@ class EditEvent(EditPrimary): self._add_tab(notebook, self.backref_list) self._setup_notebook_tabs(notebook) - + notebook.show_all() self.top.get_object('vbox').pack_start(notebook, True, True, 0) @@ -239,14 +239,14 @@ class EditEvent(EditPrimary): "enter data or cancel the edit.")) self.ok_button.set_sensitive(True) return - + (uses_dupe_id, id) = self._uses_duplicate_id() if uses_dupe_id: prim_object = self.get_from_gramps_id(id) name = prim_object.get_description() msg1 = _("Cannot save event. ID already exists.") msg2 = _("You have attempted to use the existing Gramps ID with " - "value %(id)s. This value is already used by '" + "value %(id)s. This value is already used by '" "%(prim_object)s'. Please enter a different ID or leave " "blank to get the next available ID value.") % { 'id' : id, 'prim_object' : name } @@ -286,7 +286,7 @@ class EditEvent(EditPrimary): entered date when importing from a XML file, so we can get an incorrect fail. """ - + if self.db.readonly: return False elif self.obj.handle: @@ -317,7 +317,7 @@ class DeleteEventQuery(object): with DbTxn(_("Delete Event (%s)") % self.event.get_gramps_id(), self.db) as trans: self.db.disable_signals() - + ev_handle_list = [self.event.get_handle()] for handle in self.person_list: diff --git a/gramps/gui/editors/editeventref.py b/gramps/gui/editors/editeventref.py index 8c19d720d..f0f72a9d6 100644 --- a/gramps/gui/editors/editeventref.py +++ b/gramps/gui/editors/editeventref.py @@ -37,7 +37,7 @@ _ = glocale.translation.gettext from gramps.gen.lib import EventType, NoteType from gramps.gen.db import DbTxn from ..glade import Glade -from .displaytabs import (CitationEmbedList, NoteTab, GalleryTab, +from .displaytabs import (CitationEmbedList, NoteTab, GalleryTab, EventBackRefList, AttrEmbedList) from ..widgets import (PrivacyButton, MonitoredEntry, MonitoredDate, MonitoredDataType) @@ -60,7 +60,7 @@ class EditEventRef(EditReference): def _local_init(self): self.width_key = 'interface.event-ref-width' self.height_key = 'interface.event-ref-height' - + self.top = Glade() self.set_window(self.top.toplevel, self.top.get_object('eer_title'), @@ -74,13 +74,13 @@ class EditEventRef(EditReference): notebook = self.top.get_object('notebook_ref') #recreate start page as GrampsTab notebook.remove_page(0) - self.reftab = RefTab(self.dbstate, self.uistate, self.track, + self.reftab = RefTab(self.dbstate, self.uistate, self.track, _('General'), tblref) tblref = self.top.get_object('table62') notebook = self.top.get_object('notebook') #recreate start page as GrampsTab notebook.remove_page(0) - self.primtab = RefTab(self.dbstate, self.uistate, self.track, + self.primtab = RefTab(self.dbstate, self.uistate, self.track, _('_General'), tblref) def _post_init(self): @@ -103,14 +103,14 @@ class EditEventRef(EditReference): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('event-rebuild', self.close) self._add_db_signal('event-delete', self.check_for_close) def _setup_fields(self): - + self.ref_privacy = PrivacyButton( self.top.get_object('eer_ref_priv'), self.source_ref, self.db.readonly) @@ -141,7 +141,7 @@ class EditEventRef(EditReference): self.ev_privacy = PrivacyButton( self.top.get_object("eer_ev_priv"), self.source, self.db.readonly) - + self.role_selector = MonitoredDataType( self.top.get_object('eer_role_combo'), self.source_ref.set_role, @@ -200,7 +200,7 @@ class EditEventRef(EditReference): notetype=NoteType.EVENT) self._add_tab(notebook, self.note_tab) self.track_ref_for_deletion("note_tab") - + self.note_ref_tab = NoteTab(self.dbstate, self.uistate, self.track, @@ -208,7 +208,7 @@ class EditEventRef(EditReference): notetype=NoteType.EVENTREF) self._add_tab(notebook_ref, self.note_ref_tab) self.track_ref_for_deletion("note_ref_tab") - + self.gallery_tab = GalleryTab(self.dbstate, self.uistate, self.track, @@ -241,7 +241,7 @@ class EditEventRef(EditReference): else: submenu_label = _('New Event') return (_('Event Reference Editor'),submenu_label) - + def ok_clicked(self, obj): if self.source.handle: @@ -253,7 +253,7 @@ class EditEventRef(EditReference): with DbTxn(_("Add Event"), self.db) as trans: self.add_event(self.source,trans) self.source_ref.ref = self.source.handle - + if self.update: self.update(self.source_ref,self.source) diff --git a/gramps/gui/editors/editfamily.py b/gramps/gui/editors/editfamily.py index 2c5110b1b..7d64e7b26 100644 --- a/gramps/gui/editors/editfamily.py +++ b/gramps/gui/editors/editfamily.py @@ -66,8 +66,8 @@ from ..glade import Glade from .editprimary import EditPrimary from .editchildref import EditChildRef from .editperson import EditPerson -from .displaytabs import (EmbeddedList, EventEmbedList, CitationEmbedList, - FamilyAttrEmbedList, NoteTab, GalleryTab, +from .displaytabs import (EmbeddedList, EventEmbedList, CitationEmbedList, + FamilyAttrEmbedList, NoteTab, GalleryTab, FamilyLdsEmbedList, ChildModel, TEXT_COL, MARKUP_COL, ICON_COL) from ..widgets import (PrivacyButton, MonitoredEntry, MonitoredDataType, @@ -123,13 +123,13 @@ class ChildEmbedList(EmbeddedList): None, (_('Private'), 13, 30, ICON_COL, -1, 'gramps-lock') ] - + def __init__(self, dbstate, uistate, track, family): """ Create the object, storing the passed family value """ self.family = family - EmbeddedList.__init__(self, dbstate, uistate, track, _('Chil_dren'), + EmbeddedList.__init__(self, dbstate, uistate, track, _('Chil_dren'), ChildModel, share_button=True, move_buttons=True) def get_popup_menu_items(self): @@ -158,16 +158,16 @@ class ChildEmbedList(EmbeddedList): return self.family.get_child_ref_list() def column_order(self): - return [(1, 13), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), + return [(1, 13), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (0, 8), (0, 9)] def add_button_clicked(self, obj=None): person = Person() autoname = config.get('behavior.surname-guessing') - #_("Father's surname"), - #_("None"), - #_("Combination of mother's and father's surname"), - #_("Icelandic style"), + #_("Father's surname"), + #_("None"), + #_("Combination of mother's and father's surname"), + #_("Icelandic style"), if autoname == 0: name = self.north_american() elif autoname == 2: @@ -181,7 +181,7 @@ class ChildEmbedList(EmbeddedList): def handle_extra_type(self, objtype, obj): """ - Called when a person is dropped onto the list. objtype will be + Called when a person is dropped onto the list. objtype will be 'person-link' and obj will contain a person handle. """ person = self.dbstate.db.get_person_from_handle(obj) @@ -208,7 +208,7 @@ class ChildEmbedList(EmbeddedList): sel = SelectPerson(self.dbstate, self.uistate, self.track, _("Select Child"), skip=skip_list) person = sel.run() - + if person: ref = ChildRef() ref.ref = person.get_handle() @@ -252,7 +252,7 @@ class ChildEmbedList(EmbeddedList): p, self.child_ref_edited) except WindowActiveError: pass - + def north_american(self): """ Child inherits name from father @@ -332,9 +332,9 @@ class FastFemaleFilter(object): class EditFamily(EditPrimary): QR_CATEGORY = CATEGORY_QR_FAMILY - + def __init__(self, dbstate, uistate, track, family, callback=None): - + EditPrimary.__init__(self, dbstate, uistate, track, family, dbstate.db.get_family_from_handle, dbstate.db.get_family_from_gramps_id, @@ -342,7 +342,7 @@ class EditFamily(EditPrimary): # look for the scenerio of a child and no parents on a new # family - + if (self.added and not self.obj.get_father_handle() and not self.obj.get_mother_handle() and @@ -379,13 +379,13 @@ class EditFamily(EditPrimary): def _local_init(self): self.build_interface() - + self.added = self.obj.handle is None if self.added: self.obj.handle = create_id() - + self.load_data() - + def _connect_db_signals(self): """ implement from base class DbGUIElement @@ -411,9 +411,9 @@ class EditFamily(EditPrimary): def check_for_family_change(self, handles): """ Callback for family-update signal - 1. This method checks to see if the family shown has been changed. This - is possible eg in the relationship view. If the family was changed, - the view is refreshed and a warning dialog shown to indicate all + 1. This method checks to see if the family shown has been changed. This + is possible eg in the relationship view. If the family was changed, + the view is refreshed and a warning dialog shown to indicate all changes have been lost. If a source/note/event is deleted, this method is called too. This is unfortunate as the displaytabs can track themself a delete and @@ -422,7 +422,7 @@ class EditFamily(EditPrimary): remove/change of children in relationship view reloads the family from db. 2. Changes in other families are of no consequence to the family shown - """ + """ if self.obj.get_handle() in handles: #rebuild data ## Todo: Gallery and note tab are not rebuild ?? @@ -450,7 +450,7 @@ class EditFamily(EditPrimary): # the user WarningDialog( _("Family has changed"), - _("The %(object)s you are editing has changed outside this editor." + _("The %(object)s you are editing has changed outside this editor." " This can be due to a change in one of the main views, for " "example a source used here is deleted in the source view.\n" "To make sure the information shown is still correct, the " @@ -459,9 +459,9 @@ class EditFamily(EditPrimary): def topdata_updated(self, *obj): """ - Callback method called if data shown in top part of family editor + Callback method called if data shown in top part of family editor (a parent, birth/death event of parent) changes - Note: person events shown in the event list are not tracked, the + Note: person events shown in the event list are not tracked, the tabpage itself tracks it """ self.load_data() @@ -497,7 +497,7 @@ class EditFamily(EditPrimary): def build_interface(self): self.width_key = 'interface.family-width' self.height_key = 'interface.family-height' - + self.top = Glade() self.set_window(self.top.toplevel, None, self.get_menu_title()) @@ -511,7 +511,7 @@ class EditFamily(EditPrimary): self.fdeath = self.top.get_object('fdeath') self.fbirth_label = self.top.get_object('label578') self.fdeath_label = self.top.get_object('label579') - + self.mbirth = self.top.get_object('mbirth') self.mdeath = self.top.get_object('mdeath') self.mbirth_label = self.top.get_object('label567') @@ -519,7 +519,7 @@ class EditFamily(EditPrimary): self.mname = self.top.get_object('mname') self.fname = self.top.get_object('fname') - + self.mbutton_index = self.top.get_object('mbutton_index') self.mbutton_add = self.top.get_object('mbutton_add') self.mbutton_del = self.top.get_object('mbutton_del') @@ -553,7 +553,7 @@ class EditFamily(EditPrimary): #allow for a context menu self.set_contexteventbox(self.top.get_object("eventboxtop")) #allow for drag of the family object from eventboxtop - self.contexteventbox.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, + self.contexteventbox.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, [], Gdk.DragAction.COPY) tglist = Gtk.TargetList.new([]) tglist.add(DdTargets.FAMILY_LINK.atom_drag_type, @@ -575,8 +575,8 @@ class EditFamily(EditPrimary): if parent_handle: # Allow drag if not event_box.drag_source_get_target_list(): - event_box.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, - [], + event_box.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, + [], Gdk.DragAction.COPY) tglist = Gtk.TargetList.new([]) tglist.add(DdTargets.PERSON_LINK.atom_drag_type, @@ -624,7 +624,7 @@ class EditFamily(EditPrimary): pass def _setup_fields(self): - + self.private = PrivacyButton( self.top.get_object('private'), self.obj, @@ -635,11 +635,11 @@ class EditFamily(EditPrimary): self.obj.set_gramps_id, self.obj.get_gramps_id, self.db.readonly) - + self.tags = MonitoredTagList( - self.top.get_object("tag_label"), - self.top.get_object("tag_button"), - self.obj.set_tag_list, + self.top.get_object("tag_label"), + self.top.get_object("tag_button"), + self.obj.set_tag_list, self.obj.get_tag_list, self.db, self.uistate, self.track, @@ -666,7 +666,7 @@ class EditFamily(EditPrimary): self.phandles = [mhandle, fhandle] self.phandles.extend(x.ref for x in self.obj.get_child_ref_list()) - + self.phandles = [_f for _f in self.phandles if _f] def get_start_date(self): @@ -688,31 +688,31 @@ class EditFamily(EditPrimary): self.child_tab = self._add_tab(notebook, self.child_list) self.track_ref_for_deletion("child_list") self.track_ref_for_deletion("child_tab") - + self.event_list = EventEmbedList(self.dbstate, - self.uistate, + self.uistate, self.track, self.obj, start_date=self.get_start_date()) self._add_tab(notebook, self.event_list) self.track_ref_for_deletion("event_list") - + self.citation_list = CitationEmbedList(self.dbstate, - self.uistate, + self.uistate, self.track, - self.obj.get_citation_list(), + self.obj.get_citation_list(), self.get_menu_title()) self._add_tab(notebook, self.citation_list) self.track_ref_for_deletion("citation_list") self.attr_list = FamilyAttrEmbedList(self.dbstate, - self.uistate, + self.uistate, self.track, self.obj.get_attribute_list()) self._add_tab(notebook, self.attr_list) self.track_ref_for_deletion("attr_list") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, @@ -721,7 +721,7 @@ class EditFamily(EditPrimary): notetype=NoteType.FAMILY) self._add_tab(notebook, self.note_tab) self.track_ref_for_deletion("note_tab") - + self.gallery_tab = GalleryTab(self.dbstate, self.uistate, self.track, @@ -730,7 +730,7 @@ class EditFamily(EditPrimary): self.track_ref_for_deletion("gallery_tab") self.lds_embed = FamilyLdsEmbedList(self.dbstate, - self.uistate, + self.uistate, self.track, self.obj.get_lds_ord_list()) self._add_tab(notebook, self.lds_embed) @@ -744,7 +744,7 @@ class EditFamily(EditPrimary): def update_father(self, handle): self.load_parent(handle, self.fname, self.fbirth, self.fbirth_label, - self.fdeath, self.fdeath_label, + self.fdeath, self.fdeath_label, self.fbutton_index, self.fbutton_add, self.fbutton_del, self.fbutton_edit) self._update_parent_dnd_handler(self.top.get_object('ftable_event_box'), @@ -754,7 +754,7 @@ class EditFamily(EditPrimary): def update_mother(self, handle): self.load_parent(handle, self.mname, self.mbirth, self.mbirth_label, - self.mdeath, self.mdeath_label, + self.mdeath, self.mdeath_label, self.mbutton_index, self.mbutton_add, self.mbutton_del, self.mbutton_edit) self._update_parent_dnd_handler(self.top.get_object('mtable_event_box'), @@ -766,10 +766,10 @@ class EditFamily(EditPrimary): person = Person() person.set_gender(Person.FEMALE) autoname = config.get('behavior.surname-guessing') - #_("Father's surname"), - #_("None"), - #_("Combination of mother's and father's surname"), - #_("Icelandic style"), + #_("Father's surname"), + #_("None"), + #_("Combination of mother's and father's surname"), + #_("Icelandic style"), if autoname == 2: name = self.latin_american_child("mother") else: @@ -782,10 +782,10 @@ class EditFamily(EditPrimary): person = Person() person.set_gender(Person.MALE) autoname = config.get('behavior.surname-guessing') - #_("Father's surname"), - #_("None"), - #_("Combination of mother's and father's surname"), - #_("Icelandic style"), + #_("Father's surname"), + #_("None"), + #_("Combination of mother's and father's surname"), + #_("Icelandic style"), if autoname == 0: name = self.north_american_child() elif autoname == 2: @@ -799,13 +799,13 @@ class EditFamily(EditPrimary): def new_mother_added(self, person): for i in self.hidden: i.set_sensitive(True) - self.obj.set_mother_handle(person.handle) + self.obj.set_mother_handle(person.handle) self.update_mother(person.handle) def new_father_added(self, person): for i in self.hidden: i.set_sensitive(True) - self.obj.set_father_handle(person.handle) + self.obj.set_father_handle(person.handle) self.update_father(person.handle) def del_mother_clicked(self, obj): @@ -830,27 +830,27 @@ class EditFamily(EditPrimary): self.check_for_existing_family(self.obj.get_father_handle(), person.handle, self.obj.handle) - self.obj.set_mother_handle(person.handle) + self.obj.set_mother_handle(person.handle) self.update_mother(person.handle) def on_change_father(self, selector_window, obj): if obj.__class__ == Person: try: person = obj - self.obj.set_father_handle(person.get_handle()) - self.update_father(person.get_handle()) + self.obj.set_father_handle(person.get_handle()) + self.update_father(person.get_handle()) except: log.warn("Failed to update father: \n" "obj returned from selector was: %s\n" - % (repr(obj),)) + % (repr(obj),)) raise - + else: log.warn( "Object selector returned obj.__class__ = %s, it should " "have been of type %s." % (obj.__class__.__name__, Person.__name__)) - + selector_window.close() def del_father_clicked(self, obj): @@ -874,7 +874,7 @@ class EditFamily(EditPrimary): self.check_for_existing_family(person.handle, self.obj.get_mother_handle(), self.obj.handle) - self.obj.set_father_handle(person.handle) + self.obj.set_father_handle(person.handle) self.update_father(person.handle) def check_for_existing_family(self, father_handle, mother_handle, @@ -995,7 +995,7 @@ class EditFamily(EditPrimary): self.check_for_existing_family(person.handle, self.obj.get_mother_handle(), self.obj.handle) - self.obj.set_father_handle(person.handle) + self.obj.set_father_handle(person.handle) self.update_father(person.handle) def on_drag_motherdata_received(self, widget, context, x, y, sel_data, @@ -1015,7 +1015,7 @@ class EditFamily(EditPrimary): self.check_for_existing_family(self.obj.get_father_handle(), person.handle, self.obj.handle) - self.obj.set_mother_handle(person.handle) + self.obj.set_mother_handle(person.handle) self.update_mother(person.handle) def object_is_empty(self): @@ -1023,7 +1023,7 @@ class EditFamily(EditPrimary): not self.obj.get_mother_handle() and len(self.obj.get_child_ref_list()) == 0 ) - + def save(self, *obj): ## FIXME: how to catch a specific error? #try: @@ -1071,7 +1071,7 @@ class EditFamily(EditPrimary): "Please enter data or cancel the edit.")) self.ok_button.set_sensitive(True) return - + (uses_dupe_id, id) = self._uses_duplicate_id() if uses_dupe_id: msg1 = _("Cannot save family. ID already exists.") @@ -1088,7 +1088,7 @@ class EditFamily(EditPrimary): # This prevents the signals originating in any of the following # commits from being caught by us again. self._cleanup_callbacks() - + if not original and not self.object_is_empty(): with DbTxn(_("Add Family"), self.db) as trans: @@ -1105,7 +1105,7 @@ class EditFamily(EditPrimary): parent = self.db.get_person_from_handle(handle) parent.add_family_handle(self.obj.handle) self.db.commit_person(parent, trans) - + # for each child, add the family handle to the child for ref in self.obj.get_child_ref_list(): child = self.db.get_person_from_handle(ref.ref) @@ -1131,7 +1131,7 @@ class EditFamily(EditPrimary): person = self.db.get_person_from_handle(ref.ref) person.remove_parent_family_handle(self.obj.handle) self.db.commit_person(person, trans) - + # add the family to children which have been added for ref in new_set.difference(orig_set): person = self.db.get_person_from_handle(ref.ref) diff --git a/gramps/gui/editors/editldsord.py b/gramps/gui/editors/editldsord.py index 4f4d8c6dc..26b37ab00 100644 --- a/gramps/gui/editors/editldsord.py +++ b/gramps/gui/editors/editldsord.py @@ -52,7 +52,7 @@ from ..glade import Glade from .editsecondary import EditSecondary from .objectentries import PlaceEntry from .displaytabs import CitationEmbedList,NoteTab -from ..widgets import (PrivacyButton, MonitoredDate, +from ..widgets import (PrivacyButton, MonitoredDate, MonitoredMenu, MonitoredStrMenu) from ..selectors import SelectorFactory @@ -118,7 +118,7 @@ _DATA_MAP = { LdsOrd.STATUS_UNCLEARED, ], } - + #------------------------------------------------------------------------- # # EditLdsOrd class @@ -143,7 +143,7 @@ class EditLdsOrd(EditSecondary): def _local_init(self): self.width_key = 'interface.lds-width' self.height_key = 'interface.lds-height' - + self.top = Glade() self.set_window(self.top.toplevel, self.top.get_object('title'), @@ -241,18 +241,18 @@ class EditLdsOrd(EditSecondary): def _create_tabbed_pages(self): notebook = Gtk.Notebook() - self.citation_list = CitationEmbedList(self.dbstate, self.uistate, - self.track, + self.citation_list = CitationEmbedList(self.dbstate, self.uistate, + self.track, self.obj.get_citation_list()) self._add_tab(notebook, self.citation_list) self.track_ref_for_deletion("citation_list") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, self.obj.get_note_list(), notetype=NoteType.LDS) self._add_tab(notebook, self.note_tab) self.track_ref_for_deletion("note_tab") - + self._setup_notebook_tabs( notebook) notebook.show_all() self.top.get_object('vbox').pack_start(notebook, True, True, 0) @@ -336,8 +336,8 @@ class EditFamilyLdsOrd(EditSecondary): EditSecondary.__init__(self, state, uistate, track, attrib, callback) def _local_init(self): - self.top = Glade() - self.set_window(self.top.toplevel, + self.top = Glade() + self.set_window(self.top.toplevel, self.top.get_object('title'), _('LDS Ordinance Editor')) self.share_btn = self.top.get_object('share_place') @@ -408,18 +408,18 @@ class EditFamilyLdsOrd(EditSecondary): def _create_tabbed_pages(self): notebook = Gtk.Notebook() - self.srcref_list = CitationEmbedList(self.dbstate,self.uistate, - self.track, + self.srcref_list = CitationEmbedList(self.dbstate,self.uistate, + self.track, self.obj.get_citation_list()) self._add_tab(notebook, self.srcref_list) self.track_ref_for_deletion("srcref_list") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, self.obj.get_note_list(), notetype=NoteType.LDS) self._add_tab(notebook, self.note_tab) self.track_ref_for_deletion("note_tab") - + notebook.show_all() self.top.get_object('vbox').pack_start(notebook, True, True, 0) diff --git a/gramps/gui/editors/editlink.py b/gramps/gui/editors/editlink.py index 33aa9aef8..a618a30c8 100644 --- a/gramps/gui/editors/editlink.py +++ b/gramps/gui/editors/editlink.py @@ -45,7 +45,7 @@ OBJECT_MAP = { MEDIA: "Media", NOTE: "Note", PERSON: "Person", - PLACE: "Place", + PLACE: "Place", REPOSITORY: "Repository", SOURCE: "Source", } @@ -76,8 +76,8 @@ class EditLink(ManagedWindow): _('Link Editor')) self.uri_list = self.top.get_object('link_type') for text in [_("Internet Address"), # 0 this order range above - _("Event"), # 1 - _("Family"), # 2 + _("Event"), # 1 + _("Family"), # 2 _("Media"), # 3 _("Note"), # 4 _("Person"), # 5 @@ -116,7 +116,7 @@ class EditLink(ManagedWindow): # set texts: self.selected.set_text(self.display_link( object_class, prop, value)) - self.url_link.set_text("gramps://%s/%s/%s" % + self.url_link.set_text("gramps://%s/%s/%s" % (object_class, prop, value)) else: self.uri_list.set_active(WEB) @@ -135,32 +135,32 @@ class EditLink(ManagedWindow): def display_link(self, obj_class, prop, value): return self.simple_access.display(obj_class, prop, value) - def _on_new_callback(self, obj): + def _on_new_callback(self, obj): object_class = obj.__class__.__name__ self.selected.set_text(self.display_link( object_class, "handle", obj.handle)) - self.url_link.set_text("gramps://%s/%s/%s" % + self.url_link.set_text("gramps://%s/%s/%s" % (object_class, "handle", obj.handle)) def _on_new(self, widget): from ..editors import EditObject object_class = OBJECT_MAP[self.uri_list.get_active()] - EditObject(self.dbstate, - self.uistate, - self.track, + EditObject(self.dbstate, + self.uistate, + self.track, object_class, callback=self._on_new_callback) - + def _on_edit_one(self, widget): from ..editors import EditObject uri = self.url_link.get_text() if uri.startswith("gramps://"): obj_class, prop, value = uri[9:].split("/", 2) - EditObject(self.dbstate, - self.uistate, - self.track, + EditObject(self.dbstate, + self.uistate, + self.track, obj_class, prop, value) - + def _on_pick_one(self, widget): from ..selectors import SelectorFactory object_class = OBJECT_MAP[self.uri_list.get_active()] @@ -172,12 +172,12 @@ class EditLink(ManagedWindow): if object_class == obj_class: if prop == "handle": default = value - elif (prop == "gramps_id" and + elif (prop == "gramps_id" and object_class in self.dbstate.db.get_table_names()): person = self.dbstate.db.get_table_metadata(object_class)["gramps_id_func"](value) if person: default = person.handle - d = Select(self.dbstate, self.uistate, self.track, + d = Select(self.dbstate, self.uistate, self.track, default=default) result = d.run() @@ -186,7 +186,7 @@ class EditLink(ManagedWindow): value = result.handle self.selected.set_text(self.display_link( object_class, prop, value)) - self.url_link.set_text("gramps://%s/%s/%s" % + self.url_link.set_text("gramps://%s/%s/%s" % (object_class, prop, value)) def _on_type_changed(self, widget): @@ -207,14 +207,14 @@ class EditLink(ManagedWindow): return self.url_link.get_text() else: return self.url_link.get_text() - + def _connect_signals(self): self.define_cancel_button(self.top.get_object('button125')) self.ok_button = self.top.get_object('button124') self.define_ok_button(self.ok_button, self.save) self.define_help_button(self.top.get_object('button130')) self.update_ui(self.url_link) - + def build_menu_names(self, obj): etitle =_('Link Editor') return (etitle, etitle) diff --git a/gramps/gui/editors/editlocation.py b/gramps/gui/editors/editlocation.py index 2ad4aa4d4..b1564ff52 100644 --- a/gramps/gui/editors/editlocation.py +++ b/gramps/gui/editors/editlocation.py @@ -61,43 +61,43 @@ class EditLocation(EditSecondary): self.obj.set_locality, self.obj.get_locality, self.db.readonly) - + self.city = MonitoredEntry( self.top.get_object("city"), self.obj.set_city, self.obj.get_city, self.db.readonly) - + self.state = MonitoredEntry( self.top.get_object("state"), self.obj.set_state, self.obj.get_state, self.db.readonly) - + self.postal = MonitoredEntry( self.top.get_object("postal"), self.obj.set_postal_code, self.obj.get_postal_code, self.db.readonly) - + self.phone = MonitoredEntry( self.top.get_object("phone"), self.obj.set_phone, self.obj.get_phone, self.db.readonly) - + self.parish = MonitoredEntry( self.top.get_object("parish"), self.obj.set_parish, self.obj.get_parish, self.db.readonly) - + self.county = MonitoredEntry( self.top.get_object("county"), self.obj.set_county, self.obj.get_county, self.db.readonly) - + self.country = MonitoredEntry( self.top.get_object("country"), self.obj.set_country, @@ -108,7 +108,7 @@ class EditLocation(EditSecondary): self.define_cancel_button(self.top.get_object('button119')) self.define_ok_button(self.top.get_object('button118'),self.save) self.define_help_button(self.top.get_object('button128')) - + def save(self,*obj): if self.callback: self.callback(self.obj) diff --git a/gramps/gui/editors/editmedia.py b/gramps/gui/editors/editmedia.py index 45851e3c1..bb83c2aa7 100644 --- a/gramps/gui/editors/editmedia.py +++ b/gramps/gui/editors/editmedia.py @@ -68,11 +68,11 @@ class EditMedia(EditPrimary): def __init__(self, dbstate, uistate, track, obj, callback=None): EditPrimary.__init__(self, dbstate, uistate, track, obj, - dbstate.db.get_object_from_handle, + dbstate.db.get_object_from_handle, dbstate.db.get_object_from_gramps_id, callback) if not self.obj.get_handle(): #show the addmedia dialog immediately, with track of parent. - AddMediaObject(dbstate, self.uistate, self.track, self.obj, + AddMediaObject(dbstate, self.uistate, self.track, self.obj, self._update_addmedia) def empty_object(self): @@ -96,9 +96,9 @@ class EditMedia(EditPrimary): assert(self.obj) self.width_key = 'interface.media-width' self.height_key = 'interface.media-height' - + self.glade = Glade() - self.set_window(self.glade.toplevel, + self.set_window(self.glade.toplevel, None, self.get_menu_title()) def _connect_signals(self): @@ -108,7 +108,7 @@ class EditMedia(EditPrimary): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('media-rebuild', self._do_close) @@ -125,15 +125,15 @@ class EditMedia(EditPrimary): self.obj.set_description, self.obj.get_description, self.db.readonly) - + self.gid = MonitoredEntry(self.glade.get_object("gid"), - self.obj.set_gramps_id, + self.obj.set_gramps_id, self.obj.get_gramps_id, self.db.readonly) self.tags = MonitoredTagList( - self.glade.get_object("tag_label"), - self.glade.get_object("tag_button"), - self.obj.set_tag_list, + self.glade.get_object("tag_label"), + self.glade.get_object("tag_button"), + self.obj.set_tag_list, self.obj.get_tag_list, self.db, self.uistate, self.track, @@ -145,7 +145,7 @@ class EditMedia(EditPrimary): self.pixmap = self.glade.get_object("pixmap") ebox = self.glade.get_object('eventbox') ebox.connect('button-press-event', self.button_press_event) - + self.mimetext = self.glade.get_object("type") self.setup_filepath() self.determine_mime() @@ -175,7 +175,7 @@ class EditMedia(EditPrimary): mtype = self.obj.get_mime_type() if mtype: pb = get_thumbnail_image( - media_path_full(self.db, self.obj.get_path()), + media_path_full(self.db, self.obj.get_path()), mtype) self.pixmap.set_from_pixbuf(pb) else: @@ -196,7 +196,7 @@ class EditMedia(EditPrimary): self.citation_tab = CitationEmbedList(self.dbstate, self.uistate, self.track, - self.obj.get_citation_list(), + self.obj.get_citation_list(), self.get_menu_title()) self._add_tab(notebook, self.citation_tab) self.track_ref_for_deletion("citation_tab") @@ -207,11 +207,11 @@ class EditMedia(EditPrimary): self.obj.get_attribute_list()) self._add_tab(notebook, self.attr_tab) self.track_ref_for_deletion("attr_tab") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, - self.obj.get_note_list(), + self.obj.get_note_list(), notetype=NoteType.MEDIA) self._add_tab(notebook, self.note_tab) self.track_ref_for_deletion("note_tab") @@ -247,7 +247,7 @@ class EditMedia(EditPrimary): self.determine_mime() path = self.file_path.get_text() self.obj.set_path(conv_to_unicode(path)) - AddMediaObject(self.dbstate, self.uistate, self.track, self.obj, + AddMediaObject(self.dbstate, self.uistate, self.track, self.obj, self._update_addmedia) def _update_addmedia(self, obj): @@ -286,7 +286,7 @@ class EditMedia(EditPrimary): name = prim_object.get_description() msg1 = _("Cannot save media object. ID already exists.") msg2 = _("You have attempted to use the existing Gramps ID with " - "value %(id)s. This value is already used by '" + "value %(id)s. This value is already used by '" "%(prim_object)s'. Please enter a different ID or leave " "blank to get the next available ID value.") % { 'id' : id, 'prim_object' : name } @@ -298,15 +298,15 @@ class EditMedia(EditPrimary): full_path = media_path_full(self.db, path) if os.path.isfile(full_path): self.determine_mime() - else: - msg1 = _("There is no media matching the current path value!") - msg2 = _("You have attempted to use the path with " - "value '%(path)s'. This path does not exist!" - " Please enter a different path") % { - 'path' : path } - ErrorDialog(msg1, msg2) - self.ok_button.set_sensitive(True) - return + else: + msg1 = _("There is no media matching the current path value!") + msg2 = _("You have attempted to use the path with " + "value '%(path)s'. This path does not exist!" + " Please enter a different path") % { + 'path' : path } + ErrorDialog(msg1, msg2) + self.ok_button.set_sensitive(True) + return self.obj.set_path(path) @@ -332,7 +332,7 @@ class EditMedia(EditPrimary): entered date when importing from a XML file, so we can get an incorrect fail. """ - + if self.db.readonly: return False elif self.obj.handle: @@ -353,11 +353,11 @@ class DeleteMediaQuery(object): self.uistate = uistate self.media_handle = media_handle self.the_lists = the_lists - + def query_response(self): with DbTxn(_("Remove Media Object"), self.db) as trans: self.db.disable_signals() - + (person_list, family_list, event_list, place_list, source_list, citation_list) = self.the_lists diff --git a/gramps/gui/editors/editmediaref.py b/gramps/gui/editors/editmediaref.py index 7d9145499..37abc4daf 100644 --- a/gramps/gui/editors/editmediaref.py +++ b/gramps/gui/editors/editmediaref.py @@ -73,7 +73,7 @@ class EditMediaRef(EditReference): media_ref, update) if not self.source.get_handle(): #show the addmedia dialog immediately, with track of parent. - AddMediaObject(state, self.uistate, self.track, self.source, + AddMediaObject(state, self.uistate, self.track, self.source, self._update_addmedia) def _local_init(self): @@ -93,7 +93,7 @@ class EditMediaRef(EditReference): self.track_ref_for_deletion("notebook_ref") #recreate start page as GrampsTab self.notebook_ref.remove_page(0) - self.reftab = RefTab(self.dbstate, self.uistate, self.track, + self.reftab = RefTab(self.dbstate, self.uistate, self.track, _('General'), tblref) self.track_ref_for_deletion("reftab") tblref = self.top.get_object('table2') @@ -101,7 +101,7 @@ class EditMediaRef(EditReference): #recreate start page as GrampsTab self.notebook_shared.remove_page(0) self.track_ref_for_deletion("notebook_shared") - self.primtab = RefTab(self.dbstate, self.uistate, self.track, + self.primtab = RefTab(self.dbstate, self.uistate, self.track, _('_General'), tblref) self.track_ref_for_deletion("primtab") self.rect_pixbuf = None @@ -152,18 +152,18 @@ class EditMediaRef(EditReference): self.selection.load_image('') def _setup_fields(self): - + ebox_shared = self.top.get_object('eventbox') ebox_shared.connect('button-press-event', self.button_press_event) self.pixmap = self.top.get_object("pixmap") self.mimetext = self.top.get_object("type") self.track_ref_for_deletion("mimetext") - + coord = self.source_ref.get_rectangle() #upgrade path: set invalid (from eg old db) to none if coord is not None and coord in ( - (None,)*4, + (None,)*4, (0, 0, 100, 100), (coord[0], coord[1])*2 ): @@ -173,7 +173,7 @@ class EditMediaRef(EditReference): self.rectangle = coord else: self.rectangle = (0, 0, 100, 100) - + self.selection = SelectionWidget() self.selection.set_multiple_selection(False) self.selection.connect("region-modified", self.region_modified) @@ -185,7 +185,7 @@ class EditMediaRef(EditReference): self.setup_filepath() self.determine_mime() - + corners = ["corner1_x", "corner1_y", "corner2_x", "corner2_y"] if coord and isinstance(coord, tuple): @@ -194,11 +194,11 @@ class EditMediaRef(EditReference): else: for corner, value in zip(corners, [0, 0, 100, 100]): self.top.get_object(corner).set_value(value) - + if self.dbstate.db.readonly: for corner in corners: self.top.get_object(corner).set_sensitive(False) - + self.corner1_x_spinbutton = MonitoredSpinButton( self.top.get_object("corner1_x"), self.set_corner1_x, @@ -254,18 +254,18 @@ class EditMediaRef(EditReference): self.source.set_path, self.source.get_path, self.db.readonly) - + self.date_field = MonitoredDate( self.top.get_object("date_entry"), self.top.get_object("date_edit"), self.source.get_date_object(), self.uistate, self.track, self.db.readonly) - + self.tags = MonitoredTagList( - self.top.get_object("tag_label"), - self.top.get_object("tag_button"), - self.source.set_tag_list, + self.top.get_object("tag_label"), + self.top.get_object("tag_button"), + self.source.set_tag_list, self.source.get_tag_list, self.db, self.uistate, self.track, @@ -283,10 +283,10 @@ class EditMediaRef(EditReference): Callback for the signal handling of the spinbutton for the first corner x coordinate of the subsection. Updates the subsection thumbnail using the given value - + @param value: the first corner x coordinate of the subsection in int """ - + self.rectangle = (value,) + self.rectangle[1:] self.update_region() @@ -295,10 +295,10 @@ class EditMediaRef(EditReference): Callback for the signal handling of the spinbutton for the first corner y coordinate of the subsection. Updates the subsection thumbnail using the given value - + @param value: the first corner y coordinate of the subsection in int """ - + self.rectangle = self.rectangle[:1] + (value,) + self.rectangle[2:] self.update_region() @@ -307,10 +307,10 @@ class EditMediaRef(EditReference): Callback for the signal handling of the spinbutton for the second corner x coordinate of the subsection. Updates the subsection thumbnail using the given value - + @param value: the second corner x coordinate of the subsection in int """ - + self.rectangle = self.rectangle[:2] + (value,) + self.rectangle[3:] self.update_region() @@ -319,29 +319,29 @@ class EditMediaRef(EditReference): Callback for the signal handling of the spinbutton for the second corner y coordinate of the subsection. Updates the subsection thumbnail using the given value - + @param value: the second corner y coordinate of the subsection in int """ - + self.rectangle = self.rectangle[:3] + (value,) self.update_region() def get_corner1_x(self): """ - Callback for the signal handling of the spinbutton for the first corner + Callback for the signal handling of the spinbutton for the first corner x coordinate of the subsection. - - @returns: the first corner x coordinate of the subsection or 0 if + + @returns: the first corner x coordinate of the subsection or 0 if there is no selection """ return self.rectangle[0] def get_corner1_y(self): """ - Callback for the signal handling of the spinbutton for the first corner + Callback for the signal handling of the spinbutton for the first corner y coordinate of the subsection. - - @returns: the first corner y coordinate of the subsection or 0 if + + @returns: the first corner y coordinate of the subsection or 0 if there is no selection """ return self.rectangle[1] @@ -350,8 +350,8 @@ class EditMediaRef(EditReference): """ Callback for the signal handling of the spinbutton for the second corner x coordinate of the subsection. - - @returns: the second corner x coordinate of the subsection or 100 if + + @returns: the second corner x coordinate of the subsection or 100 if there is no selection """ return self.rectangle[2] @@ -360,8 +360,8 @@ class EditMediaRef(EditReference): """ Callback for the signal handling of the spinbutton for the second corner x coordinate of the subsection. - - @returns: the second corner x coordinate of the subsection or 100 if + + @returns: the second corner x coordinate of the subsection or 100 if there is no selection """ return self.rectangle[3] @@ -398,7 +398,7 @@ class EditMediaRef(EditReference): else: submenu_label = _('New Media') return (_('Media Reference Editor'),submenu_label) - + def button_press_event(self, obj, event): if event.button==1 and event.type == Gdk.EventType._2BUTTON_PRESS: photo_path = media_path_full(self.db, self.source.get_path()) @@ -415,7 +415,7 @@ class EditMediaRef(EditReference): self.determine_mime() self.update_checksum() self.draw_preview() - + def update_checksum(self): self.uistate.set_busy_cursor(True) media_path = media_path_full(self.dbstate.db, self.source.get_path()) @@ -426,7 +426,7 @@ class EditMediaRef(EditReference): self.determine_mime() path = self.file_path.get_text() self.source.set_path(conv_to_unicode(path)) - AddMediaObject(self.dbstate, self.uistate, self.track, self.source, + AddMediaObject(self.dbstate, self.uistate, self.track, self.source, self._update_addmedia) def _connect_signals(self): @@ -435,7 +435,7 @@ class EditMediaRef(EditReference): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('media-rebuild', self.close) @@ -479,7 +479,7 @@ class EditMediaRef(EditReference): self.src_srcref_list = CitationEmbedList(self.dbstate, self.uistate, - self.track, + self.track, self.source.get_citation_list()) self._add_tab(notebook_src, self.src_srcref_list) self.track_ref_for_deletion("src_srcref_list") @@ -508,7 +508,7 @@ class EditMediaRef(EditReference): else: if self.check_for_duplicate_id('Media'): return - with DbTxn(_("Add Media Object (%s)") % + with DbTxn(_("Add Media Object (%s)") % self.source.get_description(), self.db) as trans: self.db.add_object(self.source, trans) @@ -523,7 +523,7 @@ class EditMediaRef(EditReference): #do not set unset or invalid coord if coord is not None and coord in ( - (None,)*4, + (None,)*4, (0, 0, 100, 100), (coord[0], coord[1])*2 ): diff --git a/gramps/gui/editors/editname.py b/gramps/gui/editors/editname.py index f4af32eb5..a69694ae5 100644 --- a/gramps/gui/editors/editname.py +++ b/gramps/gui/editors/editname.py @@ -50,9 +50,9 @@ from gramps.gen.display.name import displayer as name_displayer from .editsecondary import EditSecondary from gramps.gen.lib import NoteType from .displaytabs import GrampsTab, CitationEmbedList, NoteTab, SurnameTab -from ..widgets import (MonitoredEntry, MonitoredMenu, MonitoredDate, +from ..widgets import (MonitoredEntry, MonitoredMenu, MonitoredDate, MonitoredDataType, PrivacyButton) -from ..glade import Glade +from ..glade import Glade from gramps.gen.errors import ValidationError #------------------------------------------------------------------------- @@ -115,22 +115,22 @@ class EditName(EditSecondary): def _local_init(self): self.width_key = 'interface.name-width' self.height_key = 'interface.name-height' - + self.top = Glade() - + self.set_window(self.top.toplevel, None, _("Name Editor")) tblgnam = self.top.get_object('table23') notebook = self.top.get_object('notebook') hbox_surn = self.top.get_object('hboxmultsurnames') - hbox_surn.set_size_request(-1, + hbox_surn.set_size_request(-1, int(config.get('interface.surname-box-height'))) - hbox_surn.pack_start(SurnameTab(self.dbstate, self.uistate, self.track, + hbox_surn.pack_start(SurnameTab(self.dbstate, self.uistate, self.track, self.obj, top_label=None), True, True, 0) #recreate start page as GrampsTab notebook.remove_page(0) - self.gennam = GeneralNameTab(self.dbstate, self.uistate, self.track, + self.gennam = GeneralNameTab(self.dbstate, self.uistate, self.track, _('_General'), tblgnam) self.original_group_as = self.obj.get_group_as() @@ -141,7 +141,7 @@ class EditName(EditSecondary): self.group_over = self.top.get_object('group_over') self.group_over.connect('toggled',self.on_group_over_toggled) self.group_over.set_sensitive(not self.db.readonly) - + self.toggle_dirty = False def _post_init(self): @@ -163,7 +163,7 @@ class EditName(EditSecondary): self.define_ok_button(self.top.get_object('button118'), self.save) def _validate_call(self, widget, text): - """ a callname must be a part of the given name, see if this is the + """ a callname must be a part of the given name, see if this is the case """ validcall = self.given_field.obj.get_text().split() dummy = copy(validcall) @@ -186,10 +186,10 @@ class EditName(EditSecondary): self.group_as.force_value(self.global_group_as) else : self.group_as.force_value(self.obj.get_primary_surname().get_surname()) - + format_list = [(name, number) for (number, name,fmt_str,act) in name_displayer.get_name_format(also_default=True)] - + self.sort_as = MonitoredMenu( self.top.get_object('sort_as'), self.obj.set_sort_as, @@ -232,15 +232,15 @@ class EditName(EditSecondary): self.db.readonly) self.nick = MonitoredEntry( - self.top.get_object("nickname"), - self.obj.set_nick_name, - self.obj.get_nick_name, + self.top.get_object("nickname"), + self.obj.set_nick_name, + self.obj.get_nick_name, self.db.readonly) self.famnick = MonitoredEntry( - self.top.get_object("familynickname"), - self.obj.set_family_nick_name, - self.obj.get_family_nick_name, + self.top.get_object("familynickname"), + self.obj.set_family_nick_name, + self.obj.get_family_nick_name, self.db.readonly) #self.surname_field = MonitoredEntry( @@ -253,7 +253,7 @@ class EditName(EditSecondary): self.date = MonitoredDate( self.top.get_object("date_entry"), - self.top.get_object("date_stat"), + self.top.get_object("date_stat"), self.obj.get_date_object(), self.uistate, self.track, @@ -266,11 +266,11 @@ class EditName(EditSecondary): self.db.readonly, self.db.get_name_types(), ) - + self.privacy = PrivacyButton( self.top.get_object("priv"), self.obj, self.db.readonly) - + def _create_tabbed_pages(self): notebook = self.top.get_object("notebook") @@ -278,12 +278,12 @@ class EditName(EditSecondary): self._add_tab(notebook, self.gennam) self.track_ref_for_deletion("gennam") - self.srcref_list = CitationEmbedList(self.dbstate, self.uistate, - self.track, + self.srcref_list = CitationEmbedList(self.dbstate, self.uistate, + self.track, self.obj.get_citation_list()) self._add_tab(notebook, self.srcref_list) self.track_ref_for_deletion("srcref_list") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, self.obj.get_note_list(), notetype=NoteType.PERSONNAME) @@ -291,9 +291,9 @@ class EditName(EditSecondary): self.track_ref_for_deletion("note_tab") self._setup_notebook_tabs( notebook) - + def _get_global_grouping(self, srn): - """ we need info on the global grouping of the surname on init, + """ we need info on the global grouping of the surname on init, and on change of surname """ self.global_group_as = self.db.get_name_group_mapping(srn) @@ -302,7 +302,7 @@ class EditName(EditSecondary): self.global_group_set = False else: self.global_group_set = True - + def build_menu_names(self, name): if name: @@ -328,7 +328,7 @@ class EditName(EditSecondary): self.toggle_dirty = True self.group_as.force_value(self.global_group_as) elif self.group_over.get_active() and self.toggle_dirty: - #changing surname caused active group_over in past, change + #changing surname caused active group_over in past, change # group_over as we type if self.global_group_set : self.group_as.force_value(self.global_group_as) @@ -337,7 +337,7 @@ class EditName(EditSecondary): self.group_as.force_value(name) self.group_over.set_active(False) self.group_as.enable(False) - + def on_group_over_toggled(self, obj): """ group over changes, if activated, enable edit, if unactivated, go back to surname/global_group_as. @@ -345,7 +345,7 @@ class EditName(EditSecondary): self.toggle_dirty = False #enable group as box self.group_as.enable(obj.get_active()) - + if not obj.get_active(): if self.global_group_set: self.group_as.set_text(self.global_group_as) @@ -354,11 +354,11 @@ class EditName(EditSecondary): self.group_as.set_text(surname) def save(self, *obj): - """Save the name setting. All is ok, except grouping. We need to - consider: + """Save the name setting. All is ok, except grouping. We need to + consider: 1/ global set, not local set --> unset (ask if global unset) 2/ global set, local set --> unset (only local unset!) - 3/ not global set, local set + 3/ not global set, local set or not global set, not local set --> unset 4/ not local set, not global set or not local set, global set --> set val (ask global or local) @@ -369,7 +369,7 @@ class EditName(EditSecondary): surname = self.obj.get_primary_surname().get_surname() group_as= self.obj.get_group_as() grouping_active = self.group_over.get_active() - + if not grouping_active : #user wants to group with surname if self.global_group_set and not self.original_group_set : @@ -392,7 +392,7 @@ class EditName(EditSecondary): closeit = False elif self.global_group_set and self.original_group_set: #we change it only back to surname locally, so store group_as - # Note: if all surnames are locally changed to surname, we + # Note: if all surnames are locally changed to surname, we # should actually unsed the global group here .... pass else : @@ -405,7 +405,7 @@ class EditName(EditSecondary): #this might be creation of group link, or change of group link if self.global_group_as != group_as: from ..dialog import QuestionDialog2 - + q = QuestionDialog2( _("Group all people with the same name?"), _("You have the choice of grouping all people with the " @@ -434,14 +434,14 @@ class EditName(EditSecondary): #keep original value, no original group self.obj.set_group_as("") elif not self.global_group_set : - #don't ask user, group was set locally before, + #don't ask user, group was set locally before, #change it locally only if group_as == surname : #remove grouping self.obj.set_group_as("") else: pass - + else: #locally set group and global group set if group_as == self.global_group_as : diff --git a/gramps/gui/editors/editnote.py b/gramps/gui/editors/editnote.py index 72f9e7b40..29025ff52 100644 --- a/gramps/gui/editors/editnote.py +++ b/gramps/gui/editors/editnote.py @@ -49,7 +49,7 @@ from gi.repository import Pango from gramps.gen.config import config from .editprimary import EditPrimary from .displaytabs import GrampsTab, NoteBackRefList -from ..widgets import (MonitoredDataType, MonitoredCheckbox, +from ..widgets import (MonitoredDataType, MonitoredCheckbox, MonitoredEntry, PrivacyButton, MonitoredTagList) from gramps.gen.lib import Note from gramps.gen.db import DbTxn @@ -106,28 +106,28 @@ class NoteTab(GrampsTab): #------------------------------------------------------------------------- class EditNote(EditPrimary): - def __init__(self, dbstate, uistate, track, note, callback=None, + def __init__(self, dbstate, uistate, track, note, callback=None, callertitle = None, extratype = None): """Create an EditNote window. Associate a note with the window. - - @param callertitle: Text passed by calling object to add to title + + @param callertitle: Text passed by calling object to add to title @type callertitle: str @param extratype: Extra L{NoteType} values to add to the default types. They are removed from the ignorelist of L{NoteType}. @type extratype: list of int - + """ self.callertitle = callertitle self.extratype = extratype - EditPrimary.__init__(self, dbstate, uistate, track, note, - dbstate.db.get_note_from_handle, + EditPrimary.__init__(self, dbstate, uistate, track, note, + dbstate.db.get_note_from_handle, dbstate.db.get_note_from_gramps_id, callback) def empty_object(self): """Return an empty Note object for comparison for changes. - + It is used by the base class L{EditPrimary}. - + """ empty_note = Note(); if self.extratype: @@ -149,24 +149,24 @@ class EditNote(EditPrimary): 'context' : self.callertitle } else : - title = _('New Note') - + title = _('New Note') + return title - + def get_custom_notetypes(self): return self.dbstate.db.get_note_types() def _local_init(self): """Local initialization function. - + Perform basic initialization, including setting up widgets and the glade interface. It is called by the base class L{EditPrimary}, and overridden here. - + """ self.width_key = 'interface.note-width' self.height_key = 'interface.note-height' - + self.top = Glade() win = self.top.toplevel @@ -177,12 +177,12 @@ class EditNote(EditPrimary): notebook = self.top.get_object('note_notebook') #recreate start page as GrampsTab notebook.remove_page(0) - self.ntab = NoteTab(self.dbstate, self.uistate, self.track, + self.ntab = NoteTab(self.dbstate, self.uistate, self.track, _('_Note'), vboxnote) self.track_ref_for_deletion("ntab") - + self.build_interface() - + def _setup_fields(self): """Get control widgets and attach them to Note's attributes.""" self.type_selector = MonitoredDataType( @@ -199,17 +199,17 @@ class EditNote(EditPrimary): self.obj.set_format, self.obj.get_format, readonly = self.db.readonly) - + self.gid = MonitoredEntry( self.top.get_object('id'), self.obj.set_gramps_id, self.obj.get_gramps_id, self.db.readonly) - + self.tags = MonitoredTagList( - self.top.get_object("tag_label"), - self.top.get_object("tag_button"), - self.obj.set_tag_list, + self.top.get_object("tag_label"), + self.top.get_object("tag_button"), + self.obj.set_tag_list, self.obj.get_tag_list, self.db, self.uistate, self.track, @@ -218,12 +218,12 @@ class EditNote(EditPrimary): self.priv = PrivacyButton( self.top.get_object("private"), self.obj, self.db.readonly) - + def _connect_signals(self): """Connects any signals that need to be connected. - + Called by the init routine of the base class L{EditPrimary}. - + """ self.define_ok_button(self.top.get_object('ok'), self.save) self.define_cancel_button(self.top.get_object('cancel')) @@ -231,7 +231,7 @@ class EditNote(EditPrimary): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('note-rebuild', self._do_close) @@ -251,7 +251,7 @@ class EditNote(EditPrimary): self.backref_tab = self._add_tab(notebook, self.rlist) self.track_ref_for_deletion("rlist") self.track_ref_for_deletion("backref_tab") - + self._setup_notebook_tabs(notebook) def build_interface(self): @@ -263,7 +263,7 @@ class EditNote(EditPrimary): if not self.dbstate.db.readonly: vbox = self.top.get_object('container') vbox.pack_start(self.texteditor.get_toolbar(), False, False, 0) - + # setup initial values for textview and textbuffer if self.obj: self.empty = False @@ -295,16 +295,16 @@ class EditNote(EditPrimary): def save(self, *obj): """Save the data.""" self.ok_button.set_sensitive(False) - + self.update_note() - + if self.object_is_empty(): - ErrorDialog(_("Cannot save note"), + ErrorDialog(_("Cannot save note"), _("No data exists for this note. Please " "enter data or cancel the edit.")) self.ok_button.set_sensitive(True) return - + (uses_dupe_id, id) = self._uses_duplicate_id() if uses_dupe_id: msg1 = _("Cannot save note. ID already exists.") @@ -316,7 +316,7 @@ class EditNote(EditPrimary): ErrorDialog(msg1, msg2) self.ok_button.set_sensitive(True) return - + with DbTxn('', self.db) as trans: if not self.obj.get_handle(): self.db.add_note(self.obj, trans) @@ -327,7 +327,7 @@ class EditNote(EditPrimary): self.db.commit_note(self.obj, trans) msg = _("Edit Note") trans.set_description(msg) - + if self.callback: self.callback(self.obj.get_handle()) self.close() @@ -343,7 +343,7 @@ class DeleteNoteQuery(object): with DbTxn(_("Delete Note (%s)") % self.note.get_gramps_id(), self.db) as trans: self.db.disable_signals() - + (person_list, family_list, event_list, place_list, source_list, citation_list, media_list, repo_list) = self.the_lists diff --git a/gramps/gui/editors/editperson.py b/gramps/gui/editors/editperson.py index 9548b2f31..a807ca353 100644 --- a/gramps/gui/editors/editperson.py +++ b/gramps/gui/editors/editperson.py @@ -259,8 +259,8 @@ class EditPerson(EditPrimary): tglist.add(DdTargets.PERSON_LINK.atom_drag_type, DdTargets.PERSON_LINK.target_flags, DdTargets.PERSON_LINK.app_id) - self.contexteventbox.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, - [], + self.contexteventbox.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, + [], Gdk.DragAction.COPY) self.contexteventbox.drag_source_set_target_list(tglist) self.contexteventbox.drag_source_set_icon_name('gramps-person') @@ -484,7 +484,7 @@ class EditPerson(EditPrimary): self.srcref_list = CitationEmbedList(self.dbstate, self.uistate, self.track, - self.obj.get_citation_list(), + self.obj.get_citation_list(), self.get_menu_title()) self._add_tab(notebook, self.srcref_list) self.track_ref_for_deletion("srcref_list") @@ -971,8 +971,8 @@ class EditPerson(EditPrimary): Load the person's main photo using the Thumbnailer. """ pixbuf = get_thumbnail_image( - media_path_full(self.dbstate.db, - obj.get_path()), + media_path_full(self.dbstate.db, + obj.get_path()), obj.get_mime_type(), ref.get_rectangle()) diff --git a/gramps/gui/editors/editpersonref.py b/gramps/gui/editors/editpersonref.py index 0bdf57706..a86697515 100644 --- a/gramps/gui/editors/editpersonref.py +++ b/gramps/gui/editors/editpersonref.py @@ -79,9 +79,9 @@ class EditPersonRef(EditSecondary): def _local_init(self): self.width_key = 'interface.person-ref-width' self.height_key = 'interface.person-ref-height' - + self.top = Glade() - + self.set_window(self.top.toplevel, self.top.get_object("title"), _('Person Reference Editor')) @@ -104,7 +104,7 @@ class EditPersonRef(EditSecondary): self.label_event_box = self.top.get_object('person_event_box') # Set the drag action from the label if self.obj.ref: - self.label_event_box.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, + self.label_event_box.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, [], Gdk.DragAction.COPY) tglist = Gtk.TargetList.new([]) tglist.add(DdTargets.PERSON_LINK.atom_drag_type, @@ -121,7 +121,7 @@ class EditPersonRef(EditSecondary): if self.obj.ref: p = self.dbstate.db.get_person_from_handle(self.obj.ref) self.person_label.set_text(name_displayer.display(p)) - + self.street = MonitoredEntry( self.top.get_object("relationship"), self.obj.set_relation, @@ -141,7 +141,7 @@ class EditPersonRef(EditSecondary): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('person-rebuild', self.close) @@ -149,7 +149,7 @@ class EditPersonRef(EditSecondary): def check_for_close(self, handles): """ - Callback method for delete signals. + Callback method for delete signals. If there is a delete signal of the primary object we are editing, the editor (and all child windows spawned) should be closed """ @@ -178,7 +178,7 @@ class EditPersonRef(EditSecondary): (drag_type, idval, handle, val) = pickle.loads(sel_data.get_data()) person = self.db.get_person_from_handle(handle) self.update_person(person) - + def drag_data_get(self, widget, context, sel_data, info, time): # get the selected object, returning if not is defined if info == DdTargets.PERSON_LINK.app_id: @@ -190,11 +190,11 @@ class EditPersonRef(EditSecondary): Create the notebook tabs and inserts them into the main window. """ - + notebook = Gtk.Notebook() - + self.srcref_list = CitationEmbedList(self.dbstate, self.uistate, - self.track, + self.track, self.obj.get_citation_list()) self._add_tab(notebook, self.srcref_list) self.track_ref_for_deletion("srcref_list") diff --git a/gramps/gui/editors/editplace.py b/gramps/gui/editors/editplace.py index 9bf84cbc3..8b33fe259 100644 --- a/gramps/gui/editors/editplace.py +++ b/gramps/gui/editors/editplace.py @@ -67,7 +67,7 @@ class EditPlace(EditPrimary): def __init__(self, dbstate, uistate, track, place, callback=None): EditPrimary.__init__(self, dbstate, uistate, track, place, - dbstate.db.get_place_from_handle, + dbstate.db.get_place_from_handle, dbstate.db.get_place_from_gramps_id, callback) def empty_object(self): @@ -76,7 +76,7 @@ class EditPlace(EditPrimary): def _local_init(self): self.width_key = 'interface.place-width' self.height_key = 'interface.place-height' - + self.top = Glade() self.set_window(self.top.toplevel, None, self.get_menu_title()) self.place_name_label = self.top.get_object('place_name_label') @@ -97,43 +97,43 @@ class EditPlace(EditPrimary): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('place-rebuild', self._do_close) self._add_db_signal('place-delete', self.check_for_close) def _setup_fields(self): - + if not config.get('preferences.place-auto'): self.top.get_object("place_title").show() self.top.get_object("place_title_label").show() self.title = MonitoredEntry(self.top.get_object("place_title"), self.obj.set_title, self.obj.get_title, self.db.readonly) - + self.name = MonitoredEntry(self.top.get_object("name_entry"), self.obj.get_name().set_value, self.obj.get_name().get_value, self.db.readonly, changed=self.name_changed) - + edit_button = self.top.get_object("name_button") edit_button.connect('clicked', self.edit_place_name) self.gid = MonitoredEntry(self.top.get_object("gid"), - self.obj.set_gramps_id, + self.obj.set_gramps_id, self.obj.get_gramps_id, self.db.readonly) - - self.tags = MonitoredTagList(self.top.get_object("tag_label"), - self.top.get_object("tag_button"), - self.obj.set_tag_list, + + self.tags = MonitoredTagList(self.top.get_object("tag_label"), + self.top.get_object("tag_button"), + self.obj.set_tag_list, self.obj.get_tag_list, self.db, self.uistate, self.track, self.db.readonly) - self.privacy = PrivacyButton(self.top.get_object("private"), self.obj, + self.privacy = PrivacyButton(self.top.get_object("private"), self.obj, self.db.readonly) self.place_type = MonitoredDataType(self.top.get_object("place_type"), @@ -162,7 +162,7 @@ class EditPlace(EditPrimary): self.latitude.connect("validate", self._validate_coordinate, "lat") #force validation now with initial entry self.top.get_object("lat_entry").validate(force=True) - + def _validate_coordinate(self, widget, text, typedeg): if (typedeg == 'lat') and not conv_lat_lon(text, "0", "ISO-D"): return ValidationError(_("Invalid latitude (syntax: 18\u00b09'") + @@ -185,7 +185,7 @@ class EditPlace(EditPrimary): """ Create the notebook tabs and inserts them into the main window. - + """ notebook = self.top.get_object('notebook3') @@ -197,7 +197,7 @@ class EditPlace(EditPrimary): self.update_title) self._add_tab(notebook, self.placeref_list) self.track_ref_for_deletion("placeref_list") - + self.alt_name_list = PlaceNameEmbedList(self.dbstate, self.uistate, self.track, @@ -212,7 +212,7 @@ class EditPlace(EditPrimary): self.obj.alt_loc) self._add_tab(notebook, self.loc_list) self.track_ref_for_deletion("loc_list") - + self.citation_list = CitationEmbedList(self.dbstate, self.uistate, self.track, @@ -220,7 +220,7 @@ class EditPlace(EditPrimary): self.get_menu_title()) self._add_tab(notebook, self.citation_list) self.track_ref_for_deletion("citation_list") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, @@ -229,14 +229,14 @@ class EditPlace(EditPrimary): notetype=NoteType.PLACE) self._add_tab(notebook, self.note_tab) self.track_ref_for_deletion("note_tab") - + self.gallery_tab = GalleryTab(self.dbstate, self.uistate, self.track, self.obj.get_media_list()) self._add_tab(notebook, self.gallery_tab) self.track_ref_for_deletion("gallery_tab") - + self.web_list = WebEmbedList(self.dbstate, self.uistate, self.track, @@ -271,7 +271,7 @@ class EditPlace(EditPrimary): if self.obj.get_name().get_value().strip() == '': msg1 = _("Cannot save place. Name not entered.") - msg2 = _("You must enter a name before saving.") + msg2 = _("You must enter a name before saving.") ErrorDialog(msg1, msg2) self.ok_button.set_sensitive(True) return @@ -282,7 +282,7 @@ class EditPlace(EditPrimary): name = place_displayer.display(self.db, prim_object) msg1 = _("Cannot save place. ID already exists.") msg2 = _("You have attempted to use the existing Gramps ID with " - "value %(id)s. This value is already used by '" + "value %(id)s. This value is already used by '" "%(prim_object)s'. Please enter a different ID or leave " "blank to get the next available ID value.") % { 'id' : id, 'prim_object' : name } @@ -301,7 +301,7 @@ class EditPlace(EditPrimary): self.db.commit_place(self.obj, trans) msg = _("Edit Place (%s)") % place_title trans.set_description(msg) - + self.close() if self.callback: self.callback(self.obj) @@ -313,7 +313,7 @@ class EditPlace(EditPrimary): #------------------------------------------------------------------------- class DeletePlaceQuery(object): - def __init__(self, dbstate, uistate, place, person_list, family_list, + def __init__(self, dbstate, uistate, place, person_list, family_list, event_list): self.db = dbstate.db self.uistate = uistate @@ -321,12 +321,12 @@ class DeletePlaceQuery(object): self.person_list = person_list self.family_list = family_list self.event_list = event_list - + def query_response(self): place_title = place_displayer.display(self.db, self.obj) with DbTxn(_("Delete Place (%s)") % place_title, self.db) as trans: self.db.disable_signals() - + place_handle = self.obj.get_handle() for handle in self.person_list: diff --git a/gramps/gui/editors/editplaceref.py b/gramps/gui/editors/editplaceref.py index 15b031ea3..4da7c0b71 100644 --- a/gramps/gui/editors/editplaceref.py +++ b/gramps/gui/editors/editplaceref.py @@ -66,13 +66,13 @@ class EditPlaceRef(EditReference): notebook = self.top.get_object('notebook_ref') #recreate start page as GrampsTab notebook.remove_page(0) - self.reftab = RefTab(self.dbstate, self.uistate, self.track, + self.reftab = RefTab(self.dbstate, self.uistate, self.track, _('General'), tblref) tblref = self.top.get_object('table62') notebook = self.top.get_object('notebook') #recreate start page as GrampsTab notebook.remove_page(0) - self.primtab = RefTab(self.dbstate, self.uistate, self.track, + self.primtab = RefTab(self.dbstate, self.uistate, self.track, _('_General'), tblref) def _connect_signals(self): @@ -83,7 +83,7 @@ class EditPlaceRef(EditReference): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('place-rebuild', self.close) @@ -102,7 +102,7 @@ class EditPlaceRef(EditReference): self.date_field = MonitoredDate(self.top.get_object("date_entry"), self.top.get_object("date_stat"), self.source_ref.get_date_object(), - self.uistate, self.track, + self.uistate, self.track, self.db.readonly) if not config.get('preferences.place-auto'): @@ -112,29 +112,29 @@ class EditPlaceRef(EditReference): self.source.set_title, self.source.get_title, self.db.readonly) - + self.name = MonitoredEntry(self.top.get_object("name_entry"), self.source.get_name().set_value, self.source.get_name().get_value, self.db.readonly, changed=self.name_changed) - + edit_button = self.top.get_object("name_button") edit_button.connect('clicked', self.edit_place_name) self.gid = MonitoredEntry(self.top.get_object("gid"), - self.source.set_gramps_id, + self.source.set_gramps_id, self.source.get_gramps_id, self.db.readonly) - - self.tags = MonitoredTagList(self.top.get_object("tag_label"), - self.top.get_object("tag_button"), - self.source.set_tag_list, + + self.tags = MonitoredTagList(self.top.get_object("tag_label"), + self.top.get_object("tag_button"), + self.source.set_tag_list, self.source.get_tag_list, self.db, self.uistate, self.track, self.db.readonly) - self.privacy = PrivacyButton(self.top.get_object("private"), self.source, + self.privacy = PrivacyButton(self.top.get_object("private"), self.source, self.db.readonly) self.place_type = MonitoredDataType(self.top.get_object("place_type"), @@ -183,7 +183,7 @@ class EditPlaceRef(EditReference): """ Create the notebook tabs and inserts them into the main window. - + """ notebook = self.top.get_object('notebook') notebook_ref = self.top.get_object('notebook_ref') @@ -201,7 +201,7 @@ class EditPlaceRef(EditReference): self.update_title) self._add_tab(notebook, self.placeref_list) self.track_ref_for_deletion("placeref_list") - + self.alt_name_list = PlaceNameEmbedList(self.dbstate, self.uistate, self.track, @@ -216,14 +216,14 @@ class EditPlaceRef(EditReference): self.source.alt_loc) self._add_tab(notebook, self.loc_list) self.track_ref_for_deletion("loc_list") - + self.citation_list = CitationEmbedList(self.dbstate, self.uistate, self.track, self.source.get_citation_list()) self._add_tab(notebook, self.citation_list) self.track_ref_for_deletion("citation_list") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, @@ -231,14 +231,14 @@ class EditPlaceRef(EditReference): notetype=NoteType.PLACE) self._add_tab(notebook, self.note_tab) self.track_ref_for_deletion("note_tab") - + self.gallery_tab = GalleryTab(self.dbstate, self.uistate, self.track, self.source.get_media_list()) self._add_tab(notebook, self.gallery_tab) self.track_ref_for_deletion("gallery_tab") - + self.web_list = WebEmbedList(self.dbstate, self.uistate, self.track, @@ -287,7 +287,7 @@ class EditPlaceRef(EditReference): with DbTxn(_("Add Place"), self.db) as trans: self.db.add_place(self.source, trans) self.source_ref.ref = self.source.handle - + if self.update: self.update(self.source_ref, self.source) diff --git a/gramps/gui/editors/editprimary.py b/gramps/gui/editors/editprimary.py index f2b11375d..3748fcffd 100644 --- a/gramps/gui/editors/editprimary.py +++ b/gramps/gui/editors/editprimary.py @@ -52,14 +52,14 @@ from ..dbguielement import DbGUIElement class EditPrimary(ManagedWindow, DbGUIElement): QR_CATEGORY = -1 - - def __init__(self, state, uistate, track, obj, get_from_handle, + + def __init__(self, state, uistate, track, obj, get_from_handle, get_from_gramps_id, callback=None): """ - Create an edit window. - + Create an edit window. + Associate a person with the window. - + """ self.dp = parser self.dd = displayer @@ -85,7 +85,7 @@ class EditPrimary(ManagedWindow, DbGUIElement): self._connect_signals() #if the database is changed, all info shown is invalid and the window # should close - self.dbstate_connect_key = self.dbstate.connect('database-changed', + self.dbstate_connect_key = self.dbstate.connect('database-changed', self._do_close) self.show() self._post_init() @@ -139,7 +139,7 @@ class EditPrimary(ManagedWindow, DbGUIElement): if not pag == -1: notebook.get_nth_page(pag).key_pressed(obj, event) - def _switch_page_on_dnd(self, widget, context, x, y, time, notebook, + def _switch_page_on_dnd(self, widget, context, x, y, time, notebook, page_no): if notebook.get_current_page() != page_no: notebook.set_current_page(page_no) @@ -188,7 +188,7 @@ class EditPrimary(ManagedWindow, DbGUIElement): def _cleanup_db_connects(self): """ - All connects that happened to signals of the db must be removed on + All connects that happened to signals of the db must be removed on closed. This implies two things: 1. The connects on the main view must be disconnected 2. Connects done in subelements must be disconnected @@ -198,7 +198,7 @@ class EditPrimary(ManagedWindow, DbGUIElement): for tab in self.__tabs: if hasattr(tab, 'callman'): tab._cleanup_callbacks() - + def _cleanup_connects(self): """ Connects to interface elements to things outside the element should be @@ -218,7 +218,7 @@ class EditPrimary(ManagedWindow, DbGUIElement): def check_for_close(self, handles): """ - Callback method for delete signals. + Callback method for delete signals. If there is a delete signal of the primary object we are editing, the editor (and all child windows spawned) should be closed """ @@ -242,8 +242,8 @@ class EditPrimary(ManagedWindow, DbGUIElement): return False def empty_object(self): - #empty_object should be overridden in base class and will throw an - #exception if it is not because self.empty_object().serialize() is + #empty_object should be overridden in base class and will throw an + #exception if it is not because self.empty_object().serialize() is #called and PrimaryObject does not implement serialize(). See #BaseObject.serialize() return PrimaryObject @@ -266,7 +266,7 @@ class EditPrimary(ManagedWindow, DbGUIElement): """ Save changes and close. Inheriting classes must implement this """ self.close() - + def set_contexteventbox(self, eventbox): """Set the contextbox that grabs button presses if not grabbed by overlying widgets. @@ -274,7 +274,7 @@ class EditPrimary(ManagedWindow, DbGUIElement): self.contexteventbox = eventbox self.contexteventbox.connect('button-press-event', self._contextmenu_button_press) - + def _contextmenu_button_press(self, obj, event) : """ Button press event that is caught when a mousebutton has been @@ -284,12 +284,12 @@ class EditPrimary(ManagedWindow, DbGUIElement): if is_right_click(event): if self.obj.get_handle() == 0 : return False - + #build the possible popup menu self._build_popup_ui() #set or unset sensitivity in popup self._post_build_popup_ui() - + menu = self.popupmanager.get_widget('/Popup') if menu: menu.popup(None, None, None, None, event.button, event.time) @@ -300,8 +300,8 @@ class EditPrimary(ManagedWindow, DbGUIElement): """ Create actions and ui of context menu """ - from ..plug.quick import create_quickreport_menu - + from ..plug.quick import create_quickreport_menu + self.popupmanager = Gtk.UIManager() #add custom actions (ui_top, action_groups) = self._top_contextmenu() @@ -311,29 +311,29 @@ class EditPrimary(ManagedWindow, DbGUIElement): ui_qr = '' if self.QR_CATEGORY > -1 : (ui_qr, reportactions) = create_quickreport_menu(self.QR_CATEGORY, - self.dbstate, self.uistate, + self.dbstate, self.uistate, self.obj.get_handle()) self.report_action = Gtk.ActionGroup(name="/PersonReport") self.report_action.add_actions(reportactions) self.report_action.set_visible(True) self.popupmanager.insert_action_group(self.report_action, -1) - + popupui = ''' ''' + ui_top + ''' ''' + ui_qr + ''' ''' - + self.popupmanager.add_ui_from_string(popupui) - + def _top_contextmenu(self): """ - Derived class can create a ui with menuitems and corresponding list of + Derived class can create a ui with menuitems and corresponding list of actiongroups """ return "", [] - + def _post_build_popup_ui(self): """ Derived class should do extra actions here on the menu @@ -343,9 +343,9 @@ class EditPrimary(ManagedWindow, DbGUIElement): def _uses_duplicate_id(self): """ Check whether a changed or added GRAMPS ID already exists in the DB. - + Return True if a duplicate GRAMPS ID has been detected. - + """ original = self.get_from_handle(self.obj.get_handle()) if original and original.get_gramps_id() == self.obj.get_gramps_id(): @@ -355,4 +355,4 @@ class EditPrimary(ManagedWindow, DbGUIElement): if self.get_from_gramps_id(idval): return (True, idval) return (False, 0) - + diff --git a/gramps/gui/editors/editreference.py b/gramps/gui/editors/editreference.py index 8276b46c0..bcfdce3a1 100644 --- a/gramps/gui/editors/editreference.py +++ b/gramps/gui/editors/editreference.py @@ -192,7 +192,7 @@ class EditReference(ManagedWindow, DbGUIElement): def check_for_close(self, handles): """ - Callback method for delete signals. + Callback method for delete signals. If there is a delete signal of the primary object we are editing, the editor (and all child windows spawned) should be closed """ @@ -231,7 +231,7 @@ class EditReference(ManagedWindow, DbGUIElement): def _cleanup_db_connects(self): """ - All connects that happened to signals of the db must be removed on + All connects that happened to signals of the db must be removed on closed. This implies two things: 1. The connects on the main view must be disconnected 2. Connects done in subelements must be disconnected @@ -240,7 +240,7 @@ class EditReference(ManagedWindow, DbGUIElement): self._cleanup_callbacks() for tab in [tab for tab in self.__tabs if hasattr(tab, 'callman')]: tab._cleanup_callbacks() - + def _cleanup_connects(self): """ Connects to interface elements to things outside the element should be @@ -285,7 +285,7 @@ class EditReference(ManagedWindow, DbGUIElement): msg1 = _("Cannot save item. ID already exists.") if description: msg2 = _("You have attempted to use the existing Gramps " - "ID with value %(id)s. This value is already " + "ID with value %(id)s. This value is already " "used by '%(prim_object)s'. Please enter a " "different ID or leave blank to get the next " "available ID value.") % { diff --git a/gramps/gui/editors/editreporef.py b/gramps/gui/editors/editreporef.py index abd5e2878..c1d86996b 100644 --- a/gramps/gui/editors/editreporef.py +++ b/gramps/gui/editors/editreporef.py @@ -55,10 +55,10 @@ class EditRepoRef(EditReference): def _local_init(self): self.width_key = 'interface.repo-ref-width' self.height_key = 'interface.repo-ref-height' - + self.top = Glade() self.set_window(self.top.toplevel, - self.top.get_object('repo_title'), + self.top.get_object('repo_title'), _('Repository Reference Editor')) self.define_warn_box(self.top.get_object("warn_box")) @@ -68,13 +68,13 @@ class EditRepoRef(EditReference): notebook = self.top.get_object('notebook_ref') #recreate start page as GrampsTab notebook.remove_page(0) - self.reftab = RefTab(self.dbstate, self.uistate, self.track, + self.reftab = RefTab(self.dbstate, self.uistate, self.track, _('General'), tblref) tblref = self.top.get_object('table69') notebook = self.top.get_object('notebook_src') #recreate start page as GrampsTab notebook.remove_page(0) - self.primtab = RefTab(self.dbstate, self.uistate, self.track, + self.primtab = RefTab(self.dbstate, self.uistate, self.track, _('_General'), tblref) self.track_ref_for_deletion("primtab") @@ -84,7 +84,7 @@ class EditRepoRef(EditReference): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('repository-rebuild', self.close) @@ -96,7 +96,7 @@ class EditRepoRef(EditReference): self.source_ref.set_call_number, self.source_ref.get_call_number, self.db.readonly) - + self.gid = MonitoredEntry( self.top.get_object('gid'), self.source.set_gramps_id, @@ -118,7 +118,7 @@ class EditRepoRef(EditReference): self.source.set_name, self.source.get_name, self.db.readonly) - + self.type_selector = MonitoredDataType( self.top.get_object("media_type"), self.source_ref.set_media_type, @@ -152,7 +152,7 @@ class EditRepoRef(EditReference): notetype=NoteType.REPO) self._add_tab(notebook_src, self.note_tab) self.track_ref_for_deletion("note_tab") - + self.comment_tab = NoteTab(self.dbstate, self.uistate, self.track, self.source_ref.get_note_list(), notetype=NoteType.REPOREF) @@ -169,7 +169,7 @@ class EditRepoRef(EditReference): self._add_tab(notebook_src, self.web_list) self.track_ref_for_deletion("web_list") - self.backref_tab = SourceBackRefList(self.dbstate, self.uistate, + self.backref_tab = SourceBackRefList(self.dbstate, self.uistate, self.track, self.db.find_backlink_handles(self.source.handle), self.enable_warnbox) @@ -186,7 +186,7 @@ class EditRepoRef(EditReference): else: submenu_label = _('New Repository') return (_('Repo Reference Editor'),submenu_label) - + def ok_clicked(self, obj): if self.source.handle: diff --git a/gramps/gui/editors/editrepository.py b/gramps/gui/editors/editrepository.py index 39582a606..d5f6b8434 100644 --- a/gramps/gui/editors/editrepository.py +++ b/gramps/gui/editors/editrepository.py @@ -53,8 +53,8 @@ class EditRepository(EditPrimary): def __init__(self, dbstate, uistate, track, repository, callback=None): - EditPrimary.__init__(self, dbstate, uistate, track, repository, - dbstate.db.get_repository_from_handle, + EditPrimary.__init__(self, dbstate, uistate, track, repository, + dbstate.db.get_repository_from_handle, dbstate.db.get_repository_from_gramps_id) def empty_object(self): @@ -74,17 +74,17 @@ class EditRepository(EditPrimary): def _local_init(self): self.width_key = 'interface.repo-width' self.height_key = 'interface.repo-height' - + self.glade = Glade() - - self.set_window(self.glade.toplevel, None, + + self.set_window(self.glade.toplevel, None, self.get_menu_title()) def build_menu_names(self, source): - return (_('Edit Repository'), self.get_menu_title()) + return (_('Edit Repository'), self.get_menu_title()) def _setup_fields(self): - + self.name = MonitoredEntry(self.glade.get_object("repository_name"), self.obj.set_name, self.obj.get_name, self.db.readonly) @@ -96,22 +96,22 @@ class EditRepository(EditPrimary): self.call_number = MonitoredEntry(self.glade.get_object('gid'), self.obj.set_gramps_id, - self.obj.get_gramps_id, + self.obj.get_gramps_id, self.db.readonly) - self.tags = MonitoredTagList(self.glade.get_object("tag_label"), - self.glade.get_object("tag_button"), - self.obj.set_tag_list, + self.tags = MonitoredTagList(self.glade.get_object("tag_label"), + self.glade.get_object("tag_button"), + self.obj.set_tag_list, self.obj.get_tag_list, self.db, self.uistate, self.track, self.db.readonly) - self.privacy = PrivacyButton(self.glade.get_object("private"), + self.privacy = PrivacyButton(self.glade.get_object("private"), self.obj, self.db.readonly) def _create_tabbed_pages(self): - + notebook = Gtk.Notebook() self.addr_tab = AddrEmbedList(self.dbstate, @@ -127,7 +127,7 @@ class EditRepository(EditPrimary): self.obj.get_url_list()) self._add_tab(notebook, self.url_tab) self.track_ref_for_deletion("url_tab") - + self.note_tab = NoteTab(self.dbstate, self.uistate, self.track, @@ -156,7 +156,7 @@ class EditRepository(EditPrimary): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('repository-rebuild', self._do_close) @@ -177,7 +177,7 @@ class EditRepository(EditPrimary): name = prim_object.get_name() msg1 = _("Cannot save repository. ID already exists.") msg2 = _("You have attempted to use the existing Gramps ID with " - "value %(id)s. This value is already used by '" + "value %(id)s. This value is already used by '" "%(prim_object)s'. Please enter a different ID or leave " "blank to get the next available ID value.") % { 'id' : id, 'prim_object' : name } @@ -195,7 +195,7 @@ class EditRepository(EditPrimary): self.db.commit_repository(self.obj, trans) msg = _("Edit Repository (%s)") % self.obj.get_name() trans.set_description(msg) - + self.close() class DeleteRepositoryQuery(object): @@ -208,7 +208,7 @@ class DeleteRepositoryQuery(object): def query_response(self): with DbTxn(_("Delete Repository (%s)") % self.obj.get_name(), self.db) as trans: - + repos_handle_list = [self.obj.get_handle()] for handle in self.sources: diff --git a/gramps/gui/editors/editsecondary.py b/gramps/gui/editors/editsecondary.py index eeb4c374d..7874c0543 100644 --- a/gramps/gui/editors/editsecondary.py +++ b/gramps/gui/editors/editsecondary.py @@ -72,7 +72,7 @@ class EditSecondary(ManagedWindow, DbGUIElement): def build_window_key(self, obj): return id(obj) - + def _setup_notebook_tabs(self, notebook): for child in notebook.get_children(): label = notebook.get_tab_label(child) @@ -146,7 +146,7 @@ class EditSecondary(ManagedWindow, DbGUIElement): def _cleanup_db_connects(self): """ - All connects that happened to signals of the db must be removed on + All connects that happened to signals of the db must be removed on closed. This implies two things: 1. The connects on the main view must be disconnected 2. Connects done in subelements must be disconnected diff --git a/gramps/gui/editors/editsource.py b/gramps/gui/editors/editsource.py index de850b69c..32f53d6d9 100644 --- a/gramps/gui/editors/editsource.py +++ b/gramps/gui/editors/editsource.py @@ -63,8 +63,8 @@ class EditSource(EditPrimary): def __init__(self, dbstate, uistate, track, source, callback=None): - EditPrimary.__init__(self, dbstate, uistate, track, source, - dbstate.db.get_source_from_handle, + EditPrimary.__init__(self, dbstate, uistate, track, source, + dbstate.db.get_source_from_handle, dbstate.db.get_source_from_gramps_id, callback) def empty_object(self): @@ -82,9 +82,9 @@ class EditSource(EditPrimary): self.width_key = 'interface.source-width' self.height_key = 'interface.source-height' assert(self.obj) - + self.glade = Glade() - self.set_window(self.glade.toplevel, None, + self.set_window(self.glade.toplevel, None, self.get_menu_title()) def _connect_signals(self): @@ -94,7 +94,7 @@ class EditSource(EditPrimary): def _connect_db_signals(self): """ - Connect any signals that need to be connected. + Connect any signals that need to be connected. Called by the init routine of the base class (_EditPrimary). """ self._add_db_signal('source-rebuild', self._do_close) @@ -111,23 +111,23 @@ class EditSource(EditPrimary): self.db.readonly) self.gid = MonitoredEntry(self.glade.get_object("gid"), - self.obj.set_gramps_id, + self.obj.set_gramps_id, self.obj.get_gramps_id, self.db.readonly) - self.tags = MonitoredTagList(self.glade.get_object("tag_label"), - self.glade.get_object("tag_button"), - self.obj.set_tag_list, + self.tags = MonitoredTagList(self.glade.get_object("tag_label"), + self.glade.get_object("tag_button"), + self.obj.set_tag_list, self.obj.get_tag_list, self.db, self.uistate, self.track, self.db.readonly) - self.priv = PrivacyButton(self.glade.get_object("private"), self.obj, + self.priv = PrivacyButton(self.glade.get_object("private"), self.obj, self.db.readonly) self.abbrev = MonitoredEntry(self.glade.get_object("abbrev"), self.obj.set_abbreviation, - self.obj.get_abbreviation, + self.obj.get_abbreviation, self.db.readonly) self.title = MonitoredEntry(self.glade.get_object("source_title"), @@ -145,28 +145,28 @@ class EditSource(EditPrimary): NoteType.SOURCE) self._add_tab(notebook, self.note_tab) self.track_ref_for_deletion("note_tab") - + self.gallery_tab = GalleryTab(self.dbstate, self.uistate, self.track, self.obj.get_media_list()) self._add_tab(notebook, self.gallery_tab) self.track_ref_for_deletion("gallery_tab") - + self.attr_tab = SrcAttrEmbedList(self.dbstate, self.uistate, self.track, self.obj.get_attribute_list()) self._add_tab(notebook, self.attr_tab) self.track_ref_for_deletion("attr_tab") - + self.repo_tab = RepoEmbedList(self.dbstate, self.uistate, self.track, self.obj.get_reporef_list()) self._add_tab(notebook, self.repo_tab) self.track_ref_for_deletion("repo_tab") - + self.backref_list = CitationBackRefList(self.dbstate, self.uistate, self.track, @@ -174,13 +174,13 @@ class EditSource(EditPrimary): self.backref_tab = self._add_tab(notebook, self.backref_list) self.track_ref_for_deletion("backref_tab") self.track_ref_for_deletion("backref_list") - + self._setup_notebook_tabs(notebook) notebook.show_all() self.glade.get_object('vbox').pack_start(notebook, True, True, 0) def build_menu_names(self, source): - return (_('Edit Source'), self.get_menu_title()) + return (_('Edit Source'), self.get_menu_title()) def save(self, *obj): self.ok_button.set_sensitive(False) @@ -190,14 +190,14 @@ class EditSource(EditPrimary): "enter data or cancel the edit.")) self.ok_button.set_sensitive(True) return - + (uses_dupe_id, id) = self._uses_duplicate_id() if uses_dupe_id: prim_object = self.get_from_gramps_id(id) name = prim_object.get_title() msg1 = _("Cannot save source. ID already exists.") msg2 = _("You have attempted to use the existing Gramps ID with " - "value %(id)s. This value is already used by '" + "value %(id)s. This value is already used by '" "%(prim_object)s'. Please enter a different ID or leave " "blank to get the next available ID value.") % { 'id' : id, 'prim_object' : name } @@ -215,7 +215,7 @@ class EditSource(EditPrimary): self.db.commit_source(self.obj, trans) msg = _("Edit Source (%s)") % self.obj.get_title() trans.set_description(msg) - + self.close() if self.callback: self.callback(self.obj) @@ -231,14 +231,14 @@ class DeleteSrcQuery(object): with DbTxn(_("Delete Source (%s)") % self.source.get_title(), self.db) as trans: self.db.disable_signals() - + # we can have: # object(CitationBase) -> Citation(source_handle) -> Source - # We first have to remove the CitationBase references to the - # Citation. Then we remove the Citations. (We don't need to + # We first have to remove the CitationBase references to the + # Citation. Then we remove the Citations. (We don't need to # remove the source_handle references to the Source, because we are # removing the whole Citation). Then we can remove the Source - + (citation_list, citation_referents_list) = self.the_lists # citation_list is a tuple of lists. Only the first, for Citations, # exists. @@ -246,43 +246,43 @@ class DeleteSrcQuery(object): # (1) delete the references to the citation for (citation_handle, refs) in citation_referents_list: - LOG.debug('delete citation %s references %s' % + LOG.debug('delete citation %s references %s' % (citation_handle, refs)) - (person_list, family_list, event_list, place_list, source_list, + (person_list, family_list, event_list, place_list, source_list, media_list, repo_list) = refs - + ctn_handle_list = [citation_handle] - + for handle in person_list: person = self.db.get_person_from_handle(handle) person.remove_citation_references(ctn_handle_list) self.db.commit_person(person, trans) - + for handle in family_list: family = self.db.get_family_from_handle(handle) family.remove_citation_references(ctn_handle_list) self.db.commit_family(family, trans) - + for handle in event_list: event = self.db.get_event_from_handle(handle) event.remove_citation_references(ctn_handle_list) self.db.commit_event(event, trans) - + for handle in place_list: place = self.db.get_place_from_handle(handle) place.remove_citation_references(ctn_handle_list) self.db.commit_place(place, trans) - + for handle in source_list: source = self.db.get_source_from_handle(handle) source.remove_citation_references(ctn_handle_list) self.db.commit_source(source, trans) - + for handle in media_list: media = self.db.get_object_from_handle(handle) media.remove_citation_references(ctn_handle_list) self.db.commit_media_object(media, trans) - + for handle in repo_list: repo = self.db.get_repository_from_handle(handle) repo.remove_citation_references(ctn_handle_list) @@ -293,7 +293,7 @@ class DeleteSrcQuery(object): for citation_handle in citation_list: LOG.debug("remove_citation %s" % citation_handle) self.db.remove_citation(citation_handle, trans) - + # (3) delete the source self.db.enable_signals() self.db.remove_source(self.source.get_handle(), trans) diff --git a/gramps/gui/editors/edittaglist.py b/gramps/gui/editors/edittaglist.py index 0f027728e..2be2a2ec4 100644 --- a/gramps/gui/editors/edittaglist.py +++ b/gramps/gui/editors/edittaglist.py @@ -18,7 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ -Tag editing module for Gramps. +Tag editing module for Gramps. """ #------------------------------------------------------------------------- # @@ -66,7 +66,7 @@ class EditTagList(ManagedWindow): self.namemodel = None top = self._create_dialog() - self.set_window(top, None, _('Tag selection')) + self.set_window(top, None, _('Tag selection')) for tag in full_list: self.namemodel.add([tag[0], tag in tag_list, tag[1]]) @@ -113,7 +113,7 @@ class EditTagList(ManagedWindow): slist.add(view) slist.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) top.vbox.pack_start(slist, 1, 1, 5) - + top.add_button(_('_Help'), Gtk.ResponseType.HELP) top.add_button(_('_Cancel'), Gtk.ResponseType.CANCEL) top.add_button(_('_OK'), Gtk.ResponseType.OK) diff --git a/gramps/gui/editors/editurl.py b/gramps/gui/editors/editurl.py index 39a087ebb..e5f41f428 100644 --- a/gramps/gui/editors/editurl.py +++ b/gramps/gui/editors/editurl.py @@ -51,20 +51,20 @@ class EditUrl(EditSecondary): def _local_init(self): self.width_key = 'interface.url-width' self.height_key = 'interface.url-height' - + self.top = Glade() self.jump = self.top.get_object('jump') self.set_window(self.top.toplevel, self.top.get_object("title"), _('Internet Address Editor')) - + def _connect_signals(self): self.jump.connect('clicked', self.jump_to) self.define_cancel_button(self.top.get_object('button125')) self.define_ok_button(self.top.get_object('button124'), self.save) self.define_help_button(self.top.get_object('button130')) - + def jump_to(self, obj): if self.obj.get_path(): from ..display import display_url @@ -72,20 +72,20 @@ class EditUrl(EditSecondary): def _setup_fields(self): self.des = MonitoredEntry(self.top.get_object("url_des"), - self.obj.set_description, + self.obj.set_description, self.obj.get_description, self.db.readonly) - self.addr = MonitoredEntry(self.top.get_object("url_addr"), - self.obj.set_path, self.obj.get_path, + self.addr = MonitoredEntry(self.top.get_object("url_addr"), + self.obj.set_path, self.obj.get_path, self.db.readonly) - + self.priv = PrivacyButton(self.top.get_object("priv"), self.obj, self.db.readonly) - self.type_sel = MonitoredDataType(self.top.get_object("type"), - self.obj.set_type, + self.type_sel = MonitoredDataType(self.top.get_object("type"), + self.obj.set_type, self.obj.get_type, self.db.readonly) - + def build_menu_names(self, obj): etitle =_('Internet Address Editor') return (etitle, etitle) diff --git a/gramps/gui/editors/filtereditor.py b/gramps/gui/editors/filtereditor.py index 8cc51c8fa..0c2669d49 100644 --- a/gramps/gui/editors/filtereditor.py +++ b/gramps/gui/editors/filtereditor.py @@ -39,7 +39,7 @@ log = logging.getLogger(".filtereditor") #------------------------------------------------------------------------- # -# GTK/GNOME +# GTK/GNOME # #------------------------------------------------------------------------- from gi.repository import Gtk @@ -53,7 +53,7 @@ from gi.repository import GObject #------------------------------------------------------------------------- from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext -from gramps.gen.filters import (GenericFilterFactory, FilterList, +from gramps.gen.filters import (GenericFilterFactory, FilterList, reload_custom_filters) from gramps.gen.filters.rules._matchesfilterbase import MatchesFilterBase from ..listmodel import ListModel @@ -123,13 +123,13 @@ class MyBoolean(Gtk.CheckButton): def get_text(self): """ - Return the text to save. - - It should be the same no matter the present locale (English or numeric + Return the text to save. + + It should be the same no matter the present locale (English or numeric types). This class sets this to get_display_text, but when localization is an issue (events/attr/etc types) then it has to be overridden. - + """ return str(int(self.get_active())) @@ -171,10 +171,10 @@ class MyFilters(Gtk.ComboBox): def __init__(self, filters, filter_name=None): """ Construct the combobox from the entries of the filters list. - + Filter_name is name of calling filter. If filter_name is given, it will be excluded from the dropdown box. - + """ GObject.GObject.__init__(self) store = Gtk.ListStore(GObject.TYPE_STRING) @@ -191,7 +191,7 @@ class MyFilters(Gtk.ComboBox): store.append(row=[fname]) self.set_active(0) self.show() - + def get_text(self): active = self.get_active() if active < 0: @@ -208,7 +208,7 @@ class MyFilters(Gtk.ComboBox): # #------------------------------------------------------------------------- class MyList(Gtk.ComboBox): - + def __init__(self, clist, clist_trans, default=0): GObject.GObject.__init__(self) store = Gtk.ListStore(GObject.TYPE_STRING) @@ -221,7 +221,7 @@ class MyList(Gtk.ComboBox): store.append(row=[name]) self.set_active(default) self.show() - + def get_text(self): active = self.get_active() return self.clist[active] @@ -270,13 +270,13 @@ class MyLesserEqualGreater(Gtk.ComboBox): # #------------------------------------------------------------------------- class MyPlaces(Gtk.Entry): - + def __init__(self, places): GObject.GObject.__init__(self) - + fill_entry(self, places) self.show() - + #------------------------------------------------------------------------- # # MyID - Person/GRAMPS ID selection box with a standard interface @@ -297,7 +297,7 @@ class MyID(Gtk.Box): 'Note' : _('Note'), 'Citation' : _('Citation'), } - + def __init__(self, dbstate, uistate, track, namespace='Person'): GObject.GObject.__init__(self) self.set_orientation(Gtk.Orientation.HORIZONTAL) @@ -307,7 +307,7 @@ class MyID(Gtk.Box): self.db = dbstate.db self.uistate = uistate self.track = track - + self.namespace = namespace self.entry = Gtk.Entry() self.entry.show() @@ -331,7 +331,7 @@ class MyID(Gtk.Box): self.set_text('') else: self.set_text(val.get_gramps_id()) - + def get_text(self): return str(self.entry.get_text()) @@ -383,7 +383,7 @@ class MyID(Gtk.Box): # #------------------------------------------------------------------------- class MySource(MyID): - + _empty_id_txt = _('Give or select a source ID, leave empty to find objects' ' with no source.') def __init__(self, dbstate, uistate, track): @@ -396,7 +396,7 @@ class MySource(MyID): # #------------------------------------------------------------------------- class MySelect(Gtk.ComboBox): - + def __init__(self, type_class, additional): #we need to inherit and have an combobox with an entry Gtk.ComboBox.__init__(self, has_entry=True) @@ -407,7 +407,7 @@ class MySelect(Gtk.ComboBox): additional, type_class._MENU) self.show() - + def get_text(self): return self.type_class(self.sel.get_values()).xml_str() @@ -422,11 +422,11 @@ class MySelect(Gtk.ComboBox): # #------------------------------------------------------------------------- class MyEntry(Gtk.Entry): - + def __init__(self): GObject.GObject.__init__(self) self.show() - + #------------------------------------------------------------------------- # # EditRule @@ -447,7 +447,7 @@ class EditRule(ManagedWindow): self.active_rule = val self.define_glade('rule_editor', RULE_GLADE) - + self.set_window(self.get_widget('rule_editor'), self.get_widget('rule_editor_title'),label) self.window.hide() @@ -483,7 +483,7 @@ class EditRule(ManagedWindow): class_list = rules.repository.editor_rule_list elif self.namespace == 'Note': class_list = rules.note.editor_rule_list - + for class_obj in class_list: arglist = class_obj.labels vallist = [] @@ -512,7 +512,7 @@ class EditRule(ManagedWindow): elif v == _('Number of generations:'): t = MyInteger(1, 32) elif v == _('ID:'): - t = MyID(self.dbstate, self.uistate, self.track, + t = MyID(self.dbstate, self.uistate, self.track, self.namespace) elif v == _('Source ID:'): t = MySource(self.dbstate, self.uistate, self.track) @@ -570,7 +570,7 @@ class EditRule(ManagedWindow): taglist = taglist + [tag.get_name() for tag in dbstate.db.iter_tags()] t = MyList(taglist, taglist) elif v == _('Confidence level:'): - t = MyList(list(map(str, list(range(5)))), + t = MyList(list(map(str, list(range(5)))), [_(conf_strings[i]) for i in range(5)]) elif v == _('Date:'): t = DateEntry(self.uistate, self.track) @@ -578,7 +578,7 @@ class EditRule(ManagedWindow): long_days = displayer.long_days days_of_week = long_days[2:] + long_days[1:2] t = MyList(map(str, range(7)), days_of_week) - else: + else: t = MyEntry() t.set_hexpand(True) tlist.append(t) @@ -616,7 +616,7 @@ class EditRule(ManagedWindow): self.page_num = 0 self.store = Gtk.TreeStore(GObject.TYPE_STRING, GObject.TYPE_PYOBJECT) self.selection = self.rname.get_selection() - col = Gtk.TreeViewColumn(_('Rule Name'), Gtk.CellRendererText(), + col = Gtk.TreeViewColumn(_('Rule Name'), Gtk.CellRendererText(), text=0) self.rname.append_column(col) self.rname.set_model(self.store) @@ -666,7 +666,7 @@ class EditRule(ManagedWindow): tlist[i].set_text(r[i]) if class_obj.allow_regex: use_regex.set_active(self.active_rule.use_regex) - + self.selection.connect('changed', self.on_node_selected) self.rname.connect('button-press-event', self._button_press) self.rname.connect('key-press-event', self._key_press) @@ -695,8 +695,8 @@ class EditRule(ManagedWindow): def _key_press(self, obj, event): if event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter): return self.expand_collapse() - return False - + return False + def expand_collapse(self): """ Expand or collapse the selected parent name node. @@ -722,7 +722,7 @@ class EditRule(ManagedWindow): def on_node_selected(self, obj): """ - Update the informational display on the right hand side of the dialog + Update the informational display on the right hand side of the dialog box with the description of the selected report. """ store, node = self.selection.get_selected() @@ -766,7 +766,7 @@ class EditRule(ManagedWindow): # #------------------------------------------------------------------------- class EditFilter(ManagedWindow): - + def __init__(self, namespace, dbstate, uistate, track, gfilter, filterdb, update=None, selection_callback=None): @@ -780,20 +780,20 @@ class EditFilter(ManagedWindow): self.filter = gfilter self.filterdb = filterdb self.selection_callback = selection_callback - + self.define_glade('define_filter', RULE_GLADE) - + self.set_window( self.get_widget('define_filter'), self.get_widget('definition_title'), _('Define filter')) - + self.rlist = ListModel( self.get_widget('rule_list'), [(_('Name'),-1,150),(_('Values'),-1,150)], self.select_row, self.on_edit_clicked) - + self.fname = self.get_widget('filter_name') self.logical = self.get_widget('rule_apply') self.logical_not = self.get_widget('logical_not') @@ -807,7 +807,7 @@ class EditFilter(ManagedWindow): self.edit_btn.connect('clicked', self.on_edit_clicked) self.del_btn.connect('clicked', self.on_delete_clicked) self.add_btn.connect('clicked', self.on_add_clicked) - + self.get_widget('definition_help').connect('clicked', self.on_help_clicked) self.get_widget('definition_cancel').connect('clicked', @@ -841,7 +841,7 @@ class EditFilter(ManagedWindow): for filt in self.filterdb.get_filters(self.namespace) if filt != self.filter] self.ok_btn.set_sensitive((len(name) != 0) and (name not in names)) - + def select_row(self, obj): store, node = self.rlist.get_selected() if node: @@ -855,7 +855,7 @@ class EditFilter(ManagedWindow): self.rlist.clear() for r in self.filter.get_rules(): self.rlist.add([r.name,r.display_values()],r) - + def on_ok_clicked(self, obj): n = str(self.fname.get_text()).strip() if n == '': @@ -871,9 +871,9 @@ class EditFilter(ManagedWindow): break val = self.logical.get_active() # WARNING: must be listed in this order: - op = ('and' if val == 0 else - 'or' if val == 1 else - 'one' if val == 2 else + op = ('and' if val == 0 else + 'or' if val == 1 else + 'one' if val == 2 else 'sequence') self.logical.set_active(val) self.filter.set_logical_op(op) @@ -884,7 +884,7 @@ class EditFilter(ManagedWindow): if self.selection_callback: self.selection_callback(self.filterdb, self.filter.get_name()) self.close() - + def on_add_clicked(self, obj): try: EditRule(self.namespace, self.dbstate, self.uistate, self.track, @@ -917,7 +917,7 @@ class EditFilter(ManagedWindow): gfilter = self.rlist.get_object(node) self.filter.delete_rule(gfilter) self.draw_rules() - + #------------------------------------------------------------------------- # # ShowResults @@ -938,7 +938,7 @@ class ShowResults(ManagedWindow): _('Filter Test')) render = Gtk.CellRendererText() - + tree = self.get_widget('list') model = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING) tree.set_model(model) @@ -1002,7 +1002,7 @@ class ShowResults(ManagedWindow): name = name[:80]+"..." gid = note.get_gramps_id() return (name, gid) - + def sort_val_from_handle(self, handle): if self.namespace == 'Person': name = self.db.get_person_from_handle(handle).get_primary_name() @@ -1059,7 +1059,7 @@ class FilterEditor(ManagedWindow): self.set_window(self.get_widget('filter_list'), self.get_widget('filter_list_title'), - _TITLES[self.namespace]) + _TITLES[self.namespace]) self.edit.connect('clicked', self.edit_filter) self.clone.connect('clicked', self.clone_filter) @@ -1069,7 +1069,7 @@ class FilterEditor(ManagedWindow): self.connect_button('filter_list_help', self.help_clicked) self.connect_button('filter_list_close', self.close) self.connect_button('filter_list_add', self.add_new_filter) - + self.uistate.connect('filter-name-changed', self.clean_after_rename) self.clist = ListModel( @@ -1083,7 +1083,7 @@ class FilterEditor(ManagedWindow): def build_menu_names(self, obj): return (_("Custom Filter Editor"), _("Custom Filter Editor")) - + def help_clicked(self, obj): """Display the relevant portion of Gramps manual""" display_help() @@ -1100,14 +1100,14 @@ class FilterEditor(ManagedWindow): self.clone.set_sensitive(False) self.delete.set_sensitive(False) self.test.set_sensitive(False) - + def close(self, *obj): self.filterdb.save() reload_custom_filters() #reload_system_filters() self.uistate.emit('filters-changed', (self.namespace,)) ManagedWindow.close(self, *obj) - + def draw_filters(self): self.clist.clear() for f in self.filterdb.get_filters(self.namespace): @@ -1183,7 +1183,7 @@ class FilterEditor(ManagedWindow): The filter_set is amended with the found filters. """ - filters = self.filterdb.get_filters(space) + filters = self.filterdb.get_filters(space) name = gfilter.get_name() for the_filter in filters: if the_filter.get_name() == name: diff --git a/gramps/gui/editors/objectentries.py b/gramps/gui/editors/objectentries.py index a703add4a..6264d2019 100644 --- a/gramps/gui/editors/objectentries.py +++ b/gramps/gui/editors/objectentries.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -74,7 +74,7 @@ class ObjEntry(object): _DND_TYPE = None _DND_ICON = None - def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, + def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, get_val, add_edt, share, callback=None): """Pass the dbstate and uistate and present track. label is a Gtk.Label that shows the persent value @@ -84,7 +84,7 @@ class ObjEntry(object): get_val is function that is called to obtain handle from calling module share is the Gtk.Button to call the object selector or del connect - add_edt is the Gtk.Button with add or edit value. Pass None if + add_edt is the Gtk.Button with add or edit value. Pass None if this button should not be present. """ self.label = label @@ -98,7 +98,7 @@ class ObjEntry(object): self.uistate = uistate self.track = track self.callback = callback - + #set the object specific code self._init_object() @@ -129,7 +129,7 @@ class ObjEntry(object): if self.add_edt is not None: self.add_edt.connect('clicked', self.add_edt_clicked) self.share.connect('clicked', self.share_clicked) - + if not self.db.readonly and not name: if self.add_edt is None: self.label.set_text(self.EMPTY_TEXT_RED) @@ -160,7 +160,7 @@ class ObjEntry(object): if self._DND_TYPE: if self.get_val(): if not self.label.drag_source_get_target_list(): - self.label_event_box.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, + self.label_event_box.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, [], Gdk.DragAction.COPY) tglist = Gtk.TargetList.new([]) tglist.add(self._DND_TYPE.atom_drag_type, self._DND_TYPE.target_flags, @@ -300,10 +300,10 @@ class PlaceEntry(ObjEntry): DEL_STR = _('Remove place') _DND_TYPE = DdTargets.PLACE_LINK _DND_ICON = 'gramps-place' - - def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, + + def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, get_val, add_edt, share, skip=[]): - ObjEntry.__init__(self, dbstate, uistate, track, label, label_event_box, set_val, + ObjEntry.__init__(self, dbstate, uistate, track, label, label_event_box, set_val, get_val, add_edt, share) self.skip = skip @@ -324,7 +324,7 @@ class PlaceEntry(ObjEntry): place = obj func = self.after_edit try: - EditPlace(self.dbstate, self.uistate, self.track, + EditPlace(self.dbstate, self.uistate, self.track, place, func) except WindowActiveError: pass @@ -347,10 +347,10 @@ class SourceEntry(ObjEntry): DEL_STR = _('Remove source') _DND_TYPE = DdTargets.SOURCE_LINK _DND_ICON = 'gramps-source' - - def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, + + def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, get_val, add_edt, share, callback): - ObjEntry.__init__(self, dbstate, uistate, track, label, label_event_box, set_val, + ObjEntry.__init__(self, dbstate, uistate, track, label, label_event_box, set_val, get_val, add_edt, share, callback) def get_from_handle(self, handle): @@ -369,7 +369,7 @@ class SourceEntry(ObjEntry): source = obj func = self.after_edit try: - EditSource(self.dbstate, self.uistate, self.track, + EditSource(self.dbstate, self.uistate, self.track, source, func) except WindowActiveError: pass @@ -393,10 +393,10 @@ class MediaEntry(ObjEntry): DEL_STR = _('Remove media object') _DND_TYPE = DdTargets.MEDIAOBJ _DND_ICON = 'gramps-media' - - def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, + + def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, get_val, add_edt, share): - ObjEntry.__init__(self, dbstate, uistate, track, label, label_event_box, set_val, + ObjEntry.__init__(self, dbstate, uistate, track, label, label_event_box, set_val, get_val, add_edt, share) def get_from_handle(self, handle): @@ -415,7 +415,7 @@ class MediaEntry(ObjEntry): object = obj func = self.after_edit try: - EditMedia(self.dbstate, self.uistate, self.track, + EditMedia(self.dbstate, self.uistate, self.track, object, func) except WindowActiveError: pass @@ -423,7 +423,7 @@ class MediaEntry(ObjEntry): def call_selector(self): cls = SelectorFactory('MediaObject') return cls(self.dbstate, self.uistate, self.track) - + # FIXME isn't used anywhere class NoteEntry(ObjEntry): """ @@ -439,10 +439,10 @@ class NoteEntry(ObjEntry): DEL_STR = _('Remove note') _DND_TYPE = DdTargets.NOTE_LINK _DND_ICON = 'gramps-notes' - - def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, + + def __init__(self, dbstate, uistate, track, label, label_event_box, set_val, get_val, add_edt, share): - ObjEntry.__init__(self, dbstate, uistate, track, label, label_event_box, set_val, + ObjEntry.__init__(self, dbstate, uistate, track, label, label_event_box, set_val, get_val, add_edt, share) self.notetype = None @@ -476,7 +476,7 @@ class NoteEntry(ObjEntry): note = obj func = self.after_edit try: - EditNote(self.dbstate, self.uistate, self.track, + EditNote(self.dbstate, self.uistate, self.track, note, func) except WindowActiveError: pass diff --git a/gramps/gui/editors/test/test_editreference.py b/gramps/gui/editors/test/test_editreference.py index 05185ad41..f1752fc67 100644 --- a/gramps/gui/editors/test/test_editreference.py +++ b/gramps/gui/editors/test/test_editreference.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -31,7 +31,7 @@ try: except: MOCKING = False -from gramps.gen.lib import (Person, Family, Event, Source, Place, Citation, +from gramps.gen.lib import (Person, Family, Event, Source, Place, Citation, Repository, MediaObject, Note, Tag) from gramps.gen.merge.diff import DictionaryDb from gramps.cli.user import User @@ -52,7 +52,7 @@ class MockEditReference(EditReference): example = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), - "../../../..", + "../../../..", "example/gramps/example.gramps")) class TestEditReference(unittest.TestCase): @@ -69,10 +69,10 @@ class TestEditReference(unittest.TestCase): db.write_version(path) db.load(path) dbstate.change_database(db) - source = Place() + source = Place() source.gramps_id = "P0001" dbstate.db.place_map[source.handle] = source.serialize() - editor = MockEditReference(dbstate, uistate=None, track=[], + editor = MockEditReference(dbstate, uistate=None, track=[], source=source, source_ref=None, update=None) with patch('gramps.gui.editors.editreference.ErrorDialog') as MockED: editor.check_for_duplicate_id("Place") diff --git a/gramps/gui/filters/_filtercombobox.py b/gramps/gui/filters/_filtercombobox.py index 6279cefb6..0ce9609a0 100644 --- a/gramps/gui/filters/_filtercombobox.py +++ b/gramps/gui/filters/_filtercombobox.py @@ -52,7 +52,7 @@ class FilterComboBox(Gtk.ComboBox): self.add_attribute(cell,'text',0) self.map = {} - + active = 0 cnt = 0 for filt in local_filters: @@ -61,7 +61,7 @@ class FilterComboBox(Gtk.ComboBox): if default != "" and default == filt.get_name(): active = cnt cnt += 1 - + #for filt in SystemFilters.get_filters(): #self.store.append(row=[filt.get_name()]) #self.map[unicode(filt.get_name())] = filt diff --git a/gramps/gui/filters/_searchbar.py b/gramps/gui/filters/_searchbar.py index ccd1363c9..97b12ad74 100644 --- a/gramps/gui/filters/_searchbar.py +++ b/gramps/gui/filters/_searchbar.py @@ -55,8 +55,8 @@ class SearchBar(object): self.filter_button = Gtk.Button.new_with_mnemonic(_('_Find')) self.clear_button = Gtk.Button.new_with_mnemonic(_('_Clear')) self.filter_list = Gtk.ComboBox() - self.filter_model = Gtk.ListStore(GObject.TYPE_STRING, - GObject.TYPE_INT, + self.filter_model = Gtk.ListStore(GObject.TYPE_STRING, + GObject.TYPE_INT, GObject.TYPE_BOOLEAN) def destroy(self): @@ -86,7 +86,7 @@ class SearchBar(object): self.filterbar.pack_end(self.filter_button, False, True, 0) return self.filterbar - + def setup_filter( self, column_data ): """ column_data is a list of tuples: @@ -94,7 +94,7 @@ class SearchBar(object): """ self.filter_model.clear() old_value = self.filter_list.get_active() - + cell = Gtk.CellRendererText() self.filter_list.clear() self.filter_list.pack_start(cell, True) @@ -114,7 +114,7 @@ class SearchBar(object): rule = _("%s does not contain") % col self.filter_model.append(row=[rule, index, True]) maxval += 1 - + self.filter_list.set_model(self.filter_model) if old_value == -1 or old_value >= maxval: self.filter_list.set_active(0) @@ -144,7 +144,7 @@ class SearchBar(object): self.clear_button.set_sensitive(True) self.apply_filter() return False - + def apply_filter_clicked(self, obj): self.apply_filter() @@ -158,7 +158,7 @@ class SearchBar(object): index = self.filter_model.get_value(node, 1) inv = self.filter_model.get_value(node, 2) return (index, text, inv) - + def apply_filter(self, current_model=None): self.apply_text = str(self.filter_text.get_text()) self.filter_button.set_sensitive(False) diff --git a/gramps/gui/filters/sidebar/_citationsidebarfilter.py b/gramps/gui/filters/sidebar/_citationsidebarfilter.py index 375a1164b..7b5025b78 100644 --- a/gramps/gui/filters/sidebar/_citationsidebarfilter.py +++ b/gramps/gui/filters/sidebar/_citationsidebarfilter.py @@ -61,16 +61,16 @@ class CitationSidebarFilter(SidebarFilter): self.filter_src_pub = BasicEntry() self.filter_src_note = BasicEntry() self.filter_id = Gtk.Entry() - self.filter_page = Gtk.Entry() + self.filter_page = Gtk.Entry() self.filter_date = DateEntry(uistate, []) - + self.filter_conf = Gtk.ComboBox() model = Gtk.ListStore(str) for conf_value in sorted(conf_strings.keys()): model.append((_(conf_strings[conf_value]),)) self.filter_conf.set_model(model) self.filter_conf.set_active(Citation.CONF_NORMAL) - + self.filter_note = Gtk.Entry() self.filter_regex = Gtk.CheckButton(label=_('Use regular expressions')) @@ -169,15 +169,15 @@ class CitationSidebarFilter(SidebarFilter): rule = HasCitation([page, date, conf], use_regex=regex) generic_filter.add_rule(rule) - + if src_id: rule = RegExpSourceIdOf([src_id], use_regex=regex) generic_filter.add_rule(rule) - + rule = HasSource([src_title, src_author, src_abbr, src_pub], use_regex=regex) generic_filter.add_rule(rule) - + if note: rule = HasNoteRegexp([note], use_regex=regex) generic_filter.add_rule(rule) diff --git a/gramps/gui/filters/sidebar/_eventsidebarfilter.py b/gramps/gui/filters/sidebar/_eventsidebarfilter.py index f25d2f2af..a3540ca37 100644 --- a/gramps/gui/filters/sidebar/_eventsidebarfilter.py +++ b/gramps/gui/filters/sidebar/_eventsidebarfilter.py @@ -43,7 +43,7 @@ from gramps.gen.lib import Event, EventType from .. import build_filter_model from . import SidebarFilter from gramps.gen.filters import GenericFilterFactory, rules -from gramps.gen.filters.rules.event import (RegExpIdOf, HasNoteRegexp, +from gramps.gen.filters.rules.event import (RegExpIdOf, HasNoteRegexp, MatchesFilter, HasEvent, HasTag) GenericEventFilter = GenericFilterFactory('Event') @@ -62,18 +62,18 @@ class EventSidebarFilter(SidebarFilter): self.filter_event.set_type((EventType.CUSTOM, '')) self.etype = Gtk.ComboBox(has_entry=True) self.custom_types = dbstate.db.get_event_types() - + self.event_menu = widgets.MonitoredDataType( self.etype, self.filter_event.set_type, self.filter_event.get_type, custom_values=self.custom_types) - + self.filter_mainparts = widgets.BasicEntry() self.filter_date = widgets.DateEntry(uistate, []) self.filter_place = widgets.BasicEntry() self.filter_note = widgets.BasicEntry() - + self.filter_regex = Gtk.CheckButton(label=_('Use regular expressions')) self.tag = Gtk.ComboBox() @@ -144,7 +144,7 @@ class EventSidebarFilter(SidebarFilter): rule = HasEvent([etype, date, place, desc, mainparts], use_regex=regex) generic_filter.add_rule(rule) - + if note: rule = HasNoteRegexp([note], use_regex=regex) generic_filter.add_rule(rule) diff --git a/gramps/gui/filters/sidebar/_familysidebarfilter.py b/gramps/gui/filters/sidebar/_familysidebarfilter.py index a4582b336..dd53f3457 100644 --- a/gramps/gui/filters/sidebar/_familysidebarfilter.py +++ b/gramps/gui/filters/sidebar/_familysidebarfilter.py @@ -44,9 +44,9 @@ from gramps.gen.lib import Event, EventType, Family, FamilyRelType from .. import build_filter_model from . import SidebarFilter from gramps.gen.filters import GenericFilterFactory, rules -from gramps.gen.filters.rules.family import (RegExpIdOf, RegExpFatherName, - RegExpMotherName, RegExpChildName, - HasEvent, HasRelType, HasTag, +from gramps.gen.filters.rules.family import (RegExpIdOf, RegExpFatherName, + RegExpMotherName, RegExpChildName, + HasEvent, HasRelType, HasTag, HasNoteRegexp, MatchesFilter) GenericFamilyFilter = GenericFilterFactory('Family') @@ -63,7 +63,7 @@ class FamilySidebarFilter(SidebarFilter): self.filter_father = widgets.BasicEntry() self.filter_mother = widgets.BasicEntry() self.filter_child = widgets.BasicEntry() - + self.filter_event = Event() self.filter_event.set_type((EventType.CUSTOM, '')) self.etype = Gtk.ComboBox(has_entry=True) @@ -71,7 +71,7 @@ class FamilySidebarFilter(SidebarFilter): self.family_stub = Family() self.family_stub.set_relationship((FamilyRelType.CUSTOM, '')) self.rtype = Gtk.ComboBox(has_entry=True) - + self.event_menu = widgets.MonitoredDataType( self.etype, self.filter_event.set_type, @@ -81,7 +81,7 @@ class FamilySidebarFilter(SidebarFilter): self.rtype, self.family_stub.set_relationship, self.family_stub.get_relationship) - + self.filter_note = widgets.BasicEntry() self.filter_regex = Gtk.CheckButton(label=_('Use regular expressions')) @@ -171,7 +171,7 @@ class FamilySidebarFilter(SidebarFilter): if rtype: rule = HasRelType([rtype], use_regex=regex) generic_filter.add_rule(rule) - + if note: rule = HasNoteRegexp([note], use_regex=regex) generic_filter.add_rule(rule) diff --git a/gramps/gui/filters/sidebar/_mediasidebarfilter.py b/gramps/gui/filters/sidebar/_mediasidebarfilter.py index 23eb769cf..f2a2279c9 100644 --- a/gramps/gui/filters/sidebar/_mediasidebarfilter.py +++ b/gramps/gui/filters/sidebar/_mediasidebarfilter.py @@ -43,7 +43,7 @@ from ... import widgets from .. import build_filter_model from . import SidebarFilter from gramps.gen.filters import GenericFilterFactory, rules -from gramps.gen.filters.rules.media import (RegExpIdOf, HasMedia, HasTag, +from gramps.gen.filters.rules.media import (RegExpIdOf, HasMedia, HasTag, HasNoteRegexp, MatchesFilter) GenericMediaFilter = GenericFilterFactory('Media') @@ -127,7 +127,7 @@ class MediaSidebarFilter(SidebarFilter): rule = HasMedia([title, mime, path, date], use_regex=regex) generic_filter.add_rule(rule) - + if note: rule = HasNoteRegexp([note], use_regex=regex) generic_filter.add_rule(rule) diff --git a/gramps/gui/filters/sidebar/_notesidebarfilter.py b/gramps/gui/filters/sidebar/_notesidebarfilter.py index c9335aca2..9baeaf7b8 100644 --- a/gramps/gui/filters/sidebar/_notesidebarfilter.py +++ b/gramps/gui/filters/sidebar/_notesidebarfilter.py @@ -126,7 +126,7 @@ class NoteSidebarFilter(SidebarFilter): rule = HasNote([text, ntype], use_regex=regex) generic_filter.add_rule(rule) - + # check the Tag if tag: model = self.tag.get_model() @@ -143,7 +143,7 @@ class NoteSidebarFilter(SidebarFilter): generic_filter.add_rule(rule) return generic_filter - + def on_filters_changed(self, name_space): if name_space == 'Note': all_filter = GenericNoteFilter() diff --git a/gramps/gui/filters/sidebar/_personsidebarfilter.py b/gramps/gui/filters/sidebar/_personsidebarfilter.py index 641a76fb9..40434e324 100644 --- a/gramps/gui/filters/sidebar/_personsidebarfilter.py +++ b/gramps/gui/filters/sidebar/_personsidebarfilter.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -45,20 +45,20 @@ from gramps.gen.datehandler import displayer from .. import build_filter_model from . import SidebarFilter from gramps.gen.filters import GenericFilter, rules -from gramps.gen.filters.rules.person import (RegExpName, RegExpIdOf, IsMale, - IsFemale, HasUnknownGender, - HasEvent, HasTag, HasBirth, - HasDeath, HasNoteRegexp, +from gramps.gen.filters.rules.person import (RegExpName, RegExpIdOf, IsMale, + IsFemale, HasUnknownGender, + HasEvent, HasTag, HasBirth, + HasDeath, HasNoteRegexp, MatchesFilter) def extract_text(entry_widget): """ - Extract the text from the entry widget, strips off any extra spaces, - and converts the string to unicode. - - For some strange reason a gtk bug prevents the extracted string from being + Extract the text from the entry widget, strips off any extra spaces, + and converts the string to unicode. + + For some strange reason a gtk bug prevents the extracted string from being of type unicode. - + """ return str(entry_widget.get_text().strip()) @@ -79,16 +79,16 @@ class PersonSidebarFilter(SidebarFilter): self.filter_event.set_type((EventType.CUSTOM, '')) self.etype = Gtk.ComboBox(has_entry=True) self.event_menu = widgets.MonitoredDataType( - self.etype, - self.filter_event.set_type, + self.etype, + self.filter_event.set_type, self.filter_event.get_type) self.filter_note = widgets.BasicEntry() self.filter_gender = Gtk.ComboBoxText() - list(map(self.filter_gender.append_text, + list(map(self.filter_gender.append_text, [ _('any'), _('male'), _('female'), _('unknown') ])) self.filter_gender.set_active(0) - + self.filter_regex = Gtk.CheckButton(label=_('Use regular expressions')) self.tag = Gtk.ComboBox() @@ -114,10 +114,10 @@ class PersonSidebarFilter(SidebarFilter): exdate1 = Date() exdate2 = Date() - exdate1.set(Date.QUAL_NONE, Date.MOD_RANGE, - Date.CAL_GREGORIAN, (0, 0, 1800, False, + exdate1.set(Date.QUAL_NONE, Date.MOD_RANGE, + Date.CAL_GREGORIAN, (0, 0, 1800, False, 0, 0, 1900, False)) - exdate2.set(Date.QUAL_NONE, Date.MOD_BEFORE, + exdate2.set(Date.QUAL_NONE, Date.MOD_BEFORE, Date.CAL_GREGORIAN, (0, 0, 1850, False)) msg1 = displayer.display(exdate1) @@ -126,9 +126,9 @@ class PersonSidebarFilter(SidebarFilter): self.add_text_entry(_('Name'), self.filter_name) self.add_text_entry(_('ID'), self.filter_id) self.add_entry(_('Gender'), self.filter_gender) - self.add_text_entry(_('Birth date'), self.filter_birth, + self.add_text_entry(_('Birth date'), self.filter_birth, _('example: "%(msg1)s" or "%(msg2)s"') % {'msg1':msg1, 'msg2':msg2}) - self.add_text_entry(_('Death date'), self.filter_death, + self.add_text_entry(_('Death date'), self.filter_death, _('example: "%(msg1)s" or "%(msg2)s"') % {'msg1':msg1, 'msg2':msg2}) self.add_entry(_('Event'), self.etype) self.add_text_entry(_('Note'), self.filter_note) @@ -170,14 +170,14 @@ class PersonSidebarFilter(SidebarFilter): # check to see if the filter is empty. If it is empty, then # we don't build a filter - empty = not (name or gid or birth or death or etype + empty = not (name or gid or birth or death or etype or note or gender or regex or tag or generic) if empty: generic_filter = None else: # build a GenericFilter generic_filter = GenericFilter() - + # if the name is not empty, choose either the regular expression # version or the normal text match if name: @@ -203,10 +203,10 @@ class PersonSidebarFilter(SidebarFilter): if etype: rule = HasEvent([etype, '', '', '', '', True], use_regex=regex) generic_filter.add_rule(rule) - + # Build birth event filter if needed # Arguments for the HasBirth filter are Date, Place, and Description - # Since the value we extracted to the "birth" variable is the + # Since the value we extracted to the "birth" variable is the # request date, we pass it as the first argument if birth: rule = HasBirth([birth, '', '']) @@ -229,7 +229,7 @@ class PersonSidebarFilter(SidebarFilter): attr = model.get_value(node, 0) rule = HasTag([attr]) generic_filter.add_rule(rule) - + if self.generic.get_active() != 0: model = self.generic.get_model() node = self.generic.get_active_iter() diff --git a/gramps/gui/filters/sidebar/_placesidebarfilter.py b/gramps/gui/filters/sidebar/_placesidebarfilter.py index 04bff9642..faf1743db 100644 --- a/gramps/gui/filters/sidebar/_placesidebarfilter.py +++ b/gramps/gui/filters/sidebar/_placesidebarfilter.py @@ -65,7 +65,7 @@ class PlaceSidebarFilter(SidebarFilter): self.filter_place = Place() self.filter_place.set_type((PlaceType.CUSTOM, '')) self.ptype = Gtk.ComboBox(has_entry=True) - + self.place_menu = widgets.MonitoredDataType( self.ptype, self.filter_place.set_type, @@ -76,7 +76,7 @@ class PlaceSidebarFilter(SidebarFilter): self.filter_code = widgets.BasicEntry() self.filter_enclosed = widgets.PlaceEntry(dbstate, uistate, []) self.filter_note = widgets.BasicEntry() - + self.filter_regex = Gtk.CheckButton(label=_('Use regular expressions')) self.tag = Gtk.ComboBox() self.generic = Gtk.ComboBox() @@ -144,7 +144,7 @@ class PlaceSidebarFilter(SidebarFilter): rule = HasData([name, ptype, code], use_regex=regex) generic_filter.add_rule(rule) - + if note: rule = HasNoteRegexp([note], use_regex=regex) generic_filter.add_rule(rule) diff --git a/gramps/gui/filters/sidebar/_reposidebarfilter.py b/gramps/gui/filters/sidebar/_reposidebarfilter.py index 2dfa3cc92..fcefd12f8 100644 --- a/gramps/gui/filters/sidebar/_reposidebarfilter.py +++ b/gramps/gui/filters/sidebar/_reposidebarfilter.py @@ -44,7 +44,7 @@ from .. import build_filter_model from . import SidebarFilter from gramps.gen.filters import GenericFilterFactory, rules from gramps.gen.filters.rules.repository import (RegExpIdOf, HasRepo, HasTag, - HasNoteRegexp, MatchesFilter) + HasNoteRegexp, MatchesFilter) GenericRepoFilter = GenericFilterFactory('Repository') #------------------------------------------------------------------------- @@ -139,7 +139,7 @@ class RepoSidebarFilter(SidebarFilter): rule = HasRepo([title, rtype, address, url], use_regex=regex) generic_filter.add_rule(rule) - + if note: rule = HasNoteRegexp([note], use_regex=regex) generic_filter.add_rule(rule) @@ -160,13 +160,13 @@ class RepoSidebarFilter(SidebarFilter): generic_filter.add_rule(rule) return generic_filter - + def on_filters_changed(self, name_space): if name_space == 'Repository': all_filter = GenericRepoFilter() all_filter.set_name(_("None")) all_filter.add_rule(rules.repository.AllRepos([])) - self.generic.set_model(build_filter_model('Repository', + self.generic.set_model(build_filter_model('Repository', [all_filter])) self.generic.set_active(0) diff --git a/gramps/gui/filters/sidebar/_sidebarfilter.py b/gramps/gui/filters/sidebar/_sidebarfilter.py index a6d3b0ad0..0a3159711 100644 --- a/gramps/gui/filters/sidebar/_sidebarfilter.py +++ b/gramps/gui/filters/sidebar/_sidebarfilter.py @@ -55,7 +55,7 @@ class SidebarFilter(DbGUIElement): self.grid.set_column_spacing(6) self.apply_btn = Gtk.Button.new_with_mnemonic(_('_Find')) self.clear_btn = Gtk.Button() - + self._init_interface() uistate.connect('filters-changed', self.on_filters_changed) dbstate.connect('database-changed', self._db_changed) @@ -63,7 +63,7 @@ class SidebarFilter(DbGUIElement): self.dbstate = dbstate self.namespace = namespace self.__tag_list = [] - self._tag_rebuild() + self._tag_rebuild() def _init_interface(self): self.create_widget() @@ -80,7 +80,7 @@ class SidebarFilter(DbGUIElement): hbox.pack_start(image, False, False, 0) hbox.pack_start(label, False, True, 0) hbox.set_spacing(4) - + self.clear_btn.add(hbox) self.clear_btn.connect('clicked', self.clear) @@ -151,7 +151,7 @@ class SidebarFilter(DbGUIElement): Called when filters are changed. """ pass - + def _db_changed(self, db): """ Called when the database is changed. @@ -171,7 +171,7 @@ class SidebarFilter(DbGUIElement): Connect database signals defined in the signal map. """ for sig in self.signal_map: - self.callman.add_db_signal(sig, self.signal_map[sig]) + self.callman.add_db_signal(sig, self.signal_map[sig]) def _tag_add(self, handle_list): """ @@ -181,7 +181,7 @@ class SidebarFilter(DbGUIElement): tag = self.dbstate.db.get_tag_from_handle(handle) insort_left(self.__tag_list, (tag.get_name(), handle)) self.on_tags_changed([item[0] for item in self.__tag_list]) - + def _tag_update(self, handle_list): """ Called when tags are updated. @@ -192,7 +192,7 @@ class SidebarFilter(DbGUIElement): tag = self.dbstate.db.get_tag_from_handle(handle) insort_left(self.__tag_list, (tag.get_name(), handle)) self.on_tags_changed([item[0] for item in self.__tag_list]) - + def _tag_delete(self, handle_list): """ Called when tags are deleted. @@ -200,7 +200,7 @@ class SidebarFilter(DbGUIElement): self.__tag_list = [item for item in self.__tag_list if item[1] not in handle_list] self.on_tags_changed([item[0] for item in self.__tag_list]) - + def _tag_rebuild(self): """ Called when the tag list needs to be rebuilt. @@ -213,7 +213,7 @@ class SidebarFilter(DbGUIElement): handle = handle.decode('utf-8') self.__tag_list.append((tag.get_name(), handle)) self.on_tags_changed([item[0] for item in self.__tag_list]) - + def on_tags_changed(self, tag_list): """ Called when tags are changed. diff --git a/gramps/gui/filters/sidebar/_sourcesidebarfilter.py b/gramps/gui/filters/sidebar/_sourcesidebarfilter.py index f116995a5..0c5f99f33 100644 --- a/gramps/gui/filters/sidebar/_sourcesidebarfilter.py +++ b/gramps/gui/filters/sidebar/_sourcesidebarfilter.py @@ -114,7 +114,7 @@ class SourceSidebarFilter(SidebarFilter): tag = self.tag.get_active() > 0 gen = self.generic.get_active() > 0 - empty = not (gid or title or author or abbr or pub or note or regex + empty = not (gid or title or author or abbr or pub or note or regex or tag or gen) if empty: generic_filter = None @@ -126,7 +126,7 @@ class SourceSidebarFilter(SidebarFilter): rule = HasSource([title, author, abbr, pub], use_regex=regex) generic_filter.add_rule(rule) - + if note: rule = HasNoteRegexp([note], use_regex=regex) generic_filter.add_rule(rule) diff --git a/gramps/gui/glade.py b/gramps/gui/glade.py index 1ae16c709..591f5c848 100644 --- a/gramps/gui/glade.py +++ b/gramps/gui/glade.py @@ -59,19 +59,19 @@ class Glade(Gtk.Builder): Glade class: Manage glade files as Gtk.Builder objects """ __slots__ = ['__toplevel', '__filename', '__dirname'] - + def __init__(self, filename=None, dirname=None, toplevel=None): """ Class Constructor: Returns a new instance of the Glade class - + :type filename: string :param filename: The name of the glade file to be used. Defaults to None :type dirname: string - :param dirname: The directory to search for the glade file. Defaults to + :param dirname: The directory to search for the glade file. Defaults to None which will cause a search for the file in the default directory followed by the directory of the calling module. :type toplevel: toplevel - :param toplevel: The toplevel object to search for in the glade file. + :param toplevel: The toplevel object to search for in the glade file. Defaults to None, which will cause a search for a toplevel matching the file name. :rtype: object reference @@ -84,7 +84,7 @@ class Glade(Gtk.Builder): dirname_given = dirname is not None # if filename not given, use module name to derive it - + if not filename_given: filename = sys._getframe(1).f_code.co_filename filename = os.path.basename(filename) @@ -92,21 +92,21 @@ class Glade(Gtk.Builder): filename = filename.lstrip('_').lower() # if dirname not given, use current directory - + if not dirname_given: dirname = sys._getframe(1).f_code.co_filename dirname = os.path.dirname(dirname) - + # try to find the glade file - + if filename_given and dirname_given: # both given -- use them path = os.path.join(dirname, filename) - + elif filename_given: # try default directory first path = os.path.join(GLADE_DIR, filename) - if not os.path.exists(path): # then module directory + if not os.path.exists(path): # then module directory path = os.path.join(dirname, filename) - + elif dirname_given: # dirname given -- use it path = os.path.join(dirname, filename) @@ -118,14 +118,14 @@ class Glade(Gtk.Builder): path = os.path.join(GLADE_DIR, filename) if not os.path.exists(path): path = os.path.join(dirname, filename) - + # try to build Gtk objects from glade file. Let exceptions happen - + self.add_from_file(path) self.__dirname, self.__filename = os.path.split(path) - + # try to find the toplevel widget - + if toplevel: # toplevel is given self.__toplevel = self.get_object(toplevel) else: # toplevel not given @@ -145,44 +145,44 @@ class Glade(Gtk.Builder): break else: self.__toplevel = None - + def __get_filename(self): """ __get_filename: return filename of glade file - :rtype: string + :rtype: string :returns: filename of glade file """ return self.__filename - + filename = property(__get_filename) - + def __get_dirname(self): """ __get_dirname: return directory where glade file found - :rtype: string + :rtype: string :returns: directory where glade file found """ return self.__dirname dirname = property(__get_dirname) - + def __get_toplevel(self): """ __get_toplevel: return toplevel object - :rtype: object + :rtype: object :returns: toplevel object """ return self.__toplevel - + def __set_toplevel(self, toplevel): """ __set_toplevel: set toplevel object - + :type toplevel: string :param toplevel: The name of the toplevel object to use """ self.__toplevel = self.get_object(toplevel) - + toplevel = property(__get_toplevel, __set_toplevel) def get_child_object(self, value, toplevel=None): @@ -195,18 +195,18 @@ class Glade(Gtk.Builder): :type toplevel: string :param toplevel: The name of the toplevel object to us :rtype: object - :returns: child object + :returns: child object """ if not toplevel: toplevel = self.__toplevel if not toplevel: raise ValueError("Top level object required") - + if isinstance(toplevel, str): toplevel = self.get_object(toplevel) - + # Simple Breadth-First Search - + queue = [toplevel] while queue: obj = queue.pop(0) diff --git a/gramps/gui/glade/catalog/grampswidgets.py b/gramps/gui/glade/catalog/grampswidgets.py index 687775912..88c422f95 100644 --- a/gramps/gui/glade/catalog/grampswidgets.py +++ b/gramps/gui/glade/catalog/grampswidgets.py @@ -27,7 +27,7 @@ class ValidatableMaskedEntry(Gtk.Entry): class UndoableEntry(Gtk.Entry): __gtype_name__ = 'UndoableEntry' - + class StyledTextEditor(Gtk.TextView): __gtype_name__ = 'StyledTextEditor' diff --git a/gramps/gui/grampsgui.py b/gramps/gui/grampsgui.py index 3d2cce103..b7a55071b 100644 --- a/gramps/gui/grampsgui.py +++ b/gramps/gui/grampsgui.py @@ -59,7 +59,7 @@ except: "You need a version which has the function 'require_version' " "to start Gramps")) sys.exit(0) - + if not PYGOBJ_ERR: try: from gi.repository import GObject, GLib @@ -72,8 +72,8 @@ if PYGOBJ_ERR: print((_("Your pygobject version does not meet the requirements.\n" "At least pygobject %(major)d.%(feature)d.%(minor)d " "is needed to start Gramps with a GUI.\n\n" - "Gramps will terminate now.") % - {'major':MIN_PYGOBJECT_VERSION[0], + "Gramps will terminate now.") % + {'major':MIN_PYGOBJECT_VERSION[0], 'feature':MIN_PYGOBJECT_VERSION[1], 'minor':MIN_PYGOBJECT_VERSION[2]})) sys.exit(0) @@ -101,8 +101,8 @@ if (gtk_major, gtk_minor) < MIN_GTK_VERSION: print(_("Your Gtk version does not meet the requirements.\n" "At least %(major)d.%(minor)d " "is needed to start Gramps with a GUI.\n\n" - "Gramps will terminate now.") % - { 'major' : MIN_GTK_VERSION[0], + "Gramps will terminate now.") % + { 'major' : MIN_GTK_VERSION[0], 'minor' : MIN_GTK_VERSION[1] } ) sys.exit(0) @@ -196,7 +196,7 @@ class Gramps(object): 'bold_end' : '' } ) dbstate = DbState() - self.vm = ViewManager(dbstate, + self.vm = ViewManager(dbstate, config.get("interface.view-categories")) self.vm.init_interface() @@ -283,7 +283,7 @@ def __startgramps(errors, argparser): "You can also change manually the startup view in the gramps.ini file \n" "by changing the last-view parameter.\n" ), exc_info=True) - + # start Gramps, errors stop the gtk loop try: quit_now = False diff --git a/gramps/gui/listmodel.py b/gramps/gui/listmodel.py index e993bd7de..7150e45f6 100644 --- a/gramps/gui/listmodel.py +++ b/gramps/gui/listmodel.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -24,7 +24,7 @@ Provide the basic functionality for a list view #------------------------------------------------------------------------- # -# GTK +# GTK # #------------------------------------------------------------------------- from gi.repository import Pango, Gdk, Gtk, GdkPixbuf @@ -42,7 +42,7 @@ IMAGE = 3 INTEGER = 4 COLOR = 5 -NOSORT = -1 +NOSORT = -1 #------------------------------------------------------------------------- # @@ -78,8 +78,8 @@ class ListModel(object): right_click: Function called when the user right-clicks on a row. """ - def __init__(self, tree, dlist, select_func=None, event_func=None, - mode=Gtk.SelectionMode.SINGLE, list_mode="list", + def __init__(self, tree, dlist, select_func=None, event_func=None, + mode=Gtk.SelectionMode.SINGLE, list_mode="list", right_click=None): self.tree = tree @@ -124,7 +124,7 @@ class ListModel(object): self.__build_columns(dlist) self.connect_model() - + if select_func: self.selection.connect('changed', select_func) if event_func or right_click: @@ -157,7 +157,7 @@ class ListModel(object): name = item elif isinstance(item, dict): # valid fields: name, sort_id, width, type, editable, callback, visible_col - name = [item.get("name", " "), item.get("sort_id", NOSORT), item.get("width", 10), + name = [item.get("name", " "), item.get("sort_id", NOSORT), item.get("width", 10), item.get("type", TEXT), item.get("editable", False), item.get("callback", None)] visible_col = item.get("visible_col", None) if len(name) == 3: @@ -186,7 +186,7 @@ class ListModel(object): elif name[0] and name[3] == COLOR: renderer = Gtk.CellRendererText() if visible_col is not None: - column = Gtk.TreeViewColumn(name[0], renderer, background=cnum, + column = Gtk.TreeViewColumn(name[0], renderer, background=cnum, visible=visible_col) else: column = Gtk.TreeViewColumn(name[0], renderer, background=cnum) @@ -254,10 +254,10 @@ class ListModel(object): Enables or disables reordering of data """ self.tree.set_reorderable(order) - + def new_model(self): """ - Create a new model instance + Create a new model instance """ if self.model: self.cid = self.model.get_sort_column_id() @@ -271,7 +271,7 @@ class ListModel(object): self.selection = self.tree.get_selection() self.selection.set_mode(self.mode) self.sel_iter = None - + def connect_model(self): """ Connects the model to the associated tree @@ -282,7 +282,7 @@ class ListModel(object): # if the sort column has not been defined (val[0] == -2), set # the sort column to the first column - + val = self.model.get_sort_column_id() if val[0] == -2 and self.cid: self.model.set_sort_column_id(self.cid[0], self.cid[1]) @@ -301,7 +301,7 @@ class ListModel(object): else: self.model.set_sort_column_id(self.cids[0], val[1]) self.model.sort_column_changed() - + def get_selected(self): """ Return the selected items @@ -378,7 +378,7 @@ class ListModel(object): """ self.model.remove(node) self.count -= 1 - + def get_row(self, node): """ Return the row associated with the selected node @@ -397,14 +397,14 @@ class ListModel(object): Selects the item based on iter """ self.selection.select_iter(node) - + def get_object(self, node): """ Return the object associated with the node. This is controlled by extracting the data from the associated data index """ return self.model.get_value(node, self.data_index) - + def insert(self, position, data, info=None, select=0): """ Inserts the item at the specified position in the model. @@ -421,13 +421,13 @@ class ListModel(object): if select: self.selection.select_iter(node) return node - + def get_data(self, node, cols): """ Return a list of data from the model associated with the node """ return [ self.model.get_value(node, c) for c in cols ] - + def add(self, data, info=None, select=0, node=None): """ Add the data to the model at the end of the model diff --git a/gramps/gui/logger/__init__.py b/gramps/gui/logger/__init__.py index b846baebb..3c359b111 100644 --- a/gramps/gui/logger/__init__.py +++ b/gramps/gui/logger/__init__.py @@ -42,11 +42,11 @@ Usage: rh = RotateHandler(capacity=20) rh.setLevel(logging.DEBUG) - + gtkh = GtkHandler(rotate_handler=rh) gtkh.setLevel(logging.ERROR) - l = logging.getLogger("GtkHandlerTest") + l = logging.getLogger("GtkHandlerTest") l.setLevel(logging.DEBUG) l.addHandler(rh) diff --git a/gramps/gui/logger/_errorreportassistant.py b/gramps/gui/logger/_errorreportassistant.py index 021c297dc..37f1c6fab 100644 --- a/gramps/gui/logger/_errorreportassistant.py +++ b/gramps/gui/logger/_errorreportassistant.py @@ -36,7 +36,7 @@ try: BSDDB_STR = str(bsddb.__version__) + " " + str(bsddb.db.version()) except: BSDDB_STR = 'not found' - + #------------------------------------------------------------------------- # # Gramps modules @@ -121,13 +121,13 @@ class ErrorReportAssistant(Gtk.Assistant): """ Copy the bug report to the clipboard. """ - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_CLIPBOARD) clipboard.set_text( self._final_report_text_buffer.get_text( self._final_report_text_buffer.get_start_iter(), self._final_report_text_buffer.get_end_iter(), True), -1) - + clipboard = t = Gtk.Clipboard.get(Gdk.SELECTION_PRIMARY) clipboard.set_text( self._final_report_text_buffer.get_text( @@ -143,7 +143,7 @@ class ErrorReportAssistant(Gtk.Assistant): % self._final_report_text_buffer.get_text( self._final_report_text_buffer.get_start_iter(), self._final_report_text_buffer.get_end_iter(), True)) - + def _start_gramps_bts_in_browser(self, obj=None): """ Start a web browser to report the bug. @@ -176,14 +176,14 @@ class ErrorReportAssistant(Gtk.Assistant): get_env_var('LANG',''), operatingsystem, distribution, - '%d.%d.%d' % (Gtk.get_major_version(), + '%d.%d.%d' % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()), '%d.%d.%d' % GObject.pygobject_version, cairo.version_info) def _reset_error_details(self, obj=None): """ - Reset the error details buffer to its original contents. + Reset the error details buffer to its original contents. """ self._error_details_text_buffer.set_text( "\n".join(self._rotate_handler.get_formatted_log( @@ -199,7 +199,7 @@ class ErrorReportAssistant(Gtk.Assistant): def _reset_sys_information(self, obj=None): """ - Reset the system information buffer to its original contents. + Reset the system information buffer to its original contents. """ self._sys_information_text_buffer.set_text( self._get_sys_information()) @@ -276,12 +276,12 @@ class ErrorReportAssistant(Gtk.Assistant): self._error_details_text_buffer = textview.get_buffer() self._reset_error_details() - + swin.add(textview) sw_frame = Gtk.Frame() sw_frame.add(swin) - + reset = Gtk.Button("Reset") reset.connect('clicked', self._reset_error_details) clear = Gtk.Button("Clear") @@ -303,7 +303,7 @@ class ErrorReportAssistant(Gtk.Assistant): error_details_box.set_vexpand(True) error_details_box.set_property("margin", 12) - + error_details_frame = Gtk.Frame() error_details_frame.set_border_width(3) error_details_frame.set_label("%s" % _("Error Details")) @@ -361,7 +361,7 @@ class ErrorReportAssistant(Gtk.Assistant): sw_frame = Gtk.Frame() sw_frame.add(swin) - + reset = Gtk.Button("Reset") reset.connect('clicked', self._reset_sys_information) clear = Gtk.Button("Clear") @@ -437,7 +437,7 @@ class ErrorReportAssistant(Gtk.Assistant): sw_frame = Gtk.Frame() sw_frame.add(swin) - + clear = Gtk.Button("Clear") clear.connect('clicked', self._clear_user_information) @@ -506,13 +506,13 @@ class ErrorReportAssistant(Gtk.Assistant): textview.set_editable(False) textview.set_cursor_visible(False) - self._final_report_text_buffer = textview.get_buffer() + self._final_report_text_buffer = textview.get_buffer() swin.add(textview) sw_frame = Gtk.Frame() sw_frame.add(swin) - + summary_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) summary_box.pack_start(label, False, False, 0) summary_box.pack_start(sw_frame, True, True, 0) @@ -579,7 +579,7 @@ class ErrorReportAssistant(Gtk.Assistant): url_button.connect('clicked', self._start_gramps_bts_in_browser) url_button_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) url_button_vbox.pack_start(url_button, True, False, 0) - + url_box = Gtk.Box() url_box.pack_start(url_label, True, True, 0) url_box.pack_start(url_button_vbox, False, False, 0) @@ -588,7 +588,7 @@ class ErrorReportAssistant(Gtk.Assistant): url_frame = Gtk.Frame() url_frame.add(url_box) - + clip_label = Gtk.Label(label=_("Use this button " "to copy the bug report onto the clipboard. " "Then go to the bug tracking website by using " @@ -603,7 +603,7 @@ class ErrorReportAssistant(Gtk.Assistant): clip_button.connect('clicked', self._copy_to_clipboard) clip_button_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) clip_button_vbox.pack_start(clip_button, True, False, 0) - + clip_box = Gtk.Box() clip_box.pack_start(clip_label, True, True, 0) clip_box.pack_start(clip_button_vbox, False, False, 0) @@ -698,5 +698,5 @@ class ErrorReportAssistant(Gtk.Assistant): self._sys_information_text_buffer.get_text( self._sys_information_text_buffer.get_start_iter(), - self._sys_information_text_buffer.get_end_iter(), True) + self._sys_information_text_buffer.get_end_iter(), True) ) diff --git a/gramps/gui/logger/_errorview.py b/gramps/gui/logger/_errorview.py index 1406316bc..a6257fd1d 100644 --- a/gramps/gui/logger/_errorview.py +++ b/gramps/gui/logger/_errorview.py @@ -48,7 +48,7 @@ class ErrorView(object): """ A Dialog for displaying errors. """ - + def __init__(self, error_detail, rotate_handler): """ Initialize the handler with the buffer size. @@ -56,7 +56,7 @@ class ErrorView(object): self._error_detail = error_detail self._rotate_handler = rotate_handler - + self.draw_window() self.run() @@ -76,7 +76,7 @@ class ErrorView(object): def help_clicked(self): """Display the relevant portion of GRAMPS manual""" - + display_help(WIKI_HELP_PAGE, WIKI_HELP_SEC) def draw_window(self): @@ -114,25 +114,25 @@ class ErrorView(object): instructions_label.set_use_markup(True) vbox.pack_start(instructions_label, False, False, 5) - + tb_frame = Gtk.Frame(label=_("Error Detail")) tb_frame.set_border_width(6) tb_label = Gtk.TextView() tb_label.get_buffer().set_text(self._error_detail.get_formatted_log()) tb_label.set_border_width(6) tb_label.set_editable(False) - + scroll = Gtk.ScrolledWindow() scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) scroll.set_size_request(-1, 60) - + tb_frame.add(scroll) scroll.add(tb_label) tb_expander = Gtk.Expander(label='%s' % _("Error Detail")) tb_expander.set_use_markup(True) tb_expander.add(tb_frame) - + vbox.pack_start(tb_expander, True, True, 5) self.top.add_button(_('_Cancel'), Gtk.ResponseType.CANCEL) diff --git a/gramps/gui/logger/_gtkhandler.py b/gramps/gui/logger/_gtkhandler.py index 550a88596..7e644f193 100644 --- a/gramps/gui/logger/_gtkhandler.py +++ b/gramps/gui/logger/_gtkhandler.py @@ -28,7 +28,7 @@ class GtkHandler(logging.Handler): """ A handler class which pops up a Gtk Window when a log message occurs. """ - + def __init__(self,rotate_handler=None): """ Initialize the handler with a optional rotate_logger instance. diff --git a/gramps/gui/logger/test/rotate_handler_test.py b/gramps/gui/logger/test/rotate_handler_test.py index 53eabaf70..3fb30f441 100644 --- a/gramps/gui/logger/test/rotate_handler_test.py +++ b/gramps/gui/logger/test/rotate_handler_test.py @@ -28,11 +28,11 @@ class RotateHandlerTest(unittest.TestCase): def test_buffer_recall(self): """Test that simple recall of messages works.""" - + rh = RotateHandler(10) l = logging.getLogger("RotateHandlerTest") l.setLevel(logging.DEBUG) - + l.addHandler(rh) log_message = "Debug message" @@ -46,29 +46,29 @@ class RotateHandlerTest(unittest.TestCase): l.removeHandler(rh) - + def test_buffer_rotation(self): """Test that buffer correctly rolls over when capacity is reached.""" rh = RotateHandler(10) l = logging.getLogger("RotateHandlerTest") l.setLevel(logging.DEBUG) - + l.addHandler(rh) log_messages = 20 * [None] for i in range(0,20): log_messages[i] = "Message %d" % (i) - + [l.info(log_messages[i]) for i in range(0,10)] - self.assertEqual(len(rh.get_buffer()), 10, + self.assertEqual(len(rh.get_buffer()), 10, "Message buffer wrong size, should be '10' is '%d'" % (len(rh.get_buffer()))) buffer = rh.get_buffer() - + for i in range(0,10): self.assertEqual(buffer[i].getMessage(), log_messages[i], "Message buffer content is wrong, should be '%s' is '%s'. i = '%d'" @@ -86,16 +86,16 @@ class RotateHandlerTest(unittest.TestCase): [l.info(log_messages[i]) for i in range(11,20)] - + buffer = rh.get_buffer() for i in range(0,10): self.assertEqual(buffer[i].getMessage(), log_messages[i+10], "Message buffer content is wrong, should be '%s' is '%s'. i = '%d'" % (log_messages[i+10], buffer[i].getMessage(),i)) - + l.removeHandler(rh) - + def testSuite(): suite = unittest.makeSuite(RotateHandlerTest,'test') return suite diff --git a/gramps/gui/makefilter.py b/gramps/gui/makefilter.py index 23623a2a5..74a21c88f 100644 --- a/gramps/gui/makefilter.py +++ b/gramps/gui/makefilter.py @@ -21,7 +21,7 @@ import time from .editors import EditFilter from gramps.gen.const import CUSTOM_FILTERS -from gramps.gen.filters import (rules, FilterList, GenericFilterFactory, +from gramps.gen.filters import (rules, FilterList, GenericFilterFactory, reload_custom_filters) from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext @@ -43,7 +43,7 @@ def make_filter(dbstate, uistate, objclass, gramps_ids, title=None): title = title() filter.set_name(title) struct_time = time.localtime() - filter.set_comment( _("Created on %(year)4d/%(month)02d/%(day)02d") % { + filter.set_comment( _("Created on %(year)4d/%(month)02d/%(day)02d") % { 'year': struct_time.tm_year, 'month': struct_time.tm_mon, 'day': struct_time.tm_mday}) diff --git a/gramps/gui/managedwindow.py b/gramps/gui/managedwindow.py index 16ee33a67..caaff047b 100644 --- a/gramps/gui/managedwindow.py +++ b/gramps/gui/managedwindow.py @@ -109,7 +109,7 @@ class GrampsWindowManager(object): self.action_group = Gtk.ActionGroup(name='WindowManger') self.active = DISABLED self.ui = _win_top + _win_btm - + def disable(self): """ Remove the UI and action groups if the navigation is enabled @@ -138,7 +138,7 @@ class GrampsWindowManager(object): # Find an item given its ID # Return None if the ID is not found return self.id2item.get(item_id, None) - + def close_track(self, track): # This is called when item needs to be closed # Closes all its children and then removes the item from the tree. @@ -180,7 +180,7 @@ class GrampsWindowManager(object): # We need the whole gymnastics below because our item # may actually be a list consisting of a single real # item and empty lists. - + # find the track corresponding to the parent item parent_track = track[:-1] # find index of our item in parent @@ -206,7 +206,7 @@ class GrampsWindowManager(object): # if the item is identifiable then we need to remember # its id so that in the future we recall this window # instead of spawning a new one - # So people can make as many windows of type item.window_id = None + # So people can make as many windows of type item.window_id = None # Use this for add dialogs, where users may add as many values # simultaneously as they want. # Actually, we should do this away, as requiring at least id(obj) @@ -272,13 +272,13 @@ class GrampsWindowManager(object): else: idval = self.generate_id(i) data.write('' - % self.generate_id(i)) - action_data.append((idval, None, i.menu_label, + % self.generate_id(i)) + action_data.append((idval, None, i.menu_label, None, None, self.call_back_factory(i))) if isinstance(mlist, (list, tuple)): data.write('') - + def build_windows_menu(self): if self.active != DISABLED: self.uimanager.remove_ui(self.active) @@ -305,7 +305,7 @@ class GrampsWindowManager(object): class ManagedWindow(object): """ Managed window base class. - + This class provides all the goodies necessary for user-friendly window management in GRAMPS: registering the menu item under the Windows menu, keeping track of child windows, closing them on close/delete @@ -314,11 +314,11 @@ class ManagedWindow(object): def __init__(self, uistate, track, obj): """ Create child windows and add itself to menu, if not there already. - - + + The usage from derived classes is envisioned as follows: - - + + from .managedwindow import ManagedWindow class SomeWindowClass(ManagedWindow): def __init__(self,uistate,dbstate,track): @@ -333,17 +333,17 @@ class ManagedWindow(object): menu_label) # Proceed with the class. ... - + :param uistate: gramps uistate - :param track: {list of parent windows, [] if the main GRAMPS window + :param track: {list of parent windows, [] if the main GRAMPS window is the parent} - :param obj: The object that is used to id the managed window, + :param obj: The object that is used to id the managed window, The inheriting object needs a method build_menu_names(self, obj) which works on this obj and creates menu labels for use in the Gramps Window Menu. If self.submenu_label ='' then leaf, otherwise branch - - + + """ window_key = self.build_window_key(obj) menu_label, submenu_label = self.build_menu_names(obj) @@ -352,7 +352,7 @@ class ManagedWindow(object): self.width_key = None self.height_key = None self.__refs_for_deletion = [] - + if uistate and uistate.gwm.get_item_from_id(window_key): uistate.gwm.get_item_from_id(window_key).present() raise WindowActiveError('This window is already active') @@ -392,18 +392,18 @@ class ManagedWindow(object): def set_window(self, window, title, text, msg=None, isWindow=False): """ Set the window that is managed. - + :param window: if isWindow=False window must be a Gtk.Window() object, otherwise None :param title: a label widget in which to write the title, None if not needed :param text: text to use as title of window and in title param :param msg: if not None, use msg as title of window instead of text - :param isWindow: {if isWindow than self is the window - (so self inherits from Gtk.Window and + :param isWindow: {if isWindow than self is the window + (so self inherits from Gtk.Window and from ManagedWindow) - if not isWindow, than window is the Window to manage, + if not isWindow, than window is the Window to manage, and after this method self.window stores it. } - + """ self.isWindow = isWindow self.msg = msg @@ -415,7 +415,7 @@ class ManagedWindow(object): #closing the Gtk.Window must also close ManagedWindow self.window = window self.window.connect('delete-event', self.close) - + def get_window(self): """ Return the managed window. @@ -436,7 +436,7 @@ class ManagedWindow(object): def build_window_key(self, obj): return id(obj) - + def define_glade(self, top_module, glade_file=None): if glade_file is None: raise TypeError("ManagedWindow.define_glade: no glade file") @@ -463,7 +463,7 @@ class ManagedWindow(object): self.set_transient_for(self.parent_window) self.opened = True self.show_all() - + else : assert self.window, "ManagedWindow: self.window does not exist!" self.window.set_transient_for(self.parent_window) @@ -471,17 +471,17 @@ class ManagedWindow(object): self.window.show_all() def modal_call(self, after_ok_func=None): - """ + """ Method to do modal run of the ManagedWindow. - Connect the OK button to a method that checks if all is ok, + Connect the OK button to a method that checks if all is ok, Do not call close, close is called here. (if not ok, do self.window.run() to obtain new response ) TODO: remove close here and do close in ReportDialog, this can only be done, once all methods use modal_call() instead of their own implementation - Connect Cancel to do close, delete event is connected to close + Connect Cancel to do close, delete event is connected to close here in ManagedWindow. - Do not generete RESPONSE_OK/CANCEL/DELETE_EVENT on button clicks + Do not generete RESPONSE_OK/CANCEL/DELETE_EVENT on button clicks of other buttons after_ok_func is called on ok click in this method """ @@ -557,7 +557,7 @@ class ManagedWindow(object): If the object is a Gramps widget then it should have a clean_up method which can be called that removes any other GTK object it contains. """ - while len(self.__refs_for_deletion): + while len(self.__refs_for_deletion): attr = self.__refs_for_deletion.pop() obj = getattr(self, attr) if hasattr(obj, 'clean_up'): diff --git a/gramps/gui/merge/mergecitation.py b/gramps/gui/merge/mergecitation.py index f3b1869a6..b3e248985 100644 --- a/gramps/gui/merge/mergecitation.py +++ b/gramps/gui/merge/mergecitation.py @@ -107,7 +107,7 @@ class MergeCitation(ManagedWindow): for widget_name in ('gramps1', 'gramps2', 'gramps_btn1', 'gramps_btn2'): self.get_widget(widget_name).set_sensitive(False) - + # Main window widgets that determine which handle survives rbutton1 = self.get_widget("handle_btn1") rbutton_label1 = self.get_widget("label_handle_btn1") @@ -150,7 +150,7 @@ class MergeCitation(ManagedWindow): else: phoenix = self.citation2 titanic = self.citation1 - # Add second handle to history so that when merge is complete, + # Add second handle to history so that when merge is complete, # phoenix is the selected row. self.uistate.set_active(phoenix.get_handle(), 'Citation') diff --git a/gramps/gui/merge/mergeevent.py b/gramps/gui/merge/mergeevent.py index 82429e611..3c0b72670 100644 --- a/gramps/gui/merge/mergeevent.py +++ b/gramps/gui/merge/mergeevent.py @@ -165,7 +165,7 @@ class MergeEvent(ManagedWindow): else: phoenix = self.ev2 titanic = self.ev1 - # Add second handle to history so that when merge is complete, + # Add second handle to history so that when merge is complete, # phoenix is the selected row. self.uistate.set_active(phoenix.get_handle(), 'Event') @@ -180,7 +180,7 @@ class MergeEvent(ManagedWindow): if self.get_widget("gramps_btn1").get_active() ^ use_handle1: phoenix.set_gramps_id(titanic.get_gramps_id()) # cause is deprecated. - + query = MergeEventQuery(self.dbstate, phoenix, titanic) query.execute() self.uistate.set_busy_cursor(False) diff --git a/gramps/gui/merge/mergefamily.py b/gramps/gui/merge/mergefamily.py index e466d6d3e..685fa144c 100644 --- a/gramps/gui/merge/mergefamily.py +++ b/gramps/gui/merge/mergefamily.py @@ -161,7 +161,7 @@ class MergeFamily(ManagedWindow): """Preferred family changes""" if obj.get_active(): father1_text = self.get_widget("father1").get_text() - if (father1_text != " []" or + if (father1_text != " []" or self.get_widget("father2").get_text() == " []"): self.get_widget("father_btn1").set_active(True) mother1_text = self.get_widget("mother1").get_text() @@ -198,7 +198,7 @@ class MergeFamily(ManagedWindow): else: phoenix = self.fy2 titanic = self.fy1 - # Add second handle to history so that when merge is complete, + # Add second handle to history so that when merge is complete, # phoenix is the selected row. self.uistate.set_active(phoenix.get_handle(), 'Family') diff --git a/gramps/gui/merge/mergemedia.py b/gramps/gui/merge/mergemedia.py index 7071aa34b..601cb3146 100644 --- a/gramps/gui/merge/mergemedia.py +++ b/gramps/gui/merge/mergemedia.py @@ -147,7 +147,7 @@ class MergeMedia(ManagedWindow): else: phoenix = self.mo2 titanic = self.mo1 - # Add second handle to history so that when merge is complete, + # Add second handle to history so that when merge is complete, # phoenix is the selected row. self.uistate.set_active(phoenix.get_handle(), 'Media') diff --git a/gramps/gui/merge/mergenote.py b/gramps/gui/merge/mergenote.py index 417381420..6d9f9fd40 100644 --- a/gramps/gui/merge/mergenote.py +++ b/gramps/gui/merge/mergenote.py @@ -159,7 +159,7 @@ class MergeNote(ManagedWindow): else: phoenix = self.no2 titanic = self.no1 - # Add second handle to history so that when merge is complete, + # Add second handle to history so that when merge is complete, # phoenix is the selected row. self.uistate.set_active(phoenix.get_handle(), 'Note') diff --git a/gramps/gui/merge/mergeperson.py b/gramps/gui/merge/mergeperson.py index 3e0e351d1..72fa30bf2 100644 --- a/gramps/gui/merge/mergeperson.py +++ b/gramps/gui/merge/mergeperson.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -176,24 +176,24 @@ class MergePerson(ManagedWindow): title.set_property('weight', Pango.Weight.BOLD) title.set_property('scale', 1.2) self.add(tobj, title, name_displayer.display(person)) - self.add(tobj, normal, "%s:\t%s" % (_('ID'), + self.add(tobj, normal, "%s:\t%s" % (_('ID'), person.get_gramps_id())) - self.add(tobj, normal, "%s:\t%s" % (_('Gender'), + self.add(tobj, normal, "%s:\t%s" % (_('Gender'), sex[person.get_gender()])) bref = person.get_birth_ref() if bref: - self.add(tobj, normal, "%s:\t%s" % (_('Birth'), + self.add(tobj, normal, "%s:\t%s" % (_('Birth'), self.get_event_info(bref.ref))) dref = person.get_death_ref() if dref: - self.add(tobj, normal, "%s:\t%s" % (_('Death'), + self.add(tobj, normal, "%s:\t%s" % (_('Death'), self.get_event_info(dref.ref))) nlist = person.get_alternate_names() if len(nlist) > 0: self.add(tobj, title, _("Alternate Names")) for name in nlist: - self.add(tobj, normal, + self.add(tobj, normal, name_displayer.display_name(name)) elist = person.get_event_ref_list() @@ -205,10 +205,10 @@ class MergePerson(ManagedWindow): name = str( self.database.get_event_from_handle(event_handle).get_type()) if role.is_primary(): - self.add(tobj, normal, "%s:\t%s" % + self.add(tobj, normal, "%s:\t%s" % (name, self.get_event_info(event_handle))) else: - self.add(tobj, normal, "%s (%s):\t%s" % + self.add(tobj, normal, "%s (%s):\t%s" % (name, role, self.get_event_info(event_handle))) plist = person.get_parent_family_handle_list() @@ -223,7 +223,7 @@ class MergePerson(ManagedWindow): self.add(tobj, indent, "%s:\t%s" % (_('Mother'), mname)) else: self.add(tobj, normal, _("No parents found")) - + self.add(tobj, title, _("Spouses")) slist = person.get_family_handle_list() if len(slist) > 0: @@ -234,18 +234,18 @@ class MergePerson(ManagedWindow): spouse_id = ReportUtils.find_spouse(person, family) if spouse_id: spouse = self.database.get_person_from_handle(spouse_id) - self.add(tobj, indent, "%s:\t%s" % (_('Spouse'), + self.add(tobj, indent, "%s:\t%s" % (_('Spouse'), name_of(spouse))) relstr = str(family.get_relationship()) self.add(tobj, indent, "%s:\t%s" % (_('Type'), relstr)) event = ReportUtils.find_marriage(self.database, family) if event: self.add(tobj, indent, "%s:\t%s" % ( - _('Marriage'), + _('Marriage'), self.get_event_info(event.get_handle()))) for child_ref in family.get_child_ref_list(): child = self.database.get_person_from_handle(child_ref.ref) - self.add(tobj, indent, "%s:\t%s" % (_('Child'), + self.add(tobj, indent, "%s:\t%s" % (_('Child'), name_of(child))) else: self.add(tobj, normal, _("No spouses or children found")) @@ -254,7 +254,7 @@ class MergePerson(ManagedWindow): if len(alist) > 0: self.add(tobj, title, _("Addresses")) for addr in alist: - location = ", ".join([addr.get_street(), addr.get_city(), + location = ", ".join([addr.get_street(), addr.get_city(), addr.get_state(), addr.get_country(), addr.get_postal_code(), addr.get_phone()]) self.add(tobj, normal, location.strip()) @@ -307,7 +307,7 @@ class MergePerson(ManagedWindow): else: phoenix = self.pr2 titanic = self.pr1 - # Add second handle to history so that when merge is complete, + # Add second handle to history so that when merge is complete, # phoenix is the selected row. self.uistate.set_active(phoenix.get_handle(), 'Person') diff --git a/gramps/gui/merge/mergeplace.py b/gramps/gui/merge/mergeplace.py index bf8bf5810..645184c1b 100644 --- a/gramps/gui/merge/mergeplace.py +++ b/gramps/gui/merge/mergeplace.py @@ -76,7 +76,7 @@ class MergePlace(ManagedWindow): self.set_window(self._gladeobj.toplevel, self.get_widget('place_title'), _("Merge Places")) - + # Detailed selection widgets if not config.get('preferences.place-auto'): title1 = self.pl1.get_title() @@ -196,7 +196,7 @@ class MergePlace(ManagedWindow): else: phoenix = self.pl2 titanic = self.pl1 - # Add second handle to history so that when merge is complete, + # Add second handle to history so that when merge is complete, # phoenix is the selected row. self.uistate.set_active(phoenix.get_handle(), 'Place') @@ -217,7 +217,7 @@ class MergePlace(ManagedWindow): query = MergePlaceQuery(self.dbstate, phoenix, titanic) query.execute() - + if self.callback: self.callback() self.uistate.set_busy_cursor(False) diff --git a/gramps/gui/merge/mergerepository.py b/gramps/gui/merge/mergerepository.py index 3e2fbe185..2dc2b74af 100644 --- a/gramps/gui/merge/mergerepository.py +++ b/gramps/gui/merge/mergerepository.py @@ -140,7 +140,7 @@ class MergeRepository(ManagedWindow): else: phoenix = self.rp2 titanic = self.rp1 - # Add second handle to history so that when merge is complete, + # Add second handle to history so that when merge is complete, # phoenix is the selected row. self.uistate.set_active(phoenix.get_handle(), 'Repository') diff --git a/gramps/gui/merge/mergesource.py b/gramps/gui/merge/mergesource.py index 94b1ca871..3c80e1b45 100644 --- a/gramps/gui/merge/mergesource.py +++ b/gramps/gui/merge/mergesource.py @@ -114,7 +114,7 @@ class MergeSource(ManagedWindow): for widget_name in ('gramps1', 'gramps2', 'gramps_btn1', 'gramps_btn2'): self.get_widget(widget_name).set_sensitive(False) - + # Main window widgets that determine which handle survives rbutton1 = self.get_widget("handle_btn1") rbutton_label1 = self.get_widget("label_handle_btn1") @@ -159,7 +159,7 @@ class MergeSource(ManagedWindow): else: phoenix = self.src2 titanic = self.src1 - # Add second handle to history so that when merge is complete, + # Add second handle to history so that when merge is complete, # phoenix is the selected row. self.uistate.set_active(phoenix.get_handle(), 'Source') diff --git a/gramps/gui/navigator.py b/gramps/gui/navigator.py index e6eeb6146..38bb63745 100644 --- a/gramps/gui/navigator.py +++ b/gramps/gui/navigator.py @@ -93,18 +93,18 @@ class Navigator(object): self.merge_ids = [] self.top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) - + frame = Gtk.Frame() hbox = Gtk.Box() hbox.show() frame.add(hbox) frame.show() - + self.select_button = Gtk.ToggleButton() self.select_button.set_relief(Gtk.ReliefStyle.NONE) select_hbox = Gtk.Box() self.title_label = Gtk.Label(label='') - arrow = Gtk.Arrow(arrow_type=Gtk.ArrowType.DOWN, + arrow = Gtk.Arrow(arrow_type=Gtk.ArrowType.DOWN, shadow_type=Gtk.ShadowType.NONE) select_hbox.pack_start(self.title_label, False, True, 0) select_hbox.pack_end(arrow, False, True, 0) @@ -121,7 +121,7 @@ class Navigator(object): hbox.pack_start(self.select_button, False, True, 0) #hbox.pack_end(close_button, False, True, 0) - self.top.pack_end(frame, False, True, 0) + self.top.pack_end(frame, False, True, 0) self.menu = Gtk.Menu() self.menu.show() @@ -134,7 +134,7 @@ class Navigator(object): self.notebook.connect('switch_page', self.cb_switch_page) self.top.show() self.top.pack_start(self.notebook, True, True, 0) - + def load_plugins(self, dbstate, uistate): """ Load the sidebar plugins. @@ -167,7 +167,7 @@ class Navigator(object): stock_icon = page[0].stock_icon if stock_icon is None: stock_icon = cat_icon - self.view_toggle_actions[cat_num].append((pageid, + self.view_toggle_actions[cat_num].append((pageid, stock_icon, page[0].name, modifier, page[0].name, view_num)) @@ -193,7 +193,7 @@ class Navigator(object): Return the top container widget for the GUI. """ return self.top - + def add(self, title, sidebar, order): """ Add a page to the sidebar for a plugin. @@ -223,9 +223,9 @@ class Navigator(object): # Add buttons to the menu for the different view in the category uimanager = self.viewmanager.uimanager if self.cat_view_group: - if self.cat_view_group in uimanager.get_action_groups(): + if self.cat_view_group in uimanager.get_action_groups(): uimanager.remove_action_group(self.cat_view_group) - + list(map(uimanager.remove_ui, self.merge_ids)) if cat_num in self.ui_category: @@ -266,7 +266,7 @@ class Navigator(object): def cb_menu_activate(self, menu, index): """ Called when an item in the popup menu is selected. - """ + """ self.notebook.set_current_page(index) def cb_switch_page(self, notebook, unused, index): @@ -308,7 +308,7 @@ def cb_menu_position(*args): ret_val, x_pos, y_pos = button.get_window().get_origin() x_pos += button.get_allocation().x y_pos += button.get_allocation().y + button.get_allocation().height - + return (x_pos, y_pos, False) def cb_menu_deactivate(menu, button): diff --git a/gramps/gui/plug/_dialogs.py b/gramps/gui/plug/_dialogs.py index 7d5c443b1..b26a47480 100644 --- a/gramps/gui/plug/_dialogs.py +++ b/gramps/gui/plug/_dialogs.py @@ -69,7 +69,7 @@ class PluginDialog(ManagedWindow): plugin that is desired. """ def __init__(self, state, uistate, track, categories, msg, - label=None, button_label=None, tool_tip=None, + label=None, button_label=None, tool_tip=None, content=_REPORTS): """ Display the dialog box, and build up the list of available @@ -86,7 +86,7 @@ class PluginDialog(ManagedWindow): self.state = state self.uistate = uistate - + self.dialog = Gtk.Builder() self.dialog.add_from_file(PLUGINS_GLADE) self.dialog.connect_signals({ @@ -107,15 +107,15 @@ class PluginDialog(ManagedWindow): col = Gtk.TreeViewColumn('', Gtk.CellRendererText(), text=0) self.tree.append_column(col) self.tree.set_model(self.store) - + self.description = self.dialog.get_object("description") if label: self.description.set_text(label) self.status = self.dialog.get_object("report_status") - + self.author_name = self.dialog.get_object("author_name") self.author_email = self.dialog.get_object("author_email") - + self.apply_button = self.dialog.get_object("apply") if button_label: self.apply_button.set_label(button_label) @@ -126,7 +126,7 @@ class PluginDialog(ManagedWindow): self.apply_button.set_tooltip_text(tool_tip) self.item = None - + if content == _REPORTS: reg_list = self._pmgr.get_reg_reports() elif content == _TOOLS: @@ -148,7 +148,7 @@ class PluginDialog(ManagedWindow): if not self.item: return self.run_plugin(self.item) - + def on_node_selected(self, obj): """Updates the informational display on the right hand side of the dialog box with the description of the selected report""" @@ -157,7 +157,7 @@ class PluginDialog(ManagedWindow): if node: path = store.get_path(node).to_string() if not node or path not in self.imap: - return + return pdata = self.imap[path] #(report_class, options_class, title, category, name, @@ -177,7 +177,7 @@ class PluginDialog(ManagedWindow): """Populates a GtkTree with each menu item associated with a entry in the lists. The list consists of PluginData objects for reports or tools. - + old data was (item_class, options_class,title,category, name, doc,status,author,email) @@ -200,7 +200,7 @@ class PluginDialog(ManagedWindow): # GtkTreeItems that are associated with it. key_list = [item for item in item_hash if item != _UNSUPPORTED] key_list.sort(reverse=True) - + prev = None if _UNSUPPORTED in item_hash: key = _UNSUPPORTED @@ -236,25 +236,25 @@ class PluginDialog(ManagedWindow): mod = self._pmgr.load_plugin(pdata) if not mod: #import of plugin failed - return + return if pdata.ptype == REPORT: active_handle = self.uistate.get_active('Person') report(self.state, self.uistate, self.state.db.get_person_from_handle(active_handle), - eval('mod.' + pdata.reportclass), - eval('mod.' + pdata.optionclass), - pdata.name, pdata.id, + eval('mod.' + pdata.reportclass), + eval('mod.' + pdata.optionclass), + pdata.name, pdata.id, pdata.category, pdata.require_active) else: from ..user import User tool.gui_tool( - dbstate = self.state, + dbstate = self.state, user = User(uistate=self.uistate), - tool_class = eval('mod.' + pdata.toolclass), + tool_class = eval('mod.' + pdata.toolclass), options_class = eval('mod.' + pdata.optionclass), - translated_name = pdata.name, - name = pdata.id, + translated_name = pdata.name, + name = pdata.id, category = pdata.category, callback = self.state.db.request_rebuild) @@ -284,7 +284,7 @@ class ReportPluginDialog(PluginDialog): _("Select a report from those available on the left."), _("_Generate"), _("Generate selected report"), _REPORTS) - + self._pmgr.connect('plugins-reloaded', self.rebuild) def rebuild(self): diff --git a/gramps/gui/plug/_guioptions.py b/gramps/gui/plug/_guioptions.py index 82f5d9fad..90ac7cad8 100644 --- a/gramps/gui/plug/_guioptions.py +++ b/gramps/gui/plug/_guioptions.py @@ -112,10 +112,10 @@ class LastNameDialog(ManagedWindow): # self.__model.append([name, 0]) # build up the list of surnames, keeping track of the count for each - # name (this can be a lengthy process, so by passing in the + # name (this can be a lengthy process, so by passing in the # dictionary we can be certain we only do this once) progress = ProgressMeter(_('Finding Surnames')) - progress.set_pass(_('Finding surnames'), + progress.set_pass(_('Finding surnames'), database.get_number_of_people()) for person in database.iter_people(): progress.step() @@ -134,7 +134,7 @@ class LastNameDialog(ManagedWindow): # keep the list sorted starting with the most popular last name self.__model.set_sort_column_id(1, Gtk.SortType.DESCENDING) - # the "OK" button should be enabled/disabled based on the selection of + # the "OK" button should be enabled/disabled based on the selection of # a row self.__tree_selection = self.__tree_view.get_selection() self.__tree_selection.set_mode(Gtk.SelectionMode.MULTIPLE) @@ -180,7 +180,7 @@ class GuiStringOption(Gtk.Entry): # that would call the other signal handler. self.changekey = self.connect('changed', self.__text_changed) self.valuekey = self.__option.connect('value-changed', self.__value_changed) - + self.conkey = self.__option.connect('avail-changed', self.__update_avail) self.__update_avail() @@ -245,7 +245,7 @@ class GuiColorOption(Gtk.ColorButton): self.__update_avail() self.set_tooltip_text(self.__option.get_help()) - + def __color_changed(self, obj): # IGNORE:W0613 - obj is unused """ Handle the change of color made by the user. @@ -291,7 +291,7 @@ class GuiColorOption(Gtk.ColorButton): #------------------------------------------------------------------------- class GuiNumberOption(Gtk.SpinButton): """ - This class displays an option that is a simple number with defined maximum + This class displays an option that is a simple number with defined maximum and minimum values. """ def __init__(self, option, dbstate, uistate, track, override): @@ -303,12 +303,12 @@ class GuiNumberOption(Gtk.SpinButton): lower=self.__option.get_min(), upper=self.__option.get_max(), step_increment=step) - + # Calculate the number of decimal places if necessary if step < 1: import math decimals = int(math.log10(step) * -1) - + GObject.GObject.__init__(self, adjustment=adj, climb_rate=1, digits=decimals) Gtk.SpinButton.set_numeric(self, True) @@ -320,12 +320,12 @@ class GuiNumberOption(Gtk.SpinButton): # that would call the other signal handler. self.changekey = self.connect('value_changed', self.__number_changed) self.valuekey = self.__option.connect('value-changed', self.__value_changed) - + self.conkey = self.__option.connect('avail-changed', self.__update_avail) self.__update_avail() self.set_tooltip_text(self.__option.get_help()) - + def __number_changed(self, obj): # IGNORE:W0613 - obj is unused """ Handle the change of the value made by the user. @@ -333,7 +333,7 @@ class GuiNumberOption(Gtk.SpinButton): vtype = type(self.__option.get_value()) self.__option.set_value( vtype(self.get_value()) ) - + def __update_avail(self): """ Update the availability (sensitivity) of this widget. @@ -381,7 +381,7 @@ class GuiTextOption(Gtk.ScrolledWindow): gtext.set_wrap_mode(Gtk.WrapMode.WORD_CHAR) self.add(gtext) self.__buff = gtext.get_buffer() - + # Set up signal handlers when the widget value is changed # from user interaction or programmatically. When handling # a specific signal, we need to temporarily block the signal @@ -440,7 +440,7 @@ class GuiTextOption(Gtk.ScrolledWindow): self.__buff.disconnect(self.bufcon) self.__buff = None - + #------------------------------------------------------------------------- # # GuiBooleanOption class @@ -473,7 +473,7 @@ class GuiBooleanOption(Gtk.CheckButton): Handle the change of the value made by the user. """ self.__option.set_value( self.get_active() ) - + def __update_avail(self): """ Update the availability (sensitivity) of this widget. @@ -517,9 +517,9 @@ class GuiEnumeratedListOption(Gtk.Box): self.__combo.set_wrap_width(3) evtBox.add(self.__combo) self.pack_start(evtBox, True, True, 0) - + self.__update_options() - + # Set up signal handlers when the widget value is changed # from user interaction or programmatically. When handling # a specific signal, we need to temporarily block the signal @@ -532,7 +532,7 @@ class GuiEnumeratedListOption(Gtk.Box): self.__update_avail() self.set_tooltip_text(self.__option.get_help()) - + def __selection_changed(self, obj): # IGNORE:W0613 - obj is unused """ Handle the change of the value made by the user. @@ -550,7 +550,7 @@ class GuiEnumeratedListOption(Gtk.Box): self.__option.set_value( value ) self.value_changed() # Allow overriding so that another class # can add functionality - + def value_changed(self): pass @@ -569,7 +569,7 @@ class GuiEnumeratedListOption(Gtk.Box): active_index = current_index current_index += 1 self.__combo.set_active( active_index ) - + def __update_avail(self): """ Update the availability (sensitivity) of this widget. @@ -601,7 +601,7 @@ class GuiEnumeratedListOption(Gtk.Box): #------------------------------------------------------------------------- class GuiPersonOption(Gtk.Box): """ - This class displays an option that allows a person from the + This class displays an option that allows a person from the database to be selected. """ def __init__(self, option, dbstate, uistate, track, override): @@ -618,7 +618,7 @@ class GuiPersonOption(Gtk.Box): self.__track = track self.__person_label = Gtk.Label() self.__person_label.set_halign(Gtk.Align.START) - + pevt = Gtk.EventBox() pevt.add(self.__person_label) person_button = widgets.SimpleButton('gtk-index', @@ -633,7 +633,7 @@ class GuiPersonOption(Gtk.Box): # Pick up the active person person_handle = self.__uistate.get_active('Person') person = self.__dbstate.db.get_person_from_handle(person_handle) - + if override or not person: # Pick up the stored option value if there is one person = self.__db.get_person_from_gramps_id(gid) @@ -646,12 +646,12 @@ class GuiPersonOption(Gtk.Box): person = self.__db.find_initial_person() self.__update_person(person) - + self.valuekey = self.__option.connect('value-changed', self.__value_changed) self.conkey = self.__option.connect('avail-changed', self.__update_avail) self.__update_avail() - + pevt.set_tooltip_text(self.__option.get_help()) person_button.set_tooltip_text(_('Select a different person')) @@ -664,13 +664,13 @@ class GuiPersonOption(Gtk.Box): rfilter.set_logical_op('or') rfilter.add_rule(rules.person.IsBookmarked([])) rfilter.add_rule(rules.person.HasIdOf([self.__option.get_value()])) - + # Add the database home person if one exists. default_person = self.__db.get_default_person() if default_person: gid = default_person.get_gramps_id() rfilter.add_rule(rules.person.HasIdOf([gid])) - + # Add the selected person if one exists. person_handle = self.__uistate.get_active('Person') active_person = self.__dbstate.db.get_person_from_handle(person_handle) @@ -679,12 +679,12 @@ class GuiPersonOption(Gtk.Box): rfilter.add_rule(rules.person.HasIdOf([gid])) select_class = SelectorFactory('Person') - sel = select_class(self.__dbstate, self.__uistate, self.__track, - title=_('Select a person for the report'), + sel = select_class(self.__dbstate, self.__uistate, self.__track, + title=_('Select a person for the report'), filter=rfilter ) person = sel.run() self.__update_person(person) - + def __update_person(self, person): """ Update the currently selected person. @@ -694,7 +694,7 @@ class GuiPersonOption(Gtk.Box): gid = person.get_gramps_id() self.__person_label.set_text( "%s (%s)" % (name, gid) ) self.__option.set_value(gid) - + def __update_avail(self): """ Update the availability (sensitivity) of this widget. @@ -718,7 +718,7 @@ class GuiPersonOption(Gtk.Box): self.__option.disconnect(self.valuekey) self.__option.disconnect(self.conkey) self.__option = None - + #------------------------------------------------------------------------- # # GuiFamilyOption class @@ -726,7 +726,7 @@ class GuiPersonOption(Gtk.Box): #------------------------------------------------------------------------- class GuiFamilyOption(Gtk.Box): """ - This class displays an option that allows a family from the + This class displays an option that allows a family from the database to be selected. """ def __init__(self, option, dbstate, uistate, track, override): @@ -743,7 +743,7 @@ class GuiFamilyOption(Gtk.Box): self.__track = track self.__family_label = Gtk.Label() self.__family_label.set_halign(Gtk.Align.START) - + pevt = Gtk.EventBox() pevt.add(self.__family_label) family_button = widgets.SimpleButton('gtk-index', @@ -752,24 +752,24 @@ class GuiFamilyOption(Gtk.Box): self.pack_start(pevt, False, True, 0) self.pack_end(family_button, False, True, 0) - + self.__initialize_family(override) self.valuekey = self.__option.connect('value-changed', self.__value_changed) - + self.conkey = self.__option.connect('avail-changed', self.__update_avail) self.__update_avail() - + pevt.set_tooltip_text(self.__option.get_help()) family_button.set_tooltip_text(_('Select a different family')) - + def __initialize_family(self, override): """ Find a family to initialize the option with. If there is no specified family, try to find a family that the user is likely interested in. """ family_list = [] - + fid = self.__option.get_value() fid_family = self.__db.get_family_from_gramps_id(fid) active_family = self.__uistate.get_active('Family') @@ -781,14 +781,14 @@ class GuiFamilyOption(Gtk.Box): if active_family and not family_list: # Use the active family if one is selected family_list = [active_family] - + if not family_list: # Next try the family of the active person person_handle = self.__uistate.get_active('Person') person = self.__dbstate.db.get_person_from_handle(person_handle) if person: family_list = person.get_family_handle_list() - + if fid_family and not family_list: # Next try the stored option value if there is one family_list = [fid_family.get_handle()] @@ -814,10 +814,10 @@ class GuiFamilyOption(Gtk.Box): # Create a filter for the person selector. rfilter = GenericFilterFactory('Family')() rfilter.set_logical_op('or') - + # Add the current family rfilter.add_rule(rules.family.HasIdOf([self.__option.get_value()])) - + # Add all bookmarked families rfilter.add_rule(rules.family.IsBookmarked([])) @@ -829,7 +829,7 @@ class GuiFamilyOption(Gtk.Box): family = self.__db.get_family_from_handle(family_handle) gid = family.get_gramps_id() rfilter.add_rule(rules.family.HasIdOf([gid])) - + # Add the families of the selected person if one exists. # Same code as above one ! See bug #5032 feature request #5038 ### active_person = self.__uistate.get_active('Person') ### @@ -842,12 +842,12 @@ class GuiFamilyOption(Gtk.Box): #rfilter.add_rule(rules.family.HasIdOf([gid])) select_class = SelectorFactory('Family') - sel = select_class(self.__dbstate, self.__uistate, self.__track, + sel = select_class(self.__dbstate, self.__uistate, self.__track, filter=rfilter ) family = sel.run() if family: self.__update_family(family.get_handle()) - + def __update_family(self, handle): """ Update the currently selected family. @@ -857,19 +857,19 @@ class GuiFamilyOption(Gtk.Box): family_id = family.get_gramps_id() fhandle = family.get_father_handle() mhandle = family.get_mother_handle() - + if fhandle: father = self.__db.get_person_from_handle(fhandle) father_name = _nd.display(father) else: father_name = _("unknown father") - + if mhandle: mother = self.__db.get_person_from_handle(mhandle) mother_name = _nd.display(mother) else: mother_name = _("unknown mother") - + name = _("%(father_name)s and %(mother_name)s (%(family_id)s)") % { 'father_name': father_name, 'mother_name': mother_name, @@ -877,7 +877,7 @@ class GuiFamilyOption(Gtk.Box): self.__family_label.set_text( name ) self.__option.set_value(family_id) - + def __update_avail(self): """ Update the availability (sensitivity) of this widget. @@ -915,7 +915,7 @@ class GuiFamilyOption(Gtk.Box): #------------------------------------------------------------------------- class GuiNoteOption(Gtk.Box): """ - This class displays an option that allows a note from the + This class displays an option that allows a note from the database to be selected. """ def __init__(self, option, dbstate, uistate, track, override): @@ -932,7 +932,7 @@ class GuiNoteOption(Gtk.Box): self.__track = track self.__note_label = Gtk.Label() self.__note_label.set_halign(Gtk.Align.START) - + pevt = Gtk.EventBox() pevt.add(self.__note_label) note_button = widgets.SimpleButton('gtk-index', @@ -941,17 +941,17 @@ class GuiNoteOption(Gtk.Box): self.pack_start(pevt, False, True, 0) self.pack_end(note_button, False, True, 0) - + # Initialize to the current value nid = self.__option.get_value() note = self.__db.get_note_from_gramps_id(nid) self.__update_note(note) - + self.valuekey = self.__option.connect('value-changed', self.__value_changed) self.__option.connect('avail-changed', self.__update_avail) self.__update_avail() - + pevt.set_tooltip_text(self.__option.get_help()) note_button.set_tooltip_text(_('Select an existing note')) @@ -963,7 +963,7 @@ class GuiNoteOption(Gtk.Box): sel = select_class(self.__dbstate, self.__uistate, self.__track) note = sel.run() self.__update_note(note) - + def __update_note(self, note): """ Update the currently selected note. @@ -982,7 +982,7 @@ class GuiNoteOption(Gtk.Box): self.__note_label.set_text( txt ) self.__note_label.set_use_markup(True) self.__option.set_value("") - + def __update_avail(self): """ Update the availability (sensitivity) of this widget. @@ -1011,7 +1011,7 @@ class GuiNoteOption(Gtk.Box): """ self.__option.disconnect(self.valuekey) self.__option = None - + #------------------------------------------------------------------------- # # GuiMediaOption class @@ -1019,7 +1019,7 @@ class GuiNoteOption(Gtk.Box): #------------------------------------------------------------------------- class GuiMediaOption(Gtk.Box): """ - This class displays an option that allows a media object from the + This class displays an option that allows a media object from the database to be selected. """ def __init__(self, option, dbstate, uistate, track, override): @@ -1036,7 +1036,7 @@ class GuiMediaOption(Gtk.Box): self.__track = track self.__media_label = Gtk.Label() self.__media_label.set_halign(Gtk.Align.START) - + pevt = Gtk.EventBox() pevt.add(self.__media_label) media_button = widgets.SimpleButton('gtk-index', @@ -1045,17 +1045,17 @@ class GuiMediaOption(Gtk.Box): self.pack_start(pevt, False, True, 0) self.pack_end(media_button, False, True, 0) - + # Initialize to the current value mid = self.__option.get_value() media = self.__db.get_object_from_gramps_id(mid) self.__update_media(media) self.valuekey = self.__option.connect('value-changed', self.__value_changed) - + self.__option.connect('avail-changed', self.__update_avail) self.__update_avail() - + pevt.set_tooltip_text(self.__option.get_help()) media_button.set_tooltip_text(_('Select an existing media object')) @@ -1067,7 +1067,7 @@ class GuiMediaOption(Gtk.Box): sel = select_class(self.__dbstate, self.__uistate, self.__track) media = sel.run() self.__update_media(media) - + def __update_media(self, media): """ Update the currently selected media. @@ -1083,7 +1083,7 @@ class GuiMediaOption(Gtk.Box): self.__media_label.set_text( txt ) self.__media_label.set_use_markup(True) self.__option.set_value("") - + def __update_avail(self): """ Update the availability (sensitivity) of this widget. @@ -1112,7 +1112,7 @@ class GuiMediaOption(Gtk.Box): """ self.__option.disconnect(self.valuekey) self.__option = None - + #------------------------------------------------------------------------- # # GuiPersonListOption class @@ -1120,7 +1120,7 @@ class GuiMediaOption(Gtk.Box): #------------------------------------------------------------------------- class GuiPersonListOption(Gtk.Box): """ - This class displays a widget that allows multiple people from the + This class displays a widget that allows multiple people from the database to be selected. """ def __init__(self, option, dbstate, uistate, track, override): @@ -1151,7 +1151,7 @@ class GuiPersonListOption(Gtk.Box): self.__tree_view.append_column(col2) self.__scrolled_window = Gtk.ScrolledWindow() self.__scrolled_window.add(self.__tree_view) - self.__scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, + self.__scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.__scrolled_window.set_shadow_type(Gtk.ShadowType.OUT) @@ -1159,7 +1159,7 @@ class GuiPersonListOption(Gtk.Box): self.__value_changed() - # now setup the '+' and '-' pushbutton for adding/removing people from + # now setup the '+' and '-' pushbutton for adding/removing people from # the container self.__add_person = widgets.SimpleButton('list-add', self.__add_person_clicked) @@ -1172,7 +1172,7 @@ class GuiPersonListOption(Gtk.Box): self.pack_end(self.__vbbox, False, False, 0) self.valuekey = self.__option.connect('value-changed', self.__value_changed) - + self.__tree_view.set_tooltip_text(self.__option.get_help()) def __add_person_clicked(self, obj): # IGNORE:W0613 - obj is unused @@ -1190,7 +1190,7 @@ class GuiPersonListOption(Gtk.Box): i = self.__model.iter_next(i) select_class = SelectorFactory('Person') - sel = select_class(self.__dbstate, self.__uistate, + sel = select_class(self.__dbstate, self.__uistate, self.__track, skip=skip_list) person = sel.run() if person: @@ -1206,7 +1206,7 @@ class GuiPersonListOption(Gtk.Box): family_list = person.get_family_handle_list() for family_handle in family_list: family = self.__db.get_family_from_handle(family_handle) - + if person.get_handle() == family.get_father_handle(): spouse_handle = family.get_mother_handle() else: @@ -1225,9 +1225,9 @@ class GuiPersonListOption(Gtk.Box): if prompt.get_response() == Gtk.ResponseType.YES: gid = spouse.get_gramps_id() self.__model.append([spouse_name, gid]) - + self.__update_value() - + def __del_person_clicked(self, obj): # IGNORE:W0613 - obj is unused """ Handle the delete person button. @@ -1297,7 +1297,7 @@ class GuiPersonListOption(Gtk.Box): #------------------------------------------------------------------------- class GuiPlaceListOption(Gtk.Box): """ - This class displays a widget that allows multiple places from the + This class displays a widget that allows multiple places from the database to be selected. """ def __init__(self, option, dbstate, uistate, track, override): @@ -1328,7 +1328,7 @@ class GuiPlaceListOption(Gtk.Box): self.__tree_view.append_column(col2) self.__scrolled_window = Gtk.ScrolledWindow() self.__scrolled_window.add(self.__tree_view) - self.__scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, + self.__scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.__scrolled_window.set_shadow_type(Gtk.ShadowType.OUT) @@ -1336,7 +1336,7 @@ class GuiPlaceListOption(Gtk.Box): self.__value_changed() - # now setup the '+' and '-' pushbutton for adding/removing places from + # now setup the '+' and '-' pushbutton for adding/removing places from # the container self.__add_place = widgets.SimpleButton('list-add', self.__add_place_clicked) @@ -1349,7 +1349,7 @@ class GuiPlaceListOption(Gtk.Box): self.pack_end(self.__vbbox, False, False, 0) self.valuekey = self.__option.connect('value-changed', self.__value_changed) - + self.__tree_view.set_tooltip_text(self.__option.get_help()) def __add_place_clicked(self, obj): # IGNORE:W0613 - obj is unused @@ -1367,7 +1367,7 @@ class GuiPlaceListOption(Gtk.Box): i = self.__model.iter_next(i) select_class = SelectorFactory('Place') - sel = select_class(self.__dbstate, self.__uistate, + sel = select_class(self.__dbstate, self.__uistate, self.__track, skip=skip_list) place = sel.run() if place: @@ -1375,7 +1375,7 @@ class GuiPlaceListOption(Gtk.Box): gid = place.get_gramps_id() self.__model.append([place_name, gid]) self.__update_value() - + def __del_place_clicked(self, obj): # IGNORE:W0613 - obj is unused """ Handle the delete place button. @@ -1461,7 +1461,7 @@ class GuiSurnameColorOption(Gtk.Box): # This will get populated the first time the dialog is run, # and used each time after. self.__surnames = {} # list of surnames and count - + self.__model = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING) self.__tree_view = Gtk.TreeView(self.__model) self.__tree_view.connect('row-activated', self.__row_clicked) @@ -1476,7 +1476,7 @@ class GuiSurnameColorOption(Gtk.Box): self.__tree_view.append_column(col2) self.scrolled_window = Gtk.ScrolledWindow() self.scrolled_window.add(self.__tree_view) - self.scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, + self.scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.scrolled_window.set_shadow_type(Gtk.ShadowType.OUT) self.pack_start(self.scrolled_window, True, True, 0) @@ -1508,7 +1508,7 @@ class GuiSurnameColorOption(Gtk.Box): skip_list.add(surname.encode('iso-8859-1','xmlcharrefreplace')) i = self.__model.iter_next(i) - ln_dialog = LastNameDialog(self.__db, self.__uistate, + ln_dialog = LastNameDialog(self.__db, self.__uistate, self.__track, self.__surnames, skip_list) surname_set = ln_dialog.run() for surname in surname_set: @@ -1557,7 +1557,7 @@ class GuiSurnameColorOption(Gtk.Box): surname_colours = '' i = self.__model.get_iter_first() while (i): - surname = self.__model.get_value(i, 0) + surname = self.__model.get_value(i, 0) #surname = surname.encode('iso-8859-1','xmlcharrefreplace') colour = self.__model.get_value(i, 1) # Tried to use a dictionary, and tried to save it as a tuple, @@ -1623,7 +1623,7 @@ class GuiSurnameColorOption(Gtk.Box): """ self.__option.disconnect(self.valuekey) self.__option = None - + #------------------------------------------------------------------------- # # GuiDestinationOption class @@ -1631,7 +1631,7 @@ class GuiSurnameColorOption(Gtk.Box): #------------------------------------------------------------------------- class GuiDestinationOption(Gtk.Box): """ - This class displays an option that allows the user to select a + This class displays an option that allows the user to select a DestinationOption. """ def __init__(self, option, dbstate, uistate, track, override): @@ -1644,13 +1644,13 @@ class GuiDestinationOption(Gtk.Box): self.__option = option self.__entry = Gtk.Entry() self.__entry.set_text( self.__option.get_value() ) - + self.__button = Gtk.Button() img = Gtk.Image() img.set_from_icon_name('document-open', Gtk.IconSize.BUTTON) self.__button.add(img) self.__button.connect('clicked', self.__select_file) - + self.pack_start(self.__entry, True, True, 0) self.pack_end(self.__button, False, False, 0) @@ -1660,13 +1660,13 @@ class GuiDestinationOption(Gtk.Box): # that would call the other signal handler. self.changekey = self.__entry.connect('changed', self.__text_changed) self.valuekey = self.__option.connect('value-changed', self.__value_changed) - + self.conkey1 = self.__option.connect('options-changed', self.__option_changed) self.conkey2 = self.__option.connect('avail-changed', self.__update_avail) self.__update_avail() - + self.set_tooltip_text(self.__option.get_help()) - + def __option_changed(self): """ Handle a change of the option. @@ -1674,14 +1674,14 @@ class GuiDestinationOption(Gtk.Box): extension = self.__option.get_extension() directory = self.__option.get_directory_entry() value = self.__option.get_value() - + if not directory and not value.endswith(extension): value = value + extension self.__option.set_value(value) elif directory and value.endswith(extension): value = value[:-len(extension)] self.__option.set_value(value) - + self.__entry.set_text( self.__option.get_value() ) def __select_file(self, obj): @@ -1692,7 +1692,7 @@ class GuiDestinationOption(Gtk.Box): my_action = Gtk.FileChooserAction.SELECT_FOLDER else: my_action = Gtk.FileChooserAction.SAVE - + fcd = Gtk.FileChooserDialog(_("Save As"), action=my_action, buttons=(_('_Cancel'), Gtk.ResponseType.CANCEL, @@ -1721,7 +1721,7 @@ class GuiDestinationOption(Gtk.Box): self.__entry.set_text(path) self.__option.set_value(path) fcd.destroy() - + def __text_changed(self, obj): # IGNORE:W0613 - obj is unused """ Handle the change of the value made by the user. @@ -1729,7 +1729,7 @@ class GuiDestinationOption(Gtk.Box): self.__option.disable_signals() self.__option.set_value( self.__entry.get_text() ) self.__option.enable_signals() - + def __update_avail(self): """ Update the availability (sensitivity) of this widget. @@ -1753,7 +1753,7 @@ class GuiDestinationOption(Gtk.Box): self.__option.disconnect(self.conkey1) self.__option.disconnect(self.conkey2) self.__option = None - + #------------------------------------------------------------------------- # # GuiStyleOption class @@ -1769,13 +1769,13 @@ class GuiStyleOption(GuiEnumeratedListOption): @type option: gen.plug.menu.StyleOption @return: nothing """ - GuiEnumeratedListOption.__init__(self, option, dbstate, + GuiEnumeratedListOption.__init__(self, option, dbstate, uistate, track) self.__option = option - + self.__button = Gtk.Button("%s..." % _("Style Editor")) self.__button.connect('clicked', self.__on_style_edit_clicked) - + self.pack_end(self.__button, False, False) def __on_style_edit_clicked(self, *obj): @@ -1784,7 +1784,7 @@ class GuiStyleOption(GuiEnumeratedListOption): done, update the displayed styles.""" from gramps.gen.plug.docgen import StyleSheetList from .report._styleeditor import StyleListDisplay - style_list = StyleSheetList(self.__option.get_style_file(), + style_list = StyleSheetList(self.__option.get_style_file(), self.__option.get_default_style()) StyleListDisplay(style_list, None, None) @@ -1840,14 +1840,14 @@ class GuiBooleanListOption(Gtk.Box): if this_column_counter + 1 > this_column_gets: ncolumn += 1 this_column_counter = 0 - + self.valuekey = self.__option.connect('value-changed', self.__value_changed) self.__option.connect('avail-changed', self.__update_avail) self.__update_avail() - + self.set_tooltip_text(self.__option.get_help()) - + def __list_changed(self, button): """ Handle the change of the value made by the user. @@ -1860,7 +1860,7 @@ class GuiBooleanListOption(Gtk.Box): self.__option.disable_signals() self.__option.set_value(value) self.__option.enable_signals() - + def __update_avail(self): """ Update the availability (sensitivity) of this widget. @@ -1931,7 +1931,7 @@ def make_gui_option(option, dbstate, uistate, track, override=False): """ Stand-alone function so that Options can be used in other ways, too. Takes an Option and returns a GuiOption. - + override: if True will override the GuiOption's normal behavior (in a GuiOption-dependant fashion, for instance in a GuiPersonOption it will force the use of the options's value to set the GuiOption) @@ -1966,17 +1966,17 @@ def add_gui_options(dialog): for category in menu.get_categories(): for name in menu.get_option_names(category): option = menu.get_option(category, name) - + # override option default with xml-saved value: if name in options_dict: option.set_value(options_dict[name]) - + widget, label = make_gui_option(option, dialog.dbstate, dialog.uistate, dialog.track) if widget is not None: if label: - dialog.add_frame_option(category, - option.get_label(), + dialog.add_frame_option(category, + option.get_label(), widget) else: dialog.add_frame_option(category, "", widget) diff --git a/gramps/gui/plug/_windows.py b/gramps/gui/plug/_windows.py index 9896589a1..51403e481 100644 --- a/gramps/gui/plug/_windows.py +++ b/gramps/gui/plug/_windows.py @@ -88,7 +88,7 @@ class PluginStatus(ManagedWindow): HIDDEN = '%s' % _('Hidden') AVAILABLE = '%s'\ % _('Visible') - + def __init__(self, dbstate, uistate, track=[]): self.dbstate = dbstate self.__uistate = uistate @@ -104,15 +104,15 @@ class PluginStatus(ManagedWindow): None, self.title) self.window.set_size_request(750, 400) self.window.connect('response', self.close) - + notebook = Gtk.Notebook() - + #first page with all registered plugins vbox_reg = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) scrolled_window_reg = Gtk.ScrolledWindow() self.list_reg = Gtk.TreeView() # model: plugintype, hidden, pluginname, plugindescr, pluginid - self.model_reg = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING, + self.model_reg = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) self.selection_reg = self.list_reg.get_selection() self.list_reg.set_model(self.model_reg) @@ -143,7 +143,7 @@ class PluginStatus(ManagedWindow): self.__info_btn.connect('clicked', self.__info, self.list_reg, 4) # id_col self.__hide_btn = Gtk.Button(label=_("Hide/Unhide")) hbutbox.add(self.__hide_btn) - self.__hide_btn.connect('clicked', self.__hide, + self.__hide_btn.connect('clicked', self.__hide, self.list_reg, 4, 1) # list, id_col, hide_col if __debug__: self.__edit_btn = Gtk.Button(label=_("Edit")) @@ -153,16 +153,16 @@ class PluginStatus(ManagedWindow): hbutbox.add(self.__load_btn) self.__load_btn.connect('clicked', self.__load, self.list_reg, 4) # id_col vbox_reg.pack_start(hbutbox, False, False, 0) - - notebook.append_page(vbox_reg, + + notebook.append_page(vbox_reg, tab_label=Gtk.Label(label=_('Registered Plugins'))) - + #second page with loaded plugins vbox_loaded = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) scrolled_window = Gtk.ScrolledWindow() self.list = Gtk.TreeView() - self.model = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING, - GObject.TYPE_STRING, object, + self.model = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING, + GObject.TYPE_STRING, object, GObject.TYPE_STRING, GObject.TYPE_STRING) self.selection = self.list.get_selection() self.list.set_model(self.model) @@ -173,12 +173,12 @@ class PluginStatus(ManagedWindow): col.set_sort_column_id(0) col.set_resizable(True) self.list.append_column(col) - col1 = Gtk.TreeViewColumn(_('File'), Gtk.CellRendererText(), + col1 = Gtk.TreeViewColumn(_('File'), Gtk.CellRendererText(), text=1) col1.set_sort_column_id(1) col1.set_resizable(True) self.list.append_column(col1) - col = Gtk.TreeViewColumn(_('Status'), Gtk.CellRendererText(), + col = Gtk.TreeViewColumn(_('Status'), Gtk.CellRendererText(), markup=5) col.set_sort_column_id(5) self.list.append_column(col) @@ -209,7 +209,7 @@ class PluginStatus(ManagedWindow): hbutbox.add(self.__load_btn) self.__load_btn.connect('clicked', self.__load, self.list, 4) # id_col vbox_loaded.pack_start(hbutbox, False, False, 5) - notebook.append_page(vbox_loaded, + notebook.append_page(vbox_loaded, tab_label=Gtk.Label(label=_('Loaded Plugins'))) #third page with method to install plugin @@ -217,15 +217,15 @@ class PluginStatus(ManagedWindow): scrolled_window = Gtk.ScrolledWindow() self.addon_list = Gtk.TreeView() # model: help_name, name, ptype, image, desc, use, rating, contact, download, url - self.addon_model = Gtk.ListStore(GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, + self.addon_model = Gtk.ListStore(GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_STRING, GObject.TYPE_STRING) self.addon_list.set_model(self.addon_model) #self.addon_list.connect('button-press-event', self.button_press) @@ -269,27 +269,27 @@ class PluginStatus(ManagedWindow): self.__add_btn.connect('clicked', self.__get_addon_top) self.__add_all_btn = Gtk.Button(label=_("Install All Addons")) hbutbox.add(self.__add_all_btn) - self.__add_all_btn.connect('clicked', self.__get_all_addons) + self.__add_all_btn.connect('clicked', self.__get_all_addons) self.__refresh_btn = Gtk.Button(label=_("Refresh Addon List")) hbutbox.add(self.__refresh_btn) - self.__refresh_btn.connect('clicked', self.__refresh_addon_list) + self.__refresh_btn.connect('clicked', self.__refresh_addon_list) install_page.pack_start(hbutbox, False, True, 5) - # notebook.append_page(install_page, + # notebook.append_page(install_page, # tab_label=Gtk.Label(label=_('Install Addons'))) #add the notebook to the window self.window.get_content_area().pack_start(notebook, True, True, 0) - + if __debug__: - # Only show the "Reload" button when in debug mode + # Only show the "Reload" button when in debug mode # (without -O on the command line) self.__reload_btn = Gtk.Button(label=_("Reload")) self.window.action_area.add(self.__reload_btn) self.__reload_btn.connect('clicked', self.__reload) - + #obtain hidden plugins from the pluginmanager self.hidden = self.__pmgr.get_hidden_plugin_ids() - + self.window.show_all() self.__populate_lists() self.list_reg.columns_autosize() @@ -356,7 +356,7 @@ class PluginStatus(ManagedWindow): if "|" in url: url, text = url.split("|", 1) # need to get a page that says where it is: - fp = urlopen("%s%s%s" % (URL_WIKISTRING, url, + fp = urlopen("%s%s%s" % (URL_WIKISTRING, url, "&action=edit&externaledit=true&mode=file")) for line in fp: if line.startswith("URL="): @@ -367,14 +367,14 @@ class PluginStatus(ManagedWindow): url = download[1:-1] if " " in url: url, text = url.split(" ", 1) - if (url.endswith(".zip") or - url.endswith(".ZIP") or - url.endswith(".tar.gz") or + if (url.endswith(".zip") or + url.endswith(".ZIP") or + url.endswith(".tar.gz") or url.endswith(".tgz")): # Then this is ok: - self.addon_model.append(row=[help_name, name, ptype, image, desc, use, + self.addon_model.append(row=[help_name, name, ptype, image, desc, use, rating, contact, download, url]) - config.get('plugin.addonplugins').append([help_name, name, ptype, image, desc, use, + config.get('plugin.addonplugins').append([help_name, name, ptype, image, desc, use, rating, contact, download, url]) pm.close() config.save() @@ -389,7 +389,7 @@ class PluginStatus(ManagedWindow): errors = [] for row in self.addon_model: pm.step() - (help_name, name, ptype, image, desc, use, rating, contact, + (help_name, name, ptype, image, desc, use, rating, contact, download, url) = row load_addon_file(url, callback=pm.append_message) self.uistate.viewmanager.do_reg_plugins(self.dbstate, self.uistate) @@ -423,7 +423,7 @@ class PluginStatus(ManagedWindow): """ Select a file from the file system. """ - fcd = Gtk.FileChooserDialog(_("Load Addon"), + fcd = Gtk.FileChooserDialog(_("Load Addon"), buttons=(_('_Cancel'), Gtk.ResponseType.CANCEL, _('_Open'), @@ -462,13 +462,13 @@ class PluginStatus(ManagedWindow): help_name, name, ptype, image, desc, use, rating, contact, download, url = row except: continue - self.addon_model.append(row=[help_name, name, ptype, image, desc, use, + self.addon_model.append(row=[help_name, name, ptype, image, desc, use, rating, contact, download, url]) def __populate_load_list(self): """ Build list of loaded plugins""" fail_list = self.__pmgr.get_fail_list() - + for i in fail_list: # i = (filename, (exception-type, exception, traceback), pdata) err = i[1][0] @@ -501,7 +501,7 @@ class PluginStatus(ManagedWindow): self.model.append(row=[ '%s' % _("OK"), i[0], pdata.description, None, pdata.id, hiddenstr]) - + def __populate_reg_list(self): """ Build list of registered plugins""" for (type, typestr) in PTYPE_STR.items(): @@ -521,7 +521,7 @@ class PluginStatus(ManagedWindow): def __rebuild_load_list(self): self.model.clear() self.__populate_load_list() - + def __rebuild_reg_list(self): self.model_reg.clear() self.__populate_reg_list() @@ -543,13 +543,13 @@ class PluginStatus(ManagedWindow): name = model.get_value(node, 1) if data: PluginTrace(self.uistate, [], data, name) - + def button_press_reg(self, obj, event): """ Callback function from the user clicking on a line in reg plugin """ if event.type == Gdk.EventType._2BUTTON_PRESS and event.button == 1: self.__info(obj, self.list_reg, 4) - + def button_press_addon(self, obj): """ Callback function from the user clicking on a line in reg plugin """ @@ -559,16 +559,16 @@ class PluginStatus(ManagedWindow): if node: url = model.get_value(node, 9) self.install_addon_path.set_text(url) - + def build_menu_names(self, obj): return (self.title, "") - + def __reload(self, obj): """ Callback function from the "Reload" button """ self.__pmgr.reload_plugins() self.__rebuild_load_list() self.__rebuild_reg_list() - + def __info(self, obj, list_obj, id_col): """ Callback function from the "Info" button """ @@ -581,9 +581,9 @@ class PluginStatus(ManagedWindow): typestr = pdata.ptype auth = ' - '.join(pdata.authors) email = ' - '.join(pdata.authors_email) - if len(auth) > 60: + if len(auth) > 60: auth = auth[:60] + '...' - if len(email) > 60: + if len(email) > 60: email = email[:60] + '...' if pdata: infotxt = """%(plugnam)s: %(name)s [%(typestr)s] @@ -612,7 +612,7 @@ class PluginStatus(ManagedWindow): 'plugpat': _("Location"), } InfoDialog(_('Detailed Info'), infotxt, parent=self.window) - + def __hide(self, obj, list_obj, id_col, hide_col): """ Callback function from the "Hide" button """ @@ -631,7 +631,7 @@ class PluginStatus(ManagedWindow): self.hidden.add(id) model.set_value(node, hide_col, self.HIDDEN) self.__pmgr.hide_plugin(id) - + def __load(self, obj, list_obj, id_col): """ Callback function from the "Load" button """ @@ -665,7 +665,7 @@ class PluginStatus(ManagedWindow): #------------------------------------------------------------------------- class PluginTrace(ManagedWindow): """Displays a dialog showing the status of loaded plugins""" - + def __init__(self, uistate, track, data, name): self.name = name title = "%s: %s" % (_("Plugin Error"), name) @@ -677,7 +677,7 @@ class PluginTrace(ManagedWindow): None, title) self.window.set_size_request(600, 400) self.window.connect('response', self.close) - + scrolled_window = Gtk.ScrolledWindow() scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.text = Gtk.TextView() @@ -748,15 +748,15 @@ class ToolManagedWindowBase(ManagedWindow): # Build the list of widgets that are used to extend the Options # frame and to create other frames self.add_user_options() - + self.notebook = Gtk.Notebook() self.notebook.set_border_width(6) self.window.get_content_area().add(self.notebook) - self.results_text = Gtk.TextView() - self.results_text.connect('button-press-event', - self.on_button_press) - self.results_text.connect('motion-notify-event', + self.results_text = Gtk.TextView() + self.results_text.connect('button-press-event', + self.on_button_press) + self.results_text.connect('motion-notify-event', self.on_motion) self.tags = [] self.link_cursor = Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR) @@ -790,8 +790,8 @@ class ToolManagedWindowBase(ManagedWindow): return None def on_motion(self, view, event): - buffer_location = view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, - int(event.x), + buffer_location = view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, + int(event.x), int(event.y)) iter = view.get_iter_at_location(*buffer_location) for (tag, person_handle) in self.tags: @@ -803,8 +803,8 @@ class ToolManagedWindowBase(ManagedWindow): return False # handle event further, if necessary def on_button_press(self, view, event): - buffer_location = view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, - int(event.x), + buffer_location = view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, + int(event.x), int(event.y)) iter = view.get_iter_at_location(*buffer_location) for (tag, person_handle) in self.tags: @@ -831,20 +831,20 @@ class ToolManagedWindowBase(ManagedWindow): end = buffer.get_end_iter() self.tags.append((LinkTag(person_handle, buffer), person_handle)) buffer.apply_tag(self.tags[-1][0], start, end) - + def results_write(self, text): buffer = self.results_text.get_buffer() mark = buffer.create_mark("end", buffer.get_end_iter()) self.results_text.scroll_to_mark(mark, 0.0, True, 0, 0) buffer.insert_at_cursor(text) - buffer.delete_mark_by_name("end") + buffer.delete_mark_by_name("end") def write_to_page(self, page, text): buffer = page.get_buffer() mark = buffer.create_mark("end", buffer.get_end_iter()) page.scroll_to_mark(mark, 0.0, True, 0, 0) buffer.insert_at_cursor(text) - buffer.delete_mark_by_name("end") + buffer.delete_mark_by_name("end") def clear(self, text): # Remove all tags and clear text @@ -869,11 +869,11 @@ class ToolManagedWindowBase(ManagedWindow): tag_table.remove(tag) self.tags = [] buffer.set_text("") - + def pre_run(self): from ..utils import ProgressMeter self.progress = ProgressMeter(self.get_title()) - + def run(self): raise NotImplementedError("tool needs to define a run() method") @@ -896,7 +896,7 @@ class ToolManagedWindowBase(ManagedWindow): some indication of what the report will be, i.e. 'Descendant Report for %s'.""" return self.get_title() - + def setup_title(self): """Set up the title bar of the dialog. This function relies on the get_title() customization function for what the title @@ -913,7 +913,7 @@ class ToolManagedWindowBase(ManagedWindow): title = self.get_header(self.get_title()) label = Gtk.Label(label='%s' % title) label.set_use_markup(True) - self.window.get_content_area().pack_start(label, False, False, + self.window.get_content_area().pack_start(label, False, False, self.border_pad) def add_frame_option(self, frame_name, label_text, widget): @@ -925,7 +925,7 @@ class ToolManagedWindowBase(ManagedWindow): all managing of the widgets, including extracting the final value before the report executes. This task should only be called in the add_user_options task.""" - + if frame_name in self.frames: self.frames[frame_name].append((label_text, widget)) else: @@ -950,7 +950,7 @@ class ToolManagedWindowBase(ManagedWindow): window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) window.add(self.results_text) window.set_shadow_type(Gtk.ShadowType.IN) - self.frames[frame_name] = [[frame_name, window]] + self.frames[frame_name] = [[frame_name, window]] self.frame_names.append(frame_name) l = Gtk.Label(label="%s" % _(frame_name)) l.set_use_markup(True) @@ -962,13 +962,13 @@ class ToolManagedWindowBase(ManagedWindow): def add_page(self, frame_name="Help"): if frame_name not in self.frames: - text = Gtk.TextView() + text = Gtk.TextView() text.set_wrap_mode(Gtk.WrapMode.WORD) window = Gtk.ScrolledWindow() window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) window.add(text) window.set_shadow_type(Gtk.ShadowType.IN) - self.frames[frame_name] = [[frame_name, window]] + self.frames[frame_name] = [[frame_name, window]] self.frame_names.append(frame_name) l = Gtk.Label(label="%s" % _(frame_name)) l.set_use_markup(True) @@ -1036,7 +1036,7 @@ class ToolManagedWindowBatch(tool.BatchTool, ToolManagedWindowBase): self.uistate = uistate tool.BatchTool.__init__(self, dbstate, user, options_class, name) if not self.fail: - ToolManagedWindowBase.__init__(self, dbstate, uistate, + ToolManagedWindowBase.__init__(self, dbstate, uistate, options_class, name, callback) class ToolManagedWindow(tool.Tool, ToolManagedWindowBase): @@ -1044,7 +1044,7 @@ class ToolManagedWindow(tool.Tool, ToolManagedWindowBase): self.dbstate = dbstate self.uistate = uistate tool.Tool.__init__(self, dbstate, options_class, name) - ToolManagedWindowBase.__init__(self, dbstate, uistate, options_class, + ToolManagedWindowBase.__init__(self, dbstate, uistate, options_class, name, callback) #------------------------------------------------------------------------- @@ -1092,7 +1092,7 @@ class UpdateAddons(): for (status,plugin_url,plugin_dict) in addon_update_list: count = get_count(addon_update_list, plugin_dict["t"]) category = _("%(adjective)s: %(addon)s") % { - "adjective": status, + "adjective": status, "addon": _(plugin_dict["t"])} if last_category != category: last_category = category diff --git a/gramps/gui/plug/export/_exportassistant.py b/gramps/gui/plug/export/_exportassistant.py index 4125b5b05..1341275fe 100644 --- a/gramps/gui/plug/export/_exportassistant.py +++ b/gramps/gui/plug/export/_exportassistant.py @@ -83,56 +83,56 @@ _ExportAssistant_pages = { class ExportAssistant(Gtk.Assistant, ManagedWindow) : """ This class creates a GTK assistant to guide the user through the various - Save as/Export options. - - The overall goal is to keep things simple by presenting few choice options + Save as/Export options. + + The overall goal is to keep things simple by presenting few choice options on each assistant page. - + The export formats and options are obtained from the plugins. - + """ #override predefined do_xxx signal handlers __gsignals__ = {"apply": "override", "cancel": "override", "close": "override", "prepare": "override"} - + def __init__(self,dbstate,uistate): """ Set up the assistant, and build all the possible assistant pages. - + Some page elements are left empty, since their contents depends on the user choices and on the success of the attempted save. - + """ self.dbstate = dbstate self.uistate = uistate - + self.writestarted = False self.confirm = None #set up Assistant Gtk.Assistant.__init__(self) - + #set up ManagedWindow self.top_title = _("Export Assistant") ManagedWindow.__init__(self, uistate, [], self.__class__) #set_window is present in both parent classes ManagedWindow.set_window(self, self, None, - self.top_title, isWindow=True) + self.top_title, isWindow=True) #set up callback method for the export plugins self.callback = self.pulse_progressbar - + person_handle = self.uistate.get_active('Person') self.person = self.dbstate.db.get_person_from_handle(person_handle) if not self.person: self.person = self.dbstate.db.find_initial_person() - + pmgr = GuiPluginManager.get_instance() self.__exporters = pmgr.get_export_plugins() self.map_exporters = {} - + self.__previous_page = -1 #create the assistant pages @@ -143,25 +143,25 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : self.create_page_confirm() #no progress page, looks ugly, and user needs to hit forward at end! self.create_page_summary() - + self.option_box_instance = None #we need our own forward function as options page must not always be shown self.set_forward_page_func(self.forward_func, None) - + #ManagedWindow show method ManagedWindow.show(self) def build_menu_names(self, obj): """Override ManagedWindow method.""" return (self.top_title, None) - + def create_page_intro(self): """Create the introduction page.""" label = Gtk.Label(label=self.get_intro_text()) label.set_line_wrap(True) label.set_use_markup(True) label.set_max_width_chars(60) - + image = Gtk.Image() image.set_from_file(SPLASH) @@ -177,13 +177,13 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : self.set_page_title(page, _('Saving your data')) self.set_page_complete(page, True) self.set_page_type(page, Gtk.AssistantPageType.INTRO) - + def create_page_exporttypes(self): """Create the export type page. - + A Title label. A grid of format radio buttons and their descriptions. - + """ self.format_buttons = [] @@ -194,10 +194,10 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : grid = Gtk.Grid() grid.set_row_spacing(6) grid.set_column_spacing(6) - + button = None recent_type = config.get('behavior.recent-export-type') - + exporters = [(x.get_name().replace("_", ""), x) for x in self.__exporters] exporters.sort() ix = 0 @@ -212,35 +212,35 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : if ix == recent_type: button.set_active(True) ix += 1 - + box.pack_start(grid, False, False, 0) - + page = box - + page.show_all() self.append_page(page) self.set_page_title(page, _('Choose the output format')) - + self.set_page_type(page, Gtk.AssistantPageType.CONTENT) - - + + def create_page_options(self): # as we do not know yet what to show, we create an empty page page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) page.set_border_width(12) page.set_spacing(12) - + page.show_all() self.append_page(page) self.set_page_title(page, _('Export options')) self.set_page_complete(page, False) self.set_page_type(page, Gtk.AssistantPageType.CONTENT) - + def forward_func(self, pagenumber, data): """This function is called on forward press. - + Normally, go to next page, however, before options, we decide if options to show """ @@ -248,17 +248,17 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : #decide if options need to be shown: self.option_box_instance = None ix = self.get_selected_format_index() - if not self.map_exporters[ix].get_config(): + if not self.map_exporters[ix].get_config(): # no options needed return pagenumber + 2 elif pagenumber == _ExportAssistant_pages['options']: # need to check to see if we should show file selection - if (self.option_box_instance and + if (self.option_box_instance and hasattr(self.option_box_instance, "no_fileselect")): # don't show fileselect, but mark it ok return pagenumber + 2 return pagenumber + 1 - + def create_options(self): """This method gets the option page, and fills it with the options.""" option = self.get_selected_format_index() @@ -272,13 +272,13 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : self.option_box_instance = config_box_class(self.person, self.dbstate, self.uistate) box = self.option_box_instance.get_option_box() vbox.add(box) - else: + else: self.option_box_instance = None vbox.show_all() - + # We silently assume all options lead to accepted behavior self.set_page_complete(vbox, True) - + def create_page_fileselect(self): self.chooser = Gtk.FileChooserWidget(Gtk.FileChooserAction.SAVE) self.chooser.set_homogeneous(False) # Fix for bug #8350. @@ -287,30 +287,30 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : #global files, ask before overwrite self.chooser.set_local_only(False) self.chooser.set_do_overwrite_confirmation(True) - + #created, folder and name not set self.folder_is_set = False - + #connect changes in filechooser with check to mark page complete self.chooser.connect("selection-changed", self.check_fileselect) self.chooser.connect("key-release-event", self.check_fileselect) #first selection does not give a selection-changed event, grab the button self.chooser.connect("button-release-event", self.check_fileselect) - #Note, we can induce an exotic error, delete filename, + #Note, we can induce an exotic error, delete filename, # do not release button, click forward. We expect user not to do this # In case he does, recheck on confirmation page! - + self.chooser.show_all() page = self.chooser self.append_page(page) self.set_page_title(page, _('Select save file')) self.set_page_type(page, Gtk.AssistantPageType.CONTENT) - + def check_fileselect(self, filechooser, event=None, show=True): - """Given a filechooser, determine if it can be marked complete in + """Given a filechooser, determine if it can be marked complete in the Assistant. - + Used as normal callback and event callback. For callback, we will have show=True """ @@ -324,19 +324,19 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : else: folder = find_folder(folder) #the file must be valid, not a folder, and folder must be valid - if (filename and os.path.basename(filename.strip()) and folder): + if (filename and os.path.basename(filename.strip()) and folder): #this page of the assistant is complete - self.set_page_complete(filechooser, True) + self.set_page_complete(filechooser, True) else : self.set_page_complete(filechooser, False) - + def create_page_confirm(self): # Construct confirm page self.confirm = Gtk.Label() self.confirm.set_line_wrap(True) self.confirm.set_use_markup(True) self.confirm.show() - + image = Gtk.Image() image.set_from_file(SPLASH) @@ -351,7 +351,7 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : self.set_page_title(page, _('Final confirmation')) self.set_page_type(page, Gtk.AssistantPageType.CONFIRM) self.set_page_complete(page, True) - + def create_page_summary(self): # Construct summary page # As this is the last page needs to be of page_type @@ -368,13 +368,13 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : self.labelsum.set_line_wrap(True) self.labelsum.set_use_markup(True) vbox.pack_start(self.labelsum, False, False, 0) - + self.progressbar = Gtk.ProgressBar() vbox.pack_start(self.progressbar, True, True, 0) - + page = vbox page.show_all() - + self.append_page(page) self.set_page_title(page, _('Summary')) self.set_page_complete(page, False) @@ -394,11 +394,11 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : def do_prepare(self, page): """ - The "prepare" signal is emitted when a new page is set as the + The "prepare" signal is emitted when a new page is set as the assistant's current page, but before making the new page visible. - + :param page: the new page to prepare for display. - + """ #determine if we go backward or forward page_number = self.get_current_page() @@ -407,14 +407,14 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : back = True else : back = False - + if back : - #when moving backward, show page as it was, - #page we come from is set incomplete so as to disallow user jumping + #when moving backward, show page as it was, + #page we come from is set incomplete so as to disallow user jumping # to last page after backward move - self.set_page_complete(self.get_nth_page(self.__previous_page), + self.set_page_complete(self.get_nth_page(self.__previous_page), False) - + elif page_number == _ExportAssistant_pages['options']: self.create_options() self.set_page_complete(page, True) @@ -430,7 +430,7 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : self.folder_is_set = True # see if page is complete with above self.check_fileselect(page, show=True) - + elif self.get_page_type(page) == Gtk.AssistantPageType.CONFIRM: # The confirm page with apply button # Present user with what will happen @@ -438,7 +438,7 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : format = self.map_exporters[ix].get_name() page_complete = False # If no file select: - if (self.option_box_instance and + if (self.option_box_instance and hasattr(self.option_box_instance, "no_fileselect")): # No file selection filename = '' @@ -469,18 +469,18 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : 'The selected file and folder to save to ' 'cannot be created or found.\n\n' 'Press Back to return and select a valid filename.' - ) + ) page_complete = False # Set the page_complete status self.set_page_complete(page, page_complete) # If it is ok, then look for alternate confirm_text if (page_complete and - self.option_box_instance and + self.option_box_instance and hasattr(self.option_box_instance, "confirm_text")): # Override message confirm_text = self.option_box_instance.confirm_text self.confirm.set_label(confirm_text) - + elif self.get_page_type(page) == Gtk.AssistantPageType.SUMMARY : # The summary page # Lock page, show progress bar @@ -489,7 +489,7 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : success = self.save() # Unlock page self.post_save() - + #update the label and title if success: conclusion_title = _('Your data has been saved') @@ -520,7 +520,7 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : #remember previous page for next time self.__previous_page = page_number - + def close(self, *obj) : #clean up ManagedWindow menu, then destroy window, bring forward parent Gtk.Assistant.destroy(self) @@ -538,12 +538,12 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : 'If you change your mind during this process, you ' 'can safely press the Cancel button at any time and your ' 'present database will still be intact.') - + def get_selected_format_index(self): """ - Query the format radiobuttons and return the index number of the + Query the format radiobuttons and return the index number of the selected one. - + """ for ix in range(len(self.format_buttons)): button = self.format_buttons[ix] @@ -551,12 +551,12 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : return ix else: return 0 - + def suggest_filename(self): """Prepare suggested filename and set it in the file chooser.""" ix = self.get_selected_format_index() ext = self.map_exporters[ix].get_extension() - + # Suggested folder: try last export, then last import, then home. default_dir = config.get('paths.recent-export-dir') if len(default_dir)<=1: @@ -571,17 +571,17 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : else: new_filename = get_new_filename(ext,default_dir) return (default_dir, os.path.split(new_filename)[1]) - + def save(self): """ Perform the actual Save As/Export operation. - + Depending on the success status, set the text for the final page. - + """ success = False try: - if (self.option_box_instance and + if (self.option_box_instance and hasattr(self.option_box_instance, "no_fileselect")): filename = "" else: @@ -599,14 +599,14 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : success = False log.error(_("Error exporting your Family Tree"), exc_info=True) return success - + def pre_save(self,page): #as all is locked, show the page, which assistant normally only does # after prepare signal! self.writestarted = True page.set_child_visible(True) self.show_all() - + self.uistate.set_busy_cursor(True) self.set_busy_cursor(1) @@ -615,13 +615,13 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : self.set_busy_cursor(0) self.progressbar.hide() self.writestarted = False - + def set_busy_cursor(self,value): """Set or unset the busy cursor while saving data. - - Note : self.get_window() is the Gtk.Assistant Gtk.Window, not + + Note : self.get_window() is the Gtk.Assistant Gtk.Window, not a part of ManagedWindow - + """ if value: self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH)) @@ -632,7 +632,7 @@ class ExportAssistant(Gtk.Assistant, ManagedWindow) : while Gtk.events_pending(): Gtk.main_iteration() - + def pulse_progressbar(self, value, text=None): self.progressbar.set_fraction(min(value/100.0, 1.0)) if text: diff --git a/gramps/gui/plug/export/_exportoptions.py b/gramps/gui/plug/export/_exportoptions.py index 0bcc2d2c6..76a054876 100644 --- a/gramps/gui/plug/export/_exportoptions.py +++ b/gramps/gui/plug/export/_exportoptions.py @@ -2,7 +2,7 @@ # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2007-2008 Donald N. Allingham -# Copyright (C) 2008 Gary Burton +# Copyright (C) 2008 Gary Burton # Copyright (C) 2008 Robert Cheramy # # This program is free software; you can redistribute it and/or modify @@ -40,11 +40,11 @@ from gramps.gen.config import config from gramps.gen.display.name import displayer as name_displayer from gramps.gen.filters import GenericFilter, rules from ...utils import ProgressMeter -from gramps.gen.proxy import (PrivateProxyDb, - LivingProxyDb, - FilterProxyDb, +from gramps.gen.proxy import (PrivateProxyDb, + LivingProxyDb, + FilterProxyDb, ReferencedBySelectionProxyDb) - + class Progress(object): """ Mirros the same interface that the ExportAssistant uses in the @@ -91,7 +91,7 @@ class WriterOptionBox(object): """ Create a VBox with the option widgets and define methods to retrieve the options. - + """ def __init__(self, person, dbstate, uistate): self.person = person @@ -115,7 +115,7 @@ class WriterOptionBox(object): self.initialized_show_options = False self.set_config(config) # The following are special properties. Create them to force the - # export wizard to not ask for a file, and to override the + # export wizard to not ask for a file, and to override the # confirmation message: #self.no_fileselect = True #self.confirm_text = "You made it, kid!" @@ -142,7 +142,7 @@ class WriterOptionBox(object): from gi.repository import Gtk from gi.repository import Pango widget = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) - + full_database_row = Gtk.Box() label = Gtk.Label(label=_("Unfiltered Family Tree:")) full_database_row.pack_start(label, True, True, 0) @@ -161,7 +161,7 @@ class WriterOptionBox(object): full_database_row.pack_end(button, False, True, 0) widget.pack_start(full_database_row, False, True, 0) - + self.private_check = Gtk.CheckButton.new_with_mnemonic( _('_Do not include records marked private')) self.private_check.connect("clicked", self.mark_dirty) @@ -232,8 +232,8 @@ class WriterOptionBox(object): dbstate.db = self.proxy_dbase[widget.proxy_name] dbstate.open = True run_quick_report_by_name(dbstate, - self.uistate, - 'filterbyname', + self.uistate, + 'filterbyname', 'all') def preview(self, widget): @@ -381,13 +381,13 @@ class WriterOptionBox(object): self.vbox_n[n].pack_end(self.down_n[n], False, True, 0) # some spacer buttons: up = Gtk.Button() - up.set_sensitive(0) + up.set_sensitive(0) image = Gtk.Image() image.set_from_icon_name('go-up', Gtk.IconSize.MENU) up.set_image(image) self.spacer.pack_start(up, False, True, 0) down = Gtk.Button() - down.set_sensitive(0) + down.set_sensitive(0) image = Gtk.Image() image.set_from_icon_name('go-down', Gtk.IconSize.MENU) down.set_image(image) @@ -399,12 +399,12 @@ class WriterOptionBox(object): for n in range(5): self.up_n[n].show() self.down_n[n].show() - + self.proxy_options_showing = not self.proxy_options_showing def swap(self, widget): """ - Swap the order of two proxies. + Swap the order of two proxies. """ row1 = widget.row row2 = widget.row + 1 @@ -429,17 +429,17 @@ class WriterOptionBox(object): # feature request 2356: avoid genitive form des.set_name(_("Descendants of %s") % name) des.add_rule(rules.person.IsDescendantOf([gramps_id, 1])) - + df = GenericFilter() # feature request 2356: avoid genitive form df.set_name(_("Descendant Families of %s") % name) df.add_rule(rules.person.IsDescendantFamilyOf([gramps_id, 1])) - + ans = GenericFilter() # feature request 2356: avoid genitive form ans.set_name(_("Ancestors of %s") % name) ans.add_rule(rules.person.IsAncestorOf([gramps_id, 1])) - + com = GenericFilter() com.set_name(_("People with common ancestor with %s") % name) com.add_rule(rules.person.HasCommonAncestorWith([gramps_id])) @@ -447,11 +447,11 @@ class WriterOptionBox(object): return [des, df, ans, com] def get_proxy_value(self, proxy_name): - return [value for (name, value) in + return [value for (name, value) in self.config.get('export.proxy-order') if name == proxy_name][0] def set_proxy_value(self, proxy_name, proxy_value): - [name_value for name_value in + [name_value for name_value in self.config.get('export.proxy-order') if name_value[0] == proxy_name][0][1] = int(proxy_value) def get_proxy_names(self): @@ -463,8 +463,8 @@ class WriterOptionBox(object): def parse_options(self): """ - Extract the common values from the GTK widgets. - + Extract the common values from the GTK widgets. + After this function is called, the following variables are defined: private = privacy requested @@ -491,7 +491,7 @@ class WriterOptionBox(object): if node: self.restrict_num = model[node][1] self.set_proxy_value("living", self.restrict_option.get_active()) - + if self.filter_note: model = self.filter_note.get_model() node = self.filter_note.get_active_iter() @@ -557,7 +557,7 @@ class WriterOptionBox(object): def apply_proxy(self, proxy_name, dbase, progress=None): """ Apply the named proxy to the dbase, and return. - proxy_name is one of + proxy_name is one of ["person", "note", "privacy", "living", "reference"] """ # If the private flag is set, apply the PrivateProxyDb @@ -581,10 +581,10 @@ class WriterOptionBox(object): LivingProxyDb.MODE_EXCLUDE_ALL, ][self.restrict_num] dbase = LivingProxyDb( - dbase, - mode) # + dbase, + mode) # - # If the filter returned by cfilter is not empty, apply the + # If the filter returned by cfilter is not empty, apply the # FilterProxyDb (Person Filter) elif proxy_name == "person": if self.cfilter != None and not self.cfilter.is_empty(): @@ -649,7 +649,7 @@ class WriterOptionBox(object): lambda : self.edit_filter_save(filterdb, namespace)) else: # can't edit this filter from ...dialog import ErrorDialog - ErrorDialog(_("Cannot edit a system filter"), + ErrorDialog(_("Cannot edit a system filter"), _("Please select a different filter to edit")) def edit_filter_save(self, filterdb, namespace): diff --git a/gramps/gui/plug/quick/__init__.py b/gramps/gui/plug/quick/__init__.py index 38535ee35..fd40506e5 100644 --- a/gramps/gui/plug/quick/__init__.py +++ b/gramps/gui/plug/quick/__init__.py @@ -24,11 +24,11 @@ "Quick Report Framework" -from ._quickreports import (create_web_connect_menu, - create_quickreport_menu, - get_quick_report_list, - run_quick_report_by_name, - run_quick_report_by_name_direct, +from ._quickreports import (create_web_connect_menu, + create_quickreport_menu, + get_quick_report_list, + run_quick_report_by_name, + run_quick_report_by_name_direct, run_report) from ._quicktable import QuickTable from ._textbufdoc import TextBufDoc diff --git a/gramps/gui/plug/quick/_quickreports.py b/gramps/gui/plug/quick/_quickreports.py index 3452c1d3b..1a66c16e5 100644 --- a/gramps/gui/plug/quick/_quickreports.py +++ b/gramps/gui/plug/quick/_quickreports.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -57,8 +57,8 @@ from gi.repository import Gtk from ...pluginmanager import GuiPluginManager from gramps.gen.plug import (CATEGORY_QR_PERSON, CATEGORY_QR_FAMILY, CATEGORY_QR_MEDIA, CATEGORY_QR_EVENT, CATEGORY_QR_SOURCE, CATEGORY_QR_MISC, - CATEGORY_QR_PLACE, CATEGORY_QR_REPOSITORY, - CATEGORY_QR_NOTE, CATEGORY_QR_CITATION, + CATEGORY_QR_PLACE, CATEGORY_QR_REPOSITORY, + CATEGORY_QR_NOTE, CATEGORY_QR_CITATION, CATEGORY_QR_SOURCE_OR_CITATION) from ._textbufdoc import TextBufDoc from gramps.gen.simple import make_basic_stylesheet @@ -78,11 +78,11 @@ def flatten(L): return retval def create_web_connect_menu(dbstate, uistate, nav_group, handle): - """ + """ This functions querries the registered web connects. It collects the connects of the requested category, which must be one of nav_group. - + It constructs the ui string of the menu, and it's actions. The action callback function is constructed, using the dbstate and the handle as input method. A tuple is returned, containing the ui @@ -104,13 +104,13 @@ def create_web_connect_menu(dbstate, uistate, nav_group, handle): except: import traceback traceback.print_exc() - connections = [] + connections = [] connections = flatten(connections) connections.sort(key=lambda plug: plug.name) actions = [] for connect in connections: ofile.write('' % connect.key) - actions.append((connect.key, None, connect.name, None, None, + actions.append((connect.key, None, connect.name, None, None, connect(dbstate, uistate, nav_group, handle))) ofile.write('') retval = [ofile.getvalue()] @@ -118,7 +118,7 @@ def create_web_connect_menu(dbstate, uistate, nav_group, handle): return retval def create_quickreport_menu(category,dbstate,uistate, handle) : - """ This functions querries the registered quick reports with + """ This functions querries the registered quick reports with quick_report_list of _PluginMgr.py It collects the reports of the requested category, which must be one of CATEGORY_QR_PERSON, CATEGORY_QR_FAMILY, @@ -135,12 +135,12 @@ def create_quickreport_menu(category,dbstate,uistate, handle) : actions = [] ofile = StringIO() ofile.write('') - + actions.append(('QuickReport', None, _("Quick View"), None, None, None)) - + menu = Gtk.Menu() menu.show() - + #select the reports to show showlst = [] pmgr = GuiPluginManager.get_instance() @@ -148,16 +148,16 @@ def create_quickreport_menu(category,dbstate,uistate, handle) : if pdata.supported and pdata.category == category : #add tuple function, translated name, name, status showlst.append(pdata) - + showlst.sort(key=lambda x: x.name) for pdata in showlst: new_key = pdata.id.replace(' ', '-') ofile.write('' % new_key) - actions.append((new_key, None, pdata.name, None, None, - make_quick_report_callback(pdata, category, + actions.append((new_key, None, pdata.name, None, None, + make_quick_report_callback(pdata, category, dbstate, uistate, handle))) ofile.write('') - + return (ofile.getvalue(), actions) def make_quick_report_callback(pdata, category, dbstate, uistate, handle): @@ -166,8 +166,8 @@ def make_quick_report_callback(pdata, category, dbstate, uistate, handle): def get_quick_report_list(qv_category=None): """ Returns a list of PluginData of quick views of category qv_category - CATEGORY_QR_PERSON, CATEGORY_QR_FAMILY, CATEGORY_QR_EVENT, - CATEGORY_QR_SOURCE, CATEGORY_QR_MISC, CATEGORY_QR_PLACE, + CATEGORY_QR_PERSON, CATEGORY_QR_FAMILY, CATEGORY_QR_EVENT, + CATEGORY_QR_SOURCE, CATEGORY_QR_MISC, CATEGORY_QR_PLACE, CATEGORY_QR_REPOSITORY, CATEGORY_QR_MEDIA, CATEGORY_QR_CITATION, CATEGORY_QR_SOURCE_OR_CITATION or None for all """ @@ -178,11 +178,11 @@ def get_quick_report_list(qv_category=None): names.append(pdata) # (see below for item struct) return names -def run_quick_report_by_name(dbstate, uistate, report_name, handle, +def run_quick_report_by_name(dbstate, uistate, report_name, handle, container=None, **kwargs): """ Run a QuickView by name. - **kwargs provides a way of passing special quick views additional + **kwargs provides a way of passing special quick views additional arguments. """ report = None @@ -192,7 +192,7 @@ def run_quick_report_by_name(dbstate, uistate, report_name, handle, report = pdata break if report: - return run_report(dbstate, uistate, report.category, + return run_report(dbstate, uistate, report.category, handle, report, container=container, **kwargs) else: raise AttributeError("No such quick report '%s'" % report_name) @@ -220,17 +220,17 @@ def run_quick_report_by_name_direct(report_name, database, document, handle): d.close() return retval else: - raise ImportError("Quick report id = '%s' could not be loaded" + raise ImportError("Quick report id = '%s' could not be loaded" % report_name) else: raise AttributeError("No such quick report id = '%s'" % report_name) - -def run_report(dbstate, uistate, category, handle, pdata, container=None, + +def run_report(dbstate, uistate, category, handle, pdata, container=None, **kwargs): """ Run a Quick Report. - Optionally container can be passed, rather than putting the report - in a new window. + Optionally container can be passed, rather than putting the report + in a new window. **kwargs are only used for special quick views that allow additional arguments, and that are run by run_quick_report_by_name(). """ @@ -274,7 +274,7 @@ def run_report(dbstate, uistate, category, handle, pdata, container=None, obj = dbstate.db.get_note_from_handle(handle) elif category == CATEGORY_QR_MISC: obj = handle - else: + else: obj = None else: # allow caller to send object directly obj = handle diff --git a/gramps/gui/plug/quick/_quicktable.py b/gramps/gui/plug/quick/_quicktable.py index ea1f64c8b..c5921c730 100644 --- a/gramps/gui/plug/quick/_quicktable.py +++ b/gramps/gui/plug/quick/_quicktable.py @@ -53,8 +53,8 @@ from gramps.gui.utils import model_to_text, text_to_clipboard from ...widgets.multitreeview import MultiTreeView from ...ddtargets import DdTargets from ..quick import run_quick_report_by_name -from ...editors import (EditPerson, EditEvent, EditFamily, EditCitation, - EditSource, EditPlace, EditRepository, EditNote, +from ...editors import (EditPerson, EditEvent, EditFamily, EditCitation, + EditSource, EditPlace, EditRepository, EditNote, EditMedia) #------------------------------------------------------------------------- @@ -89,11 +89,11 @@ class QuickTable(SimpleTable): node = store.get_iter(tpath) if tpath else None if node: treeview.grab_focus() - index = store.get_value(node, 0) + index = store.get_value(node, 0) # FIXME: make popup come where cursor is #rectangle = treeview.get_visible_rect() #column = treeview.get_column(0) - #rectangle = treeview.get_cell_area("0:0", + #rectangle = treeview.get_cell_area("0:0", #x, y = rectangle.x, rectangle.y #func = lambda menu: (x, y, True) elif event.button == 3: @@ -128,42 +128,42 @@ class QuickTable(SimpleTable): # See details (edit, etc): objclass, handle = self._link[index] menu_item = Gtk.MenuItem(label=_("the object|See %s details") % glocale.trans_objclass(objclass)) - menu_item.connect("activate", + menu_item.connect("activate", lambda widget: self.on_table_doubleclick(treeview)) popup.append(menu_item) menu_item.show() # Add other items to menu: - if (self._callback_leftclick or + if (self._callback_leftclick or (index is not None and self._link[index])): objclass, handle = self._link[index] if objclass == 'Person': menu_item = Gtk.MenuItem(label=_("the object|Make %s active") % glocale.trans_objclass('Person')) - menu_item.connect("activate", + menu_item.connect("activate", lambda widget: self.on_table_click(treeview)) popup.append(menu_item) menu_item.show() - if (self.simpledoc.doc.dbstate.db != + if (self.simpledoc.doc.dbstate.db != self.simpledoc.doc.dbstate.db.basedb and (index is not None and self._link[index])): objclass, handle = self._link[index] - if (objclass == 'Filter' and + if (objclass == 'Filter' and handle[0] in ['Person', 'Family', 'Place', 'Event', 'Repository', 'Note', 'MediaObject', 'Citation', 'Source']): menu_item = Gtk.MenuItem(label=_("See data not in Filter")) - menu_item.connect("activate", + menu_item.connect("activate", lambda widget: self.show_not_in_filter(handle[0])) popup.append(menu_item) menu_item.show() # Show the popup menu: popup.popup(None, None, func, None, button_code, event_time) - return True + return True return False def show_not_in_filter(self, obj_class): run_quick_report_by_name(self.simpledoc.doc.dbstate, - self.simpledoc.doc.uistate, - 'filterbyname', + self.simpledoc.doc.uistate, + 'filterbyname', 'Inverse %s' % obj_class) def on_table_doubleclick(self, obj): @@ -188,7 +188,7 @@ class QuickTable(SimpleTable): person = self.access.dbase.get_person_from_handle(handle) if person: try: - EditPerson(self.simpledoc.doc.dbstate, + EditPerson(self.simpledoc.doc.dbstate, self.simpledoc.doc.uistate, [], person) return True # handled event except WindowActiveError: @@ -197,7 +197,7 @@ class QuickTable(SimpleTable): event = self.access.dbase.get_event_from_handle(handle) if event: try: - EditEvent(self.simpledoc.doc.dbstate, + EditEvent(self.simpledoc.doc.dbstate, self.simpledoc.doc.uistate, [], event) return True # handled event except WindowActiveError: @@ -206,7 +206,7 @@ class QuickTable(SimpleTable): ref = self.access.dbase.get_family_from_handle(handle) if ref: try: - EditFamily(self.simpledoc.doc.dbstate, + EditFamily(self.simpledoc.doc.dbstate, self.simpledoc.doc.uistate, [], ref) return True # handled event except WindowActiveError: @@ -215,7 +215,7 @@ class QuickTable(SimpleTable): ref = self.access.dbase.get_citation_from_handle(handle) if ref: try: - EditCitation(self.simpledoc.doc.dbstate, + EditCitation(self.simpledoc.doc.dbstate, self.simpledoc.doc.uistate, [], ref) return True # handled event except WindowActiveError: @@ -224,7 +224,7 @@ class QuickTable(SimpleTable): ref = self.access.dbase.get_source_from_handle(handle) if ref: try: - EditSource(self.simpledoc.doc.dbstate, + EditSource(self.simpledoc.doc.dbstate, self.simpledoc.doc.uistate, [], ref) return True # handled event except WindowActiveError: @@ -233,7 +233,7 @@ class QuickTable(SimpleTable): ref = self.access.dbase.get_place_from_handle(handle) if ref: try: - EditPlace(self.simpledoc.doc.dbstate, + EditPlace(self.simpledoc.doc.dbstate, self.simpledoc.doc.uistate, [], ref) return True # handled event except WindowActiveError: @@ -242,7 +242,7 @@ class QuickTable(SimpleTable): ref = self.access.dbase.get_repository_from_handle(handle) if ref: try: - EditRepository(self.simpledoc.doc.dbstate, + EditRepository(self.simpledoc.doc.dbstate, self.simpledoc.doc.uistate, [], ref) return True # handled event except WindowActiveError: @@ -251,7 +251,7 @@ class QuickTable(SimpleTable): ref = self.access.dbase.get_note_from_handle(handle) if ref: try: - EditNote(self.simpledoc.doc.dbstate, + EditNote(self.simpledoc.doc.dbstate, self.simpledoc.doc.uistate, [], ref) return True # handled event except WindowActiveError: @@ -260,23 +260,23 @@ class QuickTable(SimpleTable): ref = self.access.dbase.get_object_from_handle(handle) if ref: try: - EditMedia(self.simpledoc.doc.dbstate, + EditMedia(self.simpledoc.doc.dbstate, self.simpledoc.doc.uistate, [], ref) return True # handled event except WindowActiveError: pass elif objclass == 'PersonList': run_quick_report_by_name(self.simpledoc.doc.dbstate, - self.simpledoc.doc.uistate, - 'filterbyname', + self.simpledoc.doc.uistate, + 'filterbyname', 'list of people', handles=handle) elif objclass == 'Filter': if isinstance(handle, list): handle = handle[0] run_quick_report_by_name(self.simpledoc.doc.dbstate, - self.simpledoc.doc.uistate, - 'filterbyname', + self.simpledoc.doc.uistate, + 'filterbyname', handle) return False # didn't handle event @@ -300,7 +300,7 @@ class QuickTable(SimpleTable): handle = handle[0] if objclass == 'Person': from gi.repository import GLib - # If you emmit the signal here and it causes this table to be deleted, + # If you emmit the signal here and it causes this table to be deleted, # then you'll crash Python: #self.simpledoc.doc.uistate.set_active(handle, 'Person') # So, let's return from this, then change the active person: @@ -347,7 +347,7 @@ class QuickTable(SimpleTable): 0) treeview.drag_source_set_target_list(tglist) #treeview.enable_model_drag_dest(DdTargets.all_targets(), - # Gdk.DragAction.DEFAULT) + # Gdk.DragAction.DEFAULT) treeview.connect('drag_data_get', self.object_drag_data_get) treeview.set_grid_lines(Gtk.TreeViewGridLines.BOTH) #treeview.connect('row-activated', on_table_doubleclick, self) @@ -376,7 +376,7 @@ class QuickTable(SimpleTable): column.set_resizable(True) if self._sort_vals[cnt] != []: sort_data.append(self._sort_vals[cnt]) - column.set_sort_column_id(len(self._columns) + + column.set_sort_column_id(len(self._columns) + len(sort_data)) sort_data_types.append(int) else: @@ -384,7 +384,7 @@ class QuickTable(SimpleTable): treeview.append_column(column) self.model_index_of_column[col] = model_index #if model_index == sort_index: - # FIXME: what to set here? + # FIXME: what to set here? model_index += 1 cnt += 1 if self.title: diff --git a/gramps/gui/plug/quick/_textbufdoc.py b/gramps/gui/plug/quick/_textbufdoc.py index d0c260fc5..759c3e1ce 100644 --- a/gramps/gui/plug/quick/_textbufdoc.py +++ b/gramps/gui/plug/quick/_textbufdoc.py @@ -35,14 +35,14 @@ from gi.repository import Pango, PangoCairo # #------------------------------------------------------------------------ from gramps.gen.plug.docgen import (BaseDoc, TextDoc, FONT_SERIF, PARA_ALIGN_RIGHT, - FONT_SANS_SERIF, FONT_MONOSPACE, PARA_ALIGN_CENTER, + FONT_SANS_SERIF, FONT_MONOSPACE, PARA_ALIGN_CENTER, PARA_ALIGN_LEFT) from ...managedwindow import ManagedWindow RESOLUTION = PangoCairo.font_map_get_default().get_resolution() def pixels(cm): - return int (RESOLUTION/2.54 * cm) + return int (RESOLUTION/2.54 * cm) #------------------------------------------------------------------------ # @@ -55,7 +55,7 @@ _WIDTH_IN_CHARS = 72 class DisplayBuf(ManagedWindow): def __init__(self, title, document): self.title = title - ManagedWindow.__init__(self, document.uistate, [], + ManagedWindow.__init__(self, document.uistate, [], document) self.set_window(Gtk.Dialog("",document.uistate.window, Gtk.DialogFlags.DESTROY_WITH_PARENT, @@ -70,7 +70,7 @@ class DisplayBuf(ManagedWindow): scrolled_window.add(document.text_view) self.window.vbox.pack_start(scrolled_window, True, True, 0) self.window.show_all() - + def build_menu_names(self, obj): return ('View', _('Quick View')) @@ -159,7 +159,7 @@ class TextBufDoc(BaseDoc, TextDoc): #-------------------------------------------------------------------- # - # Close the file. Call the app if required. + # Close the file. Call the app if required. # #-------------------------------------------------------------------- def close(self): @@ -194,7 +194,7 @@ class TextBufDoc(BaseDoc, TextDoc): #-------------------------------------------------------------------- # - # Starts a paragraph. + # Starts a paragraph. # #-------------------------------------------------------------------- def start_paragraph(self, style_name, leader=None): @@ -206,7 +206,7 @@ class TextBufDoc(BaseDoc, TextDoc): #-------------------------------------------------------------------- # - # End a paragraph. First format it to the desired widths. + # End a paragraph. First format it to the desired widths. # If not in table cell, write it immediately. If in the cell, # add it to the list for this cell after formatting. # @@ -219,7 +219,7 @@ class TextBufDoc(BaseDoc, TextDoc): #-------------------------------------------------------------------- # - # Start a table. Grab the table style, and store it. + # Start a table. Grab the table style, and store it. # #-------------------------------------------------------------------- def start_table(self, name,style_name): @@ -295,7 +295,7 @@ class TextBufDoc(BaseDoc, TextDoc): while span: self.cell_widths[self.cellnum-span] = 0 span -= 1 - + #-------------------------------------------------------------------- # # End a cell. Find out the number of lines in this cell, correct @@ -337,7 +337,7 @@ class TextBufDoc(BaseDoc, TextDoc): #-------------------------------------------------------------------- # - # Writes text. + # Writes text. #-------------------------------------------------------------------- def write_text(self,text,mark=None): self.text = self.text + text diff --git a/gramps/gui/plug/report/_bookdialog.py b/gramps/gui/plug/report/_bookdialog.py index 800a378df..625dbd75c 100644 --- a/gramps/gui/plug/report/_bookdialog.py +++ b/gramps/gui/plug/report/_bookdialog.py @@ -22,7 +22,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -# Written by Alex Roitman, +# Written by Alex Roitman, # largely based on the BaseDoc classes by Don Allingham #------------------------------------------------------------------------- @@ -94,7 +94,7 @@ def _initialize_options(options, dbstate, uistate): """ Validates all options by making sure that their values are consistent with the database. - + menu: The Menu class dbase: the database the options will be applied to """ @@ -102,7 +102,7 @@ def _initialize_options(options, dbstate, uistate): return dbase = dbstate.get_database() menu = options.menu - + for name in menu.get_all_option_names(): option = menu.get_option_by_name(name) value = option.get_value() @@ -112,7 +112,7 @@ def _initialize_options(options, dbstate, uistate): person_handle = uistate.get_active('Person') person = dbase.get_person_from_handle(person_handle) option.set_value(person.get_gramps_id()) - + elif isinstance(option, FamilyOption): if not dbase.get_family_from_gramps_id(value): person_handle = uistate.get_active('Person') @@ -136,31 +136,31 @@ def _initialize_options(options, dbstate, uistate): def _get_subject(options, dbase): """ Attempts to determine the subject of a set of options. The subject would - likely be a person (using a PersonOption) or a filter (using a + likely be a person (using a PersonOption) or a filter (using a FilterOption) - + options: The ReportOptions class dbase: the database for which it corresponds """ if not hasattr(options, "menu"): return "" menu = options.menu - + option_names = menu.get_all_option_names() if not option_names: return _("Entire Database") for name in option_names: option = menu.get_option_by_name(name) - + if isinstance(option, FilterOption): return option.get_filter().get_name() - + elif isinstance(option, PersonOption): gid = option.get_value() person = dbase.get_person_from_gramps_id(gid) return _nd.display(person) - + elif isinstance(option, FamilyOption): family = dbase.get_family_from_gramps_id(option.get_value()) if not family: @@ -168,25 +168,25 @@ def _get_subject(options, dbase): family_id = family.get_gramps_id() fhandle = family.get_father_handle() mhandle = family.get_mother_handle() - + if fhandle: father = dbase.get_person_from_handle(fhandle) father_name = _nd.display(father) else: father_name = _("unknown father") - + if mhandle: mother = dbase.get_person_from_handle(mhandle) mother_name = _nd.display(mother) else: mother_name = _("unknown mother") - + name = _("%(father)s and %(mother)s (%(id)s)") % { - 'father' : father_name, - 'mother' : mother_name, + 'father' : father_name, + 'mother' : mother_name, 'id' : family_id } return name - + return "" #------------------------------------------------------------------------ @@ -196,7 +196,7 @@ def _get_subject(options, dbase): #------------------------------------------------------------------------ class BookListDisplay(object): """ - Interface into a dialog with the list of available books. + Interface into a dialog with the list of available books. Allows the user to select and/or delete a book from the list. """ @@ -209,14 +209,14 @@ class BookListDisplay(object): nodelete: if not 0 then the Delete button is hidden dosave: if 1 then the book list is saved on hitting OK """ - + self.booklist = booklist self.dosave = dosave self.xml = Glade('book.glade') self.top = self.xml.toplevel self.unsaved_changes = False - set_titles(self.top, self.xml.get_object('title2'), + set_titles(self.top, self.xml.get_object('title2'), _('Available Books')) if nodelete: @@ -249,7 +249,7 @@ class BookListDisplay(object): def redraw(self): """Redraws the list of currently available books""" - + self.blist.model.clear() names = self.booklist.get_book_names() if not len(names): @@ -271,7 +271,7 @@ class BookListDisplay(object): def on_booklist_delete_clicked(self, obj): """ Deletes selected book from the list. - + This change is not final. OK button has to be clicked to save the list. """ store, the_iter = self.blist.get_selected() @@ -292,13 +292,13 @@ class BookListDisplay(object): _('Proceed'), _('Cancel')) if q.run(): - return + return else: self.top.run() def on_button_press(self, obj, event): """ - Checks for a double click event. In the list, we want to + Checks for a double click event. In the list, we want to treat a double click as if it was OK button press. """ if event.type == Gdk.EventType._2BUTTON_PRESS and event.button == 1: @@ -353,12 +353,12 @@ class BookOptions(ReportOptions): #------------------------------------------------------------------------- # -# Book creation dialog +# Book creation dialog # #------------------------------------------------------------------------- class BookSelector(ManagedWindow): """ - Interface into a dialog setting up the book. + Interface into a dialog setting up the book. Allows the user to add/remove/reorder/setup items for the current book and to clear/load/save/edit whole books. @@ -375,7 +375,7 @@ class BookSelector(ManagedWindow): self.xml = Glade('book.glade', toplevel="top") window = self.xml.toplevel - + title_label = self.xml.get_object('title') self.set_window(window, title_label, self.title) window.show() @@ -420,12 +420,12 @@ class BookSelector(ManagedWindow): avail_titles = [ (_('Name'), 0, 230), (_('Type'), 1, 80 ), ( '' , -1, 0 ) ] - + book_titles = [ (_('Item name'), -1, 230), (_('Type'), -1, 80 ), ( '', -1, 0 ), (_('Subject'), -1, 50 ) ] - + self.avail_nr_cols = len(avail_titles) self.book_nr_cols = len(book_titles) @@ -441,7 +441,7 @@ class BookSelector(ManagedWindow): def draw_avail_list(self): """ Draw the list with the selections available for the book. - + The selections are read from the book item registry. """ pmgr = GuiPluginManager.get_instance() @@ -469,7 +469,7 @@ class BookSelector(ManagedWindow): def open_book(self, book): """ Open the book: set the current set of selections to this book's items. - + book: the book object to load. """ if book.get_paper_name(): @@ -493,12 +493,12 @@ class BookSelector(ManagedWindow): WarningDialog(_('Different database'), _( 'This book was created with the references to database ' '%s.\n\n This makes references to the central person ' - 'saved in the book invalid.\n\n' - 'Therefore, the central person for each item is being set ' + 'saved in the book invalid.\n\n' + 'Therefore, the central person for each item is being set ' 'to the active person of the currently opened database.') % book.get_dbname(), parent=self.window) - + self.book.clear() self.book_model.clear() for saved_item in book.get_item_list(): @@ -514,21 +514,21 @@ class BookSelector(ManagedWindow): menu_option = menu.get_option_by_name(optname) if menu_option: menu_option.set_value(opt_dict[optname]) - + _initialize_options(item.option_class, self.dbstate, self.uistate) item.set_style_name(saved_item.get_style_name()) self.book.append_item(item) - + data = [ item.get_translated_name(), item.get_category(), item.get_name() ] - + data[2] = _get_subject(item.option_class, self.db) self.book_model.add(data) def on_add_clicked(self, obj): """ - Add an item to the current selections. - + Add an item to the current selections. + Use the selected available item to get the item's name in the registry. """ store, the_iter = self.avail_model.get_selected() @@ -629,7 +629,7 @@ class BookSelector(ManagedWindow): def book_button_press(self, obj, event): """ Double-click on the current book selection is the same as setup. - Right click evokes the context menu. + Right click evokes the context menu. """ if event.type == Gdk.EventType._2BUTTON_PRESS and event.button == 1: self.on_setup_clicked(obj) @@ -639,7 +639,7 @@ class BookSelector(ManagedWindow): def avail_button_press(self, obj, event): """ Double-click on the available selection is the same as add. - Right click evokes the context menu. + Right click evokes the context menu. """ if event.type == Gdk.EventType._2BUTTON_PRESS and event.button == 1: self.on_add_clicked(obj) @@ -648,12 +648,12 @@ class BookSelector(ManagedWindow): def build_book_context_menu(self, event): """Builds the menu with item-centered and book-centered options.""" - + store, the_iter = self.book_model.get_selected() if the_iter: - sensitivity = 1 + sensitivity = 1 else: - sensitivity = 0 + sensitivity = 0 entries = [ (_('_Up'), 'go-up', self.on_up_clicked, sensitivity), (_('_Down'), 'go-down', self.on_down_clicked, sensitivity), @@ -684,12 +684,12 @@ class BookSelector(ManagedWindow): def build_avail_context_menu(self, event): """Builds the menu with the single Add option.""" - + store, the_iter = self.avail_model.get_selected() if the_iter: - sensitivity = 1 + sensitivity = 1 else: - sensitivity = 0 + sensitivity = 0 entries = [ (_('_Add'), 'list-add', self.on_add_clicked, sensitivity), ] @@ -710,9 +710,9 @@ class BookSelector(ManagedWindow): self.menu.append(item) self.menu.popup(None, None, None, None, event.button, event.time) - def on_book_ok_clicked(self, obj): + def on_book_ok_clicked(self, obj): """ - Run final BookDialog with the current book. + Run final BookDialog with the current book. """ if self.book.item_list: BookDialog(self.dbstate, self.uistate, @@ -725,7 +725,7 @@ class BookSelector(ManagedWindow): def on_save_clicked(self, obj): """ - Save the current book in the xml booklist file. + Save the current book in the xml booklist file. """ self.book_list = BookList(self.file, self.db) name = str(self.name_entry.get_text()) @@ -757,7 +757,7 @@ class BookSelector(ManagedWindow): def on_open_clicked(self, obj): """ - Run the BookListDisplay dialog to present the choice of books to open. + Run the BookListDisplay dialog to present the choice of books to open. """ self.book_list = BookList(self.file, self.db) booklistdisplay = BookListDisplay(self.book_list, 1, 0) @@ -770,7 +770,7 @@ class BookSelector(ManagedWindow): def on_edit_clicked(self, obj): """ - Run the BookListDisplay dialog to present the choice of books to delete. + Run the BookListDisplay dialog to present the choice of books to delete. """ self.book_list = BookList(self.file, self.db) booklistdisplay = BookListDisplay(self.book_list, 0, 1) @@ -813,18 +813,18 @@ class BookItemDialog(ReportDialog): self.parse_user_options() self.options.handler.save_options() - + def setup_target_frame(self): """Target frame is not used.""" pass - + def parse_target_frame(self): """Target frame is not used.""" return 1 def init_options(self, option_class): try: - if issubclass(option_class, object): + if issubclass(option_class, object): self.options = option_class(self.raw_name, self.db) except TypeError: self.options = option_class @@ -842,22 +842,22 @@ class BookItemDialog(ReportDialog): for category in menu.get_categories(): for name in menu.get_option_names(category): option = menu.get_option(category, name) - + # override option default with xml-saved value: if name in options_dict: option.set_value(options_dict[name]) - + widget, label = make_gui_option(option, self.dbstate, self.uistate, self.track, self.is_from_saved_book) if widget is not None: if label: self.add_frame_option(category, - option.get_label(), + option.get_label(), widget) else: self.add_frame_option(category, "", widget) - + #------------------------------------------------------------------------- # # _BookFormatComboBox @@ -868,13 +868,13 @@ class _BookFormatComboBox(Gtk.ComboBox): def __init__(self, active): GObject.GObject.__init__(self) - + pmgr = GuiPluginManager.get_instance() self.__bookdoc_plugins = [] for plugin in pmgr.get_docgen_plugins(): if plugin.get_text_support() and plugin.get_draw_support(): self.__bookdoc_plugins.append(plugin) - + self.store = Gtk.ListStore(GObject.TYPE_STRING) self.set_model(self.store) cell = Gtk.CellRendererText() @@ -899,13 +899,13 @@ class _BookFormatComboBox(Gtk.ComboBox): #------------------------------------------------------------------------ # -# The final dialog - paper, format, target, etc. +# The final dialog - paper, format, target, etc. # #------------------------------------------------------------------------ class BookDialog(DocReportDialog): """ - A usual Report.Dialog subclass. - + A usual Report.Dialog subclass. + Create a dialog selecting target, format, and paper/HTML options. """ @@ -971,7 +971,7 @@ class BookDialog(DocReportDialog): for item in self.book.get_item_list(): item.option_class.set_document(self.doc) report_class = item.get_write_item() - obj = write_book_item(self.database, report_class, + obj = write_book_item(self.database, report_class, item.option_class, user) self.rptlist.append(obj) append_styles(selected_style, item) @@ -980,7 +980,7 @@ class BookDialog(DocReportDialog): self.doc.open(self.target_path) def make_book(self): - """The actual book. Start it out, then go through the item list + """The actual book. Start it out, then go through the item list and call each item's write_book_item method.""" self.doc.init() @@ -993,7 +993,7 @@ class BookDialog(DocReportDialog): rpt.begin_report() rpt.write_report() self.doc.close() - + if self.open_with_app.get_active(): open_file_with_default_application(self.target_path) diff --git a/gramps/gui/plug/report/_docreportdialog.py b/gramps/gui/plug/report/_docreportdialog.py index 068770207..3a517cead 100644 --- a/gramps/gui/plug/report/_docreportdialog.py +++ b/gramps/gui/plug/report/_docreportdialog.py @@ -61,7 +61,7 @@ class DocReportDialog(ReportDialog): def __init__(self, dbstate, uistate, option_class, name, trans_name): """Initialize a dialog to request that the user select options for a basic *stand-alone* report.""" - + self.style_name = "default" self.firstpage_added = False self.CSS = PLUGMAN.process_plugin_data('WEBSTUFF') @@ -93,7 +93,7 @@ class DocReportDialog(ReportDialog): """Create a document of the type requested by the user. """ pstyle = self.paper_frame.get_paper_style() - + if self.doc_options: self.doc = self.format(self.selected_style, pstyle, self.doc_options) @@ -102,7 +102,7 @@ class DocReportDialog(ReportDialog): if not self.format_menu.get_active_plugin().get_paper_used(): #set css filename self.doc.set_css_filename(self.css_filename) - + self.options.set_document(self.doc) def doc_type_changed(self, obj, preserve_tab=True): @@ -142,7 +142,7 @@ class DocReportDialog(ReportDialog): if ext_val: fname = self.target_fileentry.get_full_path(0) (spath, ext) = os.path.splitext(fname) - + fname = spath + "." + ext_val self.target_fileentry.set_filename(fname) self.target_fileentry.set_sensitive(True) @@ -192,7 +192,7 @@ class DocReportDialog(ReportDialog): base = "%s.%s" % (default_name, ext) spath = os.path.normpath(os.path.join(spath, base)) self.target_fileentry.set_filename(spath) - + def setup_report_options_frame(self): self.paper_frame = PaperFrame(self.options.handler.get_paper_metric(), self.options.handler.get_paper_name(), @@ -223,7 +223,7 @@ class DocReportDialog(ReportDialog): css_filename = self.options.handler.get_css_filename() active_index = 0 index = 0 - for (name, id) in sorted([(self.CSS[key]["translation"], self.CSS[key]["id"]) + for (name, id) in sorted([(self.CSS[key]["translation"], self.CSS[key]["id"]) for key in self.CSS]): if self.CSS[id]["user"]: self.css_combo.append_text(self.CSS[id]["translation"]) @@ -273,15 +273,15 @@ class DocReportDialog(ReportDialog): self.options.handler.set_orientation(self.paper_frame.get_orientation()) self.options.handler.set_margins(self.paper_frame.get_paper_margins()) self.options.handler.set_custom_paper_size(self.paper_frame.get_custom_paper_size()) - + self.parse_user_options() # Create the output document. self.make_document() - + self.parse_doc_options() # Save options self.options.handler.save_options() - config.set('interface.open-with-default-viewer', + config.set('interface.open-with-default-viewer', self.open_with_app.get_active()) diff --git a/gramps/gui/plug/report/_drawreportdialog.py b/gramps/gui/plug/report/_drawreportdialog.py index 9465b6a8d..a69420cc0 100644 --- a/gramps/gui/plug/report/_drawreportdialog.py +++ b/gramps/gui/plug/report/_drawreportdialog.py @@ -49,13 +49,13 @@ class _DrawFormatComboBox(Gtk.ComboBox): def __init__(self, active): GObject.GObject.__init__(self) - + pmgr = GuiPluginManager.get_instance() self.__drawdoc_plugins = [] for plugin in pmgr.get_docgen_plugins(): if plugin.get_draw_support(): self.__drawdoc_plugins.append(plugin) - + self.store = Gtk.ListStore(GObject.TYPE_STRING) self.set_model(self.store) cell = Gtk.CellRendererText() @@ -95,7 +95,7 @@ class DrawReportDialog(DocReportDialog): """ self.format_menu = None self.category = CATEGORY_DRAW - DocReportDialog.__init__(self, dbstate, uistate, opt, + DocReportDialog.__init__(self, dbstate, uistate, opt, name, translated_name) def make_doc_menu(self,active=None): diff --git a/gramps/gui/plug/report/_fileentry.py b/gramps/gui/plug/report/_fileentry.py index 1ea48077d..52c806426 100644 --- a/gramps/gui/plug/report/_fileentry.py +++ b/gramps/gui/plug/report/_fileentry.py @@ -56,7 +56,7 @@ class FileEntry(Gtk.Box): my_action = Gtk.FileChooserAction.SELECT_FOLDER else: my_action = Gtk.FileChooserAction.SAVE - + dialog = Gtk.FileChooserDialog(self.title, self.parent, action=my_action, @@ -97,8 +97,8 @@ class FileEntry(Gtk.Box): return self.entry.get_text() def set_directory_entry(self, opt): - """ - Configure the FileEntry to either select a directory or a file. + """ + Configure the FileEntry to either select a directory or a file. Set it to True to select a directory. Set it to False to select a file. """ diff --git a/gramps/gui/plug/report/_graphvizreportdialog.py b/gramps/gui/plug/report/_graphvizreportdialog.py index 0adbb158c..43ab16a12 100644 --- a/gramps/gui/plug/report/_graphvizreportdialog.py +++ b/gramps/gui/plug/report/_graphvizreportdialog.py @@ -101,7 +101,7 @@ class GraphvizFormatComboBox(Gtk.ComboBox): def get_clname(self): return graphdoc.FORMATS[self.get_active()]["type"] - + #----------------------------------------------------------------------- # # GraphvizReportDialog @@ -118,23 +118,23 @@ class GraphvizReportDialog(ReportDialog): self.dbname = dbstate.db.get_dbname() ReportDialog.__init__(self, dbstate, uistate, opt, name, translated_name) - + def init_options(self, option_class): try: if issubclass(option_class, object): # Old-style class self.options = option_class(self.raw_name, self.dbstate.get_database()) except TypeError: - self.options = option_class - + self.options = option_class + menu = Menu() self.__gvoptions.add_menu_options(menu) - + for category in menu.get_categories(): for name in menu.get_option_names(category): option = menu.get_option(category, name) self.options.add_menu_option(category, name, option) - + self.options.load_previous_values() def init_interface(self): @@ -172,7 +172,7 @@ class GraphvizReportDialog(ReportDialog): base = "%s%s" % (default_name, ext) # "ext" already has a dot spath = os.path.normpath(os.path.join(spath, base)) self.target_fileentry.set_filename(spath) - + def setup_report_options_frame(self): self.paper_label = Gtk.Label(label='%s' % _("Paper Options")) self.paper_label.set_use_markup(True) @@ -199,7 +199,7 @@ class GraphvizReportDialog(ReportDialog): file. Those changes are made here. """ self.open_with_app.set_sensitive(True) - + fname = self.target_fileentry.get_full_path(0) (spath, ext) = os.path.splitext(fname) @@ -209,7 +209,7 @@ class GraphvizReportDialog(ReportDialog): else: fname = spath self.target_fileentry.set_filename(fname) - + output_format_str = obj.get_oformat_str() if output_format_str in ['gvpdf', 'gspdf', 'ps']: # Always use 72 DPI for PostScript and PDF files. @@ -232,11 +232,11 @@ class GraphvizReportDialog(ReportDialog): """Create a document of the type requested by the user. """ pstyle = self.paper_frame.get_paper_style() - + self.doc = self.format(self.options, pstyle) - + self.options.set_document(self.doc) - + def on_ok_clicked(self, obj): """The user is satisfied with the dialog choices. Validate the output file name before doing anything else. If there is @@ -257,22 +257,22 @@ class GraphvizReportDialog(ReportDialog): self.options.handler.set_margins(self.paper_frame.get_paper_margins()) self.options.handler.set_custom_paper_size( self.paper_frame.get_custom_paper_size()) - + # Create the output document. self.make_document() - + # Save options self.options.handler.save_options() - config.set('interface.open-with-default-viewer', + config.set('interface.open-with-default-viewer', self.open_with_app.get_active()) - + def parse_format_frame(self): """Parse the format frame of the dialog. Save the user selected output format for later use.""" self.format = self.format_menu.get_reference() format_name = self.format_menu.get_clname() self.options.handler.set_format_name(format_name) - + def setup_style_frame(self): """Required by ReportDialog""" pass diff --git a/gramps/gui/plug/report/_papermenu.py b/gramps/gui/plug/report/_papermenu.py index 9db4b5e9c..487a012de 100644 --- a/gramps/gui/plug/report/_papermenu.py +++ b/gramps/gui/plug/report/_papermenu.py @@ -54,7 +54,7 @@ class PaperComboBox(Gtk.ComboBox): def __init__(self,default_name): GObject.GObject.__init__(self) self.set_wrap_width(4) - + self.store = Gtk.ListStore(GObject.TYPE_STRING) self.set_model(self.store) cell = Gtk.CellRendererText() @@ -73,7 +73,7 @@ class PaperComboBox(Gtk.ComboBox): key_name = key.trans_pname # display the translated paper name self.store.append(row=[key_name]) index += 1 - + self.set_active(start_index) def get_value(self): @@ -95,7 +95,7 @@ class OrientationComboBox(Gtk.ComboBox): def __init__(self,default=PAPER_PORTRAIT): GObject.GObject.__init__(self) - + self.store = Gtk.ListStore(GObject.TYPE_STRING) self.set_model(self.store) cell = Gtk.CellRendererText() @@ -129,7 +129,7 @@ class OrientationComboBox(Gtk.ComboBox): # # PaperFrame # -#------------------------------------------------------------------------- +#------------------------------------------------------------------------- class PaperFrame(Gtk.Box): """PaperFrame provides all the entry necessary to specify a paper style. """ def __init__(self,default_metric,default_name,default_orientation, @@ -139,20 +139,20 @@ class PaperFrame(Gtk.Box): self.paper_grid = glade_xml.get_object('paper_grid') - + # get all the widgets widgets = ('pwidth', 'pheight', 'lmargin', 'rmargin', 'tmargin', 'bmargin', 'lunits1', 'lunits2', 'lunits3', 'lunits4', 'lunits5', 'lunits6', 'metric') - + for w in widgets: setattr(self, w, glade_xml.get_object(w)) - + # insert custom widgets self.papersize_menu = PaperComboBox(default_name) self.orientation_menu = OrientationComboBox(default_orientation) self.metric.set_active(default_metric) - + # connect all widgets format_grid = glade_xml.get_object('format_grid') format_grid.attach(self.papersize_menu, 1, 0, 1, 1) @@ -172,7 +172,7 @@ class PaperFrame(Gtk.Box): self.rmargin.set_text("%.2f" % margins[1]) self.tmargin.set_text("%.2f" % margins[2]) self.bmargin.set_text("%.2f" % margins[3]) - + self.paper_grid.show_all() self.paper_grid.reparent(self) @@ -196,7 +196,7 @@ class PaperFrame(Gtk.Box): else: raise ValueError('Paper dimension unit "%s" is not allowed' % self.paper_unit) - + def units_changed(self, checkbox): """Metric checkbox 'toggled' callback.""" paper_size, paper_name = self.get_paper_size() @@ -210,21 +210,21 @@ class PaperFrame(Gtk.Box): self.paper_unit = 'in.' self.paper_unit_multiplier = 2.54 paper_unit_text = _("inch|in.") - + self.lunits1.set_text(paper_unit_text) self.lunits2.set_text(paper_unit_text) self.lunits3.set_text(paper_unit_text) self.lunits4.set_text(paper_unit_text) self.lunits5.set_text(paper_unit_text) self.lunits6.set_text(paper_unit_text) - + if self.paper_unit == 'cm': self.pwidth.set_text("%.2f" % paper_size.get_width()) self.pheight.set_text("%.2f" % paper_size.get_height()) else: self.pwidth.set_text("%.2f" % paper_size.get_width_inches()) self.pheight.set_text("%.2f" % paper_size.get_height_inches()) - + self.lmargin.set_text("%.2f" % (paper_margins[0] / self.paper_unit_multiplier)) self.rmargin.set_text("%.2f" % @@ -233,7 +233,7 @@ class PaperFrame(Gtk.Box): (paper_margins[2] / self.paper_unit_multiplier)) self.bmargin.set_text("%.2f" % (paper_margins[3] / self.paper_unit_multiplier)) - + def get_paper_size(self): """Read and validate paper size values. @@ -246,7 +246,7 @@ class PaperFrame(Gtk.Box): try: h = float(str(self.pheight.get_text().replace(",", "."))) w = float(str(self.pwidth.get_text().replace(",", ".") )) - + if h <= 1.0 or w <= 1.0: papersize.set_height(29.7) papersize.set_width(21.0) @@ -256,18 +256,18 @@ class PaperFrame(Gtk.Box): except: papersize.set_height(29.7) papersize.set_width(21.0) - + return papersize, papername def get_paper_margins(self): """Get and validate margin values from dialog entries. - + Values returned in [cm]. - + """ paper_margins = [str(margin.get_text()) for margin in (self.lmargin, self.rmargin, self.tmargin, self.bmargin)] - + for i, margin in enumerate(paper_margins): try: paper_margins[i] = float(margin.replace(",", ".")) @@ -275,7 +275,7 @@ class PaperFrame(Gtk.Box): paper_margins[i] = max(paper_margins[i], 0) except: paper_margins[i] = 2.54 - + return paper_margins def get_custom_paper_size(self): @@ -299,18 +299,18 @@ class PaperFrame(Gtk.Box): paper_size, paper_name = self.get_paper_size() paper_orientation = self.orientation_menu.get_value() paper_margins = self.get_paper_margins() - + pstyle = PaperStyle(paper_size, paper_orientation, *paper_margins) return pstyle - + def get_paper_metric(self): return self.metric.get_active() def get_paper_name(self): paper_size, paper_name = self.get_paper_size() return paper_name - + def get_orientation(self): return self.orientation_menu.get_value() diff --git a/gramps/gui/plug/report/_reportdialog.py b/gramps/gui/plug/report/_reportdialog.py index 916b9c0fa..7c549dd16 100644 --- a/gramps/gui/plug/report/_reportdialog.py +++ b/gramps/gui/plug/report/_reportdialog.py @@ -87,7 +87,7 @@ class ReportDialog(ManagedWindow): track=[]): """Initialize a dialog to request that the user select options for a basic *stand-alone* report.""" - + self.style_name = "default" self.firstpage_added = False self.raw_name = name @@ -95,7 +95,7 @@ class ReportDialog(ManagedWindow): self.uistate = uistate self.db = dbstate.db self.report_name = trans_name - + ManagedWindow.__init__(self, uistate, track, self) self.init_options(option_class) @@ -215,7 +215,7 @@ class ReportDialog(ManagedWindow): name = self.report_name category = standalone_categories[self.category][1] return "%s - %s - Gramps" % (name, category) - + #------------------------------------------------------------------------ # # Functions related to extending the options @@ -230,13 +230,13 @@ class ReportDialog(ManagedWindow): def parse_user_options(self): """Called to allow parsing of added widgets. - It is called when OK is pressed in a dialog. + It is called when OK is pressed in a dialog. All custom widgets should provide a parsing code here.""" try: self.options.parse_user_options() except: LOG.error("Failed to parse user options.", exc_info=True) - + def add_option(self, label_text, widget): """Takes a text string and a Gtk Widget, and stores them to be appended to the Options section of the dialog. The text string @@ -256,13 +256,13 @@ class ReportDialog(ManagedWindow): all managing of the widgets, including extracting the final value before the report executes. This task should only be called in the add_user_options task.""" - + if frame_name in self.frames: self.frames[frame_name].append((label_text, widget)) else: self.frames[frame_name] = [(label_text, widget)] self.frame_names.append(frame_name) - + #------------------------------------------------------------------------ # # Functions to create a default output style. @@ -277,13 +277,13 @@ class ReportDialog(ManagedWindow): created here instead of inline with the rest of the style frame, because it must be recreated to reflect any changes whenever the user closes the style editor dialog.""" - + if default is None: default = self.style_name - + style_sheet_map = self.style_sheet_list.get_style_sheet_map() self.style_menu.set(style_sheet_map, default) - + #------------------------------------------------------------------------ # # Functions related to setting up the dialog window. @@ -297,11 +297,11 @@ class ReportDialog(ManagedWindow): def setup_header(self): """Set up the header line bar of the dialog.""" - label = Gtk.Label(label='%s' % + label = Gtk.Label(label='%s' % self.report_name) label.set_use_markup(True) self.window.vbox.pack_start(label, False, False, self.border_pad) - + def setup_style_frame(self): """Set up the style frame of the dialog. This function relies on other routines to create the default style for this report, @@ -329,7 +329,7 @@ class ReportDialog(ManagedWindow): self.grid.attach(self.style_menu, 2, self.row, 1, 1) self.grid.attach(self.style_button, 3, self.row, 1, 1) self.row += 1 - + # Build the initial list of available styles sets. This # includes the default style set and any style sets saved from # previous invocations of gramps. @@ -359,11 +359,11 @@ class ReportDialog(ManagedWindow): grid.set_border_width(6) grid.set_column_spacing(12) grid.set_row_spacing(6) - + label = Gtk.Label(label="%s" % _("Report Options")) label.set_halign(Gtk.Align.START) label.set_use_markup(True) - + self.notebook.append_page(grid, label) # Setup requested widgets @@ -404,13 +404,13 @@ class ReportDialog(ManagedWindow): else: grid.attach(widget, 2, row, 1, 1) row += 1 - + #------------------------------------------------------------------------ # # Customization hooks for stand-alone reports (subclass ReportDialog) # #------------------------------------------------------------------------ - def setup_format_frame(self): + def setup_format_frame(self): """Not used in bare report dialogs. Override in the subclass.""" pass @@ -455,7 +455,7 @@ class ReportDialog(ManagedWindow): self.grid.set_border_width(12) self.grid.attach(label, 0, self.row, 4, 1) self.row += 1 - + def setup_target_frame(self): """Set up the target frame of the dialog. This function relies on several target_xxx() customization functions to @@ -471,7 +471,7 @@ class ReportDialog(ManagedWindow): self.target_fileentry.set_hexpand(True) self.grid.attach(self.target_fileentry, 2, self.row, 2, 1) self.row += 1 - + #------------------------------------------------------------------------ # # Functions related to retrieving data from the dialog window @@ -511,7 +511,7 @@ class ReportDialog(ManagedWindow): _('_Overwrite'), None, _('_Change filename'), None, parent=self.window) - + if a.get_response() == Gtk.ResponseType.YES: return None @@ -536,11 +536,11 @@ class ReportDialog(ManagedWindow): 'or create it.') % parent_dir, parent=self.window) return None - + self.set_default_directory(os.path.dirname(self.target_path) + os.sep) self.options.handler.output = self.target_path return 1 - + def parse_style_frame(self): """Parse the style frame of the dialog. Save the user selected output style for later use. Note that this routine @@ -568,17 +568,17 @@ class ReportDialog(ManagedWindow): # Preparation self.parse_style_frame() self.parse_user_options() - + # Save options self.options.handler.save_options() - + def on_cancel(self, *obj): pass def on_help_clicked(self, *obj): from ...display import display_help display_help(URL_REPORT_PAGE, self.report_name.replace(" ", "_")) - + def on_style_edit_clicked(self, *obj): """The user has clicked on the 'Edit Styles' button. Create a style sheet editor object and let them play. When they are @@ -632,7 +632,7 @@ class ReportDialog(ManagedWindow): def parse_doc_options(self): """ Called to allow parsing of added docgen widgets. - It is called when OK is pressed in a dialog. + It is called when OK is pressed in a dialog. """ if not self.doc_options: return @@ -681,7 +681,7 @@ def report(dbstate, uistate, person, report_class, options_class, report_class(dbstate, uistate) except WindowActiveError: pass - return + return else: dialog_class = ReportDialog @@ -699,14 +699,14 @@ def report(dbstate, uistate, person, report_class, options_class, MyReport.write_report() MyReport.end_report() - # Web reports do not have a target frame + # Web reports do not have a target frame # The GtkPrint generator can not be "opened" if hasattr(dialog, "open_with_app") and \ dialog.open_with_app.get_property('sensitive') == True and \ dialog.open_with_app.get_active(): out_file = dialog.options.get_output() open_file_with_default_application(out_file) - + except FilterError as msg: (m1, m2) = msg.messages() ErrorDialog(m1, m2, parent=uistate.window) @@ -716,13 +716,13 @@ def report(dbstate, uistate, person, report_class, options_class, except ReportError as msg: (m1, m2) = msg.messages() ErrorDialog(m1, m2, parent=uistate.window) - except DatabaseError as msg: + except DatabaseError as msg: ErrorDialog(_("Report could not be created"), str(msg), parent=uistate.window) # The following except statement will catch all "NoneType" exceptions. # This is useful for released code where the exception is most likely # a corrupt database. But it is less useful for developing new reports -# where the exception is most likely a report bug. +# where the exception is most likely a report bug. # except AttributeError,msg: # if str(msg).startswith("'NoneType' object has no attribute"): # # "'NoneType' object has no attribute ..." usually means diff --git a/gramps/gui/plug/report/_stylecombobox.py b/gramps/gui/plug/report/_stylecombobox.py index 997a019b5..1c534c4d1 100644 --- a/gramps/gui/plug/report/_stylecombobox.py +++ b/gramps/gui/plug/report/_stylecombobox.py @@ -45,7 +45,7 @@ class StyleComboBox(Gtk.ComboBox): cell = Gtk.CellRendererText() self.pack_start(cell,True) self.add_attribute(cell,'text',0) - + def set(self,style_map,default): """ Set the options for the ComboBox, using the passed style @@ -68,7 +68,7 @@ class StyleComboBox(Gtk.ComboBox): self.store.append(row=[key]) if key == default: start_index = index - + self.set_active(start_index) def get_value(self): diff --git a/gramps/gui/plug/report/_styleeditor.py b/gramps/gui/plug/report/_styleeditor.py index ce3c07979..6baf3d8f6 100644 --- a/gramps/gui/plug/report/_styleeditor.py +++ b/gramps/gui/plug/report/_styleeditor.py @@ -13,7 +13,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -51,7 +51,7 @@ from gi.repository import Gtk, Gdk # #------------------------------------------------------------------------ from gramps.gen.plug.docgen import (StyleSheet, FONT_SERIF, FONT_SANS_SERIF, - PARA_ALIGN_RIGHT, PARA_ALIGN_CENTER, PARA_ALIGN_LEFT, + PARA_ALIGN_RIGHT, PARA_ALIGN_CENTER, PARA_ALIGN_LEFT, PARA_ALIGN_JUSTIFY, ParagraphStyle, TableStyle, TableCellStyle, GraphicsStyle) from ...listmodel import ListModel @@ -65,7 +65,7 @@ from ...glade import Glade #------------------------------------------------------------------------ class StyleListDisplay(object): """ - Shows the available paragraph/font styles. Allows the user to select, + Shows the available paragraph/font styles. Allows the user to select, add, edit, and delete styles from a StyleSheet. """ @@ -78,26 +78,26 @@ class StyleListDisplay(object): callback - task called with an object has been added. """ self.callback = callback - + self.sheetlist = stylesheetlist - + self.top = Glade(toplevel='styles') self.window = self.top.toplevel - set_titles(self.window, self.top.get_object('title'), + set_titles(self.window, self.top.get_object('title'), _('Document Styles')) self.top.connect_signals({ "destroy_passed_object" : self.__close, - "on_ok_clicked" : self.on_ok_clicked, - "on_add_clicked" : self.on_add_clicked, - "on_delete_clicked" : self.on_delete_clicked, - "on_button_press" : self.on_button_press, + "on_ok_clicked" : self.on_ok_clicked, + "on_add_clicked" : self.on_add_clicked, + "on_delete_clicked" : self.on_delete_clicked, + "on_button_press" : self.on_button_press, "on_edit_clicked" : self.on_edit_clicked, "on_save_style_clicked" : dummy_callback, }) - self.list = ListModel(self.top.get_object("list"), + self.list = ListModel(self.top.get_object("list"), [(_('Style'), -1, 10)], ) self.redraw() if parent_window: @@ -110,7 +110,7 @@ class StyleListDisplay(object): def redraw(self): """Redraws the list of styles that are current available""" - + self.list.model.clear() self.list.add([_("default")]) @@ -128,7 +128,7 @@ class StyleListDisplay(object): StyleEditor(_("New Style"), style, self) def on_ok_clicked(self, obj): - """Called with the OK button is clicked; Calls the callback task, + """Called with the OK button is clicked; Calls the callback task, then saves the stylesheet.""" if self.callback is not None: self.callback() @@ -143,7 +143,7 @@ class StyleListDisplay(object): def on_button_press(self, obj, event): if event.type == Gdk.EventType._2BUTTON_PRESS and event.button == 1: self.on_edit_clicked(obj) - + def on_edit_clicked(self, obj): """ Called with the EDIT button is clicked. @@ -152,7 +152,7 @@ class StyleListDisplay(object): store, node = self.list.selection.get_selected() if not node: return - + name = str(self.list.model.get_value(node, 0)) if name == _('default'): # the default style cannot be edited return @@ -180,7 +180,7 @@ class StyleEditor(object): Edits the current style definition. Presents a dialog allowing the values of the paragraphs in the style to be altered. """ - + def __init__(self, name, style, parent): """ Create the StyleEditor. @@ -191,19 +191,19 @@ class StyleEditor(object): """ self.current_style = None self.current_name = None - + self.style = StyleSheet(style) self.parent = parent self.top = Glade(toplevel='editor') self.window = self.top.toplevel - + self.top.connect_signals({ - "on_save_style_clicked" : self.on_save_style_clicked, + "on_save_style_clicked" : self.on_save_style_clicked, "destroy_passed_object" : self.__close, - "on_ok_clicked" : dummy_callback, - "on_add_clicked" : dummy_callback, - "on_delete_clicked" : dummy_callback, - "on_button_press" : dummy_callback, + "on_ok_clicked" : dummy_callback, + "on_add_clicked" : dummy_callback, + "on_delete_clicked" : dummy_callback, + "on_button_press" : dummy_callback, "on_edit_clicked" : dummy_callback, }) @@ -223,12 +223,12 @@ class StyleEditor(object): self.line_style.pack_start(renderer_text, True) self.line_style.add_attribute(renderer_text, "text", 1) - set_titles(self.window, self.top.get_object('title'), + set_titles(self.window, self.top.get_object('title'), _('Style editor')) self.top.get_object("label6").set_text(_("point size|pt")) - + titles = [(_('Style'), 0, 130)] - self.plist = ListModel(self.top.get_object("ptree"), titles, + self.plist = ListModel(self.top.get_object("ptree"), titles, self.change_display) for widget_name in ('color', 'bgcolor', 'line_color', 'fill_color'): @@ -257,7 +257,7 @@ class StyleEditor(object): for d_name in names: self.plist.add([d_name], self.style.get_draw_style(d_name)) self.plist.select_row(0) - + if self.parent: self.window.set_transient_for(parent.window) self.window.run() @@ -373,7 +373,7 @@ class StyleEditor(object): descr = p.get_description() self.pdescription.set_text(descr or _("No description available") ) - + font = p.get_font() self.top.get_object("size").set_value(font.get_size()) if font.get_type_face() == FONT_SERIF: @@ -475,7 +475,7 @@ class StyleEditor(object): p = self.current_style font = p.get_font() font.set_size(self.top.get_object("size").get_value_as_int()) - + if self.top.get_object("roman").get_active(): font.set_type_face(FONT_SERIF) else: @@ -489,9 +489,9 @@ class StyleEditor(object): elif self.top.get_object("ralign").get_active(): p.set_alignment(PARA_ALIGN_RIGHT) elif self.top.get_object("calign").get_active(): - p.set_alignment(PARA_ALIGN_CENTER) + p.set_alignment(PARA_ALIGN_CENTER) else: - p.set_alignment(PARA_ALIGN_JUSTIFY) + p.set_alignment(PARA_ALIGN_JUSTIFY) p.set_right_margin(self.top.get_object("rmargin").get_value()) p.set_left_margin(self.top.get_object("lmargin").get_value()) @@ -508,7 +508,7 @@ class StyleEditor(object): font.set_color(color2rgb(color)) bg_color = self.top.get_object("bgcolor").get_color() p.set_background_color(color2rgb(bg_color)) - + self.style.add_paragraph_style(self.current_name, self.current_style) def on_save_style_clicked(self, obj): @@ -554,8 +554,8 @@ def color2rgb(color): return (color.red >> 8, color.green >> 8, color.blue >> 8) def dummy_callback(obj): - """Dummy callback to satisfy gtkbuilder on connect of signals. - There are two widgets in the glade file, although only one is needed, + """Dummy callback to satisfy gtkbuilder on connect of signals. + There are two widgets in the glade file, although only one is needed, the signals of the other must be connected too """ pass diff --git a/gramps/gui/plug/report/_textreportdialog.py b/gramps/gui/plug/report/_textreportdialog.py index dae44d46a..ad169bfab 100644 --- a/gramps/gui/plug/report/_textreportdialog.py +++ b/gramps/gui/plug/report/_textreportdialog.py @@ -48,9 +48,9 @@ class _TextFormatComboBox(Gtk.ComboBox): from all textdoc plugins. """ def __init__(self, active): - + GObject.GObject.__init__(self) - + pmgr = GuiPluginManager.get_instance() self.__textdoc_plugins = [] for plugin in pmgr.get_docgen_plugins(): @@ -72,7 +72,7 @@ class _TextFormatComboBox(Gtk.ComboBox): active_index = index index += 1 self.set_active(active_index) - + def get_active_plugin(self): """ Get the plugin represented by the currently active selection. @@ -96,7 +96,7 @@ class TextReportDialog(DocReportDialog): """ self.format_menu = None self.category = CATEGORY_TEXT - DocReportDialog.__init__(self, dbstate, uistate, options, + DocReportDialog.__init__(self, dbstate, uistate, options, name, translated_name) def make_doc_menu(self, active=None): diff --git a/gramps/gui/plug/report/_webreportdialog.py b/gramps/gui/plug/report/_webreportdialog.py index c65713433..020fc0482 100644 --- a/gramps/gui/plug/report/_webreportdialog.py +++ b/gramps/gui/plug/report/_webreportdialog.py @@ -51,7 +51,7 @@ class WebReportDialog(ReportDialog): def setup_target_frame(self): """Target frame is not used.""" pass - + def parse_target_frame(self): """Target frame is not used.""" return 1 diff --git a/gramps/gui/plug/tool.py b/gramps/gui/plug/tool.py index be32c7ae8..88610d235 100644 --- a/gramps/gui/plug/tool.py +++ b/gramps/gui/plug/tool.py @@ -42,7 +42,7 @@ from gramps.gen.display.name import displayer as name_displayer from gramps.gen.errors import WindowActiveError from gramps.gen.plug._options import (Options, OptionHandler, OptionList, OptionListCollection) -from gramps.gen.plug import (TOOL_DEBUG, TOOL_ANAL, TOOL_DBPROC, TOOL_DBFIX, +from gramps.gen.plug import (TOOL_DEBUG, TOOL_ANAL, TOOL_DBPROC, TOOL_DBFIX, TOOL_REVCTL, TOOL_UTILS) #------------------------------------------------------------------------- @@ -79,10 +79,10 @@ class Tool(object): # FIXME: pass in person_id self.options = options_class(name, None, dbstate) else: # must be some kind of class or we get a TypeError - self.options = options_class(name) + self.options = options_class(name) except TypeError: self.options = options_class - + self.options.load_previous_values() if hasattr(options_class, 'options_dict'): old_opts = options_class.saved_options_dict @@ -128,11 +128,11 @@ class ActivePersonTool(Tool): """ def __init__(self, dbstate, uistate, options_class, name): - + if not uistate.get_active('Person'): # TODO: should we replace this with a callback? from ..dialog import ErrorDialog - + ErrorDialog(_('Active person has not been set'), _('You must select an active person for this ' 'tool to work properly.')) @@ -247,8 +247,8 @@ def gui_tool(dbstate, user, tool_class, options_class, translated_name, """ try: - tool_class(dbstate = dbstate, user = user, - options_class = options_class, name = name, + tool_class(dbstate = dbstate, user = user, + options_class = options_class, name = name, callback = callback) except WindowActiveError: pass @@ -278,7 +278,7 @@ def cli_tool(dbstate, name, category, tool_class, options_class, options_str_dic #------------------------------------------------------------------------- # -# Class handling options for plugins +# Class handling options for plugins # #------------------------------------------------------------------------- class ToolOptionHandler(OptionHandler): @@ -302,7 +302,7 @@ class ToolOptions(Options): """ Defines options and provides handling interface. - + This is a base Options class for the tools. All tools, options classes should derive from it. """ @@ -317,6 +317,6 @@ class ToolOptions(Options): self.options_dict = {} self.options_help = {} self.handler = None - + def load_previous_values(self): self.handler = ToolOptionHandler(self.name, self.options_dict, self.person_id) diff --git a/gramps/gui/pluginmanager.py b/gramps/gui/pluginmanager.py index bb609e984..ec6cf3c42 100644 --- a/gramps/gui/pluginmanager.py +++ b/gramps/gui/pluginmanager.py @@ -53,14 +53,14 @@ from gramps.gen.const import ICON # #------------------------------------------------------------------------- class GuiPluginManager(Callback): - """ PluginManager is a Singleton which manages plugins. - It is the gui implementation using a unique BasePluginmanager. - This class adds the possibility to hide plugins in the GUI via a config + """ PluginManager is a Singleton which manages plugins. + It is the gui implementation using a unique BasePluginmanager. + This class adds the possibility to hide plugins in the GUI via a config setting """ __instance = None __signals__ = { 'plugins-reloaded' : None } - + def get_instance(): """ Use this function to get the instance of the PluginManager """ if GuiPluginManager.__instance is None: @@ -68,13 +68,13 @@ class GuiPluginManager(Callback): GuiPluginManager.__instance = GuiPluginManager() return GuiPluginManager.__instance get_instance = staticmethod(get_instance) - + def __init__(self): """ This function should only be run once by get_instance() """ if GuiPluginManager.__instance is not 1: raise Exception("This class is a singleton. " "Use the get_instance() method") - + Callback.__init__(self) self.basemgr = BasePluginManager.get_instance() self.__hidden_plugins = set(config.get('plugin.hiddenplugins')) @@ -97,7 +97,7 @@ class GuiPluginManager(Callback): def reload_plugins(self): self.basemgr.reload_plugins() self.emit('plugins-reloaded') - + def __getattr__(self, name): return getattr(self.basemgr, name) @@ -105,7 +105,7 @@ class GuiPluginManager(Callback): #if hidden changed, stored data must be emptied as it could contain #something that now must be hidden self.empty_managed_plugins() - #objects that need to know if the plugins available changed, are + #objects that need to know if the plugins available changed, are #listening to this signal to update themselves. If a plugin becomes #(un)hidden, this should happen, so we emit. self.emit('plugins-reloaded') @@ -120,12 +120,12 @@ class GuiPluginManager(Callback): """ Hide plugin with given id. This will hide the plugin so queries do not return it anymore, and write this change to the config. Note that config will then emit a signal - """ + """ self.__hidden_plugins.add(id) config.set('plugin.hiddenplugins', list(self.__hidden_plugins)) config.save() self.__hidden_changed() - + def unhide_plugin(self, id): """ Unhide plugin with given id. This will unhide the plugin so queries return it again, and write this change to the config @@ -142,7 +142,7 @@ class GuiPluginManager(Callback): """ return [plg for plg in self.basemgr.get_reg_reports(gui) if plg.id not in self.__hidden_plugins] - + def get_reg_tools(self, gui=True): """ Return list of non hidden registered tools :Param gui: bool indicating if GUI reports or CLI reports must be @@ -156,13 +156,13 @@ class GuiPluginManager(Callback): """ return [plg for plg in self.basemgr.get_reg_views() if plg.id not in self.__hidden_plugins] - + def get_reg_quick_reports(self): """ Return list of non hidden registered quick reports """ return [plg for plg in self.basemgr.get_reg_quick_reports() if plg.id not in self.__hidden_plugins] - + def get_reg_mapservices(self): """ Return list of non hidden registered mapservices """ @@ -178,7 +178,7 @@ class GuiPluginManager(Callback): def get_reg_gramplets(self): """ Return list of non hidden reports registered as bookitem """ - return [plg for plg in self.basemgr.get_reg_gramplets() + return [plg for plg in self.basemgr.get_reg_gramplets() if plg.id not in self.__hidden_plugins] def get_reg_sidebars(self): @@ -192,13 +192,13 @@ class GuiPluginManager(Callback): """ return [plg for plg in self.basemgr.get_reg_importers() if plg.id not in self.__hidden_plugins] - + def get_reg_exporters(self): """ Return list of registered exporters """ return [plg for plg in self.basemgr.get_reg_exporters() if plg.id not in self.__hidden_plugins] - + def get_reg_docgens(self): """ Return list of registered docgen """ diff --git a/gramps/gui/selectors/baseselector.py b/gramps/gui/selectors/baseselector.py index 7646f32f3..b1d5067f4 100644 --- a/gramps/gui/selectors/baseselector.py +++ b/gramps/gui/selectors/baseselector.py @@ -46,7 +46,7 @@ class BaseSelector(ManagedWindow): """Base class for the selectors, showing a dialog from which to select one of the primary objects """ - + NONE = -1 TEXT = 0 MARKUP = 1 @@ -56,8 +56,8 @@ class BaseSelector(ManagedWindow): show_search_bar = True, default=None): """Set up the dialog with the dbstate and uistate, track of parent windows for ManagedWindow, initial filter for the model, skip with - set of handles to skip in the view, and search_bar to show the - SearchBar at the top or not. + set of handles to skip in the view, and search_bar to show the + SearchBar at the top or not. """ self.filter = (2, filter, False) @@ -74,9 +74,9 @@ class BaseSelector(ManagedWindow): self.db = dbstate.db self.tree = None self.model = None - + self.glade = Glade() - + window = self.glade.toplevel self.showall = self.glade.get_object('showall') title_label = self.glade.get_object('title') @@ -99,7 +99,7 @@ class BaseSelector(ManagedWindow): vbox.reorder_child(filter_box, 1) self.set_window(window,title_label,self.title) - + #set up sorting self.sort_col = 0 self.setupcols = True @@ -110,7 +110,7 @@ class BaseSelector(ManagedWindow): self.build_tree() self.selection = self.tree.get_selection() self.track_ref_for_deletion("selection") - + self._local_init() self._set_size() @@ -175,8 +175,8 @@ class BaseSelector(ManagedWindow): column.set_clickable(True) ##column.set_sort_column_id(ix) # model has its own sort implemented self.columns.append(column) - tree.append_column(column) - + tree.append_column(column) + def build_menu_names(self, obj): return (self.title, None) @@ -222,24 +222,24 @@ class BaseSelector(ManagedWindow): def get_model_class(self): assert False, "Must be defined in the subclass" - + def get_column_titles(self): """ Defines the columns to show in the selector. Must be defined in the subclasses. :returns: a list of tuples with four entries. The four entries should - be 0: column header string, 1: column width, - 2: TEXT, MARKUP or IMAGE, 3: column in the model that must be + be 0: column header string, 1: column width, + 2: TEXT, MARKUP or IMAGE, 3: column in the model that must be used. """ raise NotImplementedError def get_from_handle_func(self): assert False, "Must be defined in the subclass" - + def get_from_handle_func2(self): return None - + def set_show_search_bar(self, value): """make the search bar at the top shown """ @@ -250,7 +250,7 @@ class BaseSelector(ManagedWindow): self.search_bar.show() else : self.search_bar.hide() - + def column_order(self): """ returns a tuple indicating the column order of the model @@ -272,7 +272,7 @@ class BaseSelector(ManagedWindow): if pair[0] ] self.search_bar.setup_filter(cols) - + def build_tree(self): """ Builds the selection people see in the Selector @@ -280,7 +280,7 @@ class BaseSelector(ManagedWindow): if self.filter[1]: filter_info = self.filter else: - #search info for the + #search info for the if self.search_bar.get_value()[0] in self.exact_search(): filter_info = (0, self.search_bar.get_value(), True) else: @@ -297,7 +297,7 @@ class BaseSelector(ManagedWindow): sort_map=self.column_order(), skip=self.skip_list, search=filter_info) - + self.tree.set_model(self.model) #sorting arrow in column header (not on start, only on click) @@ -310,9 +310,9 @@ class BaseSelector(ManagedWindow): # set the search column to be the sorted column search_col = self.column_order()[self.sort_col][1] self.tree.set_search_column(search_col) - + self.setupcols = False - + def column_clicked(self, obj, data): if self.sort_col != data: self.sortorder = Gtk.SortType.ASCENDING @@ -331,7 +331,7 @@ class BaseSelector(ManagedWindow): path = self.model.on_get_path(handle) self.selection.select_path(path) self.tree.scroll_to_cell(path, None, 1, 0.5, 0) - + return True def show_toggle(self, obj): diff --git a/gramps/gui/selectors/selectcitation.py b/gramps/gui/selectors/selectcitation.py index 3a988343d..324ad6261 100644 --- a/gramps/gui/selectors/selectcitation.py +++ b/gramps/gui/selectors/selectcitation.py @@ -2,7 +2,7 @@ # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2003-2006 Donald N. Allingham -# 2009 Gary Burton +# 2009 Gary Burton # Copyright (C) 2011 Tim G L Lyons, Nick Hall # # This program is free software; you can redistribute it and/or modify @@ -56,7 +56,7 @@ class SelectCitation(BaseSelector): def get_window_title(self): return _("Select Source or Citation") - + def get_model_class(self): return CitationTreeModel @@ -69,6 +69,6 @@ class SelectCitation(BaseSelector): def get_from_handle_func(self): return self.db.get_source_from_handle - + def get_from_handle_func2(self): return self.db.get_citation_from_handle diff --git a/gramps/gui/selectors/selectevent.py b/gramps/gui/selectors/selectevent.py index 5f2c73dc9..044085752 100644 --- a/gramps/gui/selectors/selectevent.py +++ b/gramps/gui/selectors/selectevent.py @@ -51,7 +51,7 @@ class SelectEvent(BaseSelector): def get_window_title(self): return _("Select Event") - + def get_model_class(self): return EventModel diff --git a/gramps/gui/selectors/selectfamily.py b/gramps/gui/selectors/selectfamily.py index 73ff7458c..6ff4c7f41 100644 --- a/gramps/gui/selectors/selectfamily.py +++ b/gramps/gui/selectors/selectfamily.py @@ -51,7 +51,7 @@ class SelectFamily(BaseSelector): def get_window_title(self): return _("Select Family") - + def get_model_class(self): return FamilyModel diff --git a/gramps/gui/selectors/selectnote.py b/gramps/gui/selectors/selectnote.py index ec04446d8..9296ee29d 100644 --- a/gramps/gui/selectors/selectnote.py +++ b/gramps/gui/selectors/selectnote.py @@ -56,7 +56,7 @@ class SelectNote(BaseSelector): def get_window_title(self): return _("Select Note") - + def get_model_class(self): return NoteModel @@ -68,6 +68,6 @@ class SelectNote(BaseSelector): (_('Tags'), 100, BaseSelector.TEXT, 4), (_('Last Change'), 150, BaseSelector.TEXT, 5), ] - + def get_from_handle_func(self): return self.db.get_note_from_handle diff --git a/gramps/gui/selectors/selectobject.py b/gramps/gui/selectors/selectobject.py index b66b9b97e..aa94d833e 100644 --- a/gramps/gui/selectors/selectobject.py +++ b/gramps/gui/selectors/selectobject.py @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -# Written by Alex Roitman, +# Written by Alex Roitman, # largely based on the MediaView and SelectPerson by Don Allingham #------------------------------------------------------------------------- @@ -58,13 +58,13 @@ class SelectObject(BaseSelector): def get_window_title(self): return _("Select Media Object") - + def get_model_class(self): return MediaModel def get_from_handle_func(self): return self.db.get_object_from_handle - + def get_column_titles(self): return [ (_('Title'), 350, BaseSelector.TEXT, 0), diff --git a/gramps/gui/selectors/selectorexceptions.py b/gramps/gui/selectors/selectorexceptions.py index e1c42589d..9d5dfab02 100644 --- a/gramps/gui/selectors/selectorexceptions.py +++ b/gramps/gui/selectors/selectorexceptions.py @@ -19,9 +19,9 @@ # class SelectorException(Exception): - + def __init__(self, value): self.value = value - + def __str__(self): return repr(self.value) diff --git a/gramps/gui/selectors/selectperson.py b/gramps/gui/selectors/selectperson.py index f0d4efa34..c2fa3dfee 100644 --- a/gramps/gui/selectors/selectperson.py +++ b/gramps/gui/selectors/selectperson.py @@ -65,7 +65,7 @@ class SelectPerson(BaseSelector): def get_window_title(self): return _("Select Person") - + def get_model_class(self): return PersonTreeModel @@ -84,7 +84,7 @@ class SelectPerson(BaseSelector): def get_from_handle_func(self): return self.db.get_person_from_handle - + def exact_search(self): """ Returns a tuple indicating columns requiring an exact search diff --git a/gramps/gui/selectors/selectplace.py b/gramps/gui/selectors/selectplace.py index 7ea2cdf11..ec5f8f176 100644 --- a/gramps/gui/selectors/selectplace.py +++ b/gramps/gui/selectors/selectplace.py @@ -52,7 +52,7 @@ class SelectPlace(BaseSelector): def get_window_title(self): return _("Select Place") - + def get_model_class(self): return PlaceTreeModel diff --git a/gramps/gui/selectors/selectrepository.py b/gramps/gui/selectors/selectrepository.py index 249ee3f18..a3ce364a3 100644 --- a/gramps/gui/selectors/selectrepository.py +++ b/gramps/gui/selectors/selectrepository.py @@ -51,7 +51,7 @@ class SelectRepository(BaseSelector): def get_window_title(self): return _("Select Repository") - + def get_model_class(self): return RepositoryModel diff --git a/gramps/gui/selectors/selectsource.py b/gramps/gui/selectors/selectsource.py index cf3871a64..b695f2717 100644 --- a/gramps/gui/selectors/selectsource.py +++ b/gramps/gui/selectors/selectsource.py @@ -51,7 +51,7 @@ class SelectSource(BaseSelector): def get_window_title(self): return _("Select Source") - + def get_model_class(self): return SourceModel diff --git a/gramps/gui/spell.py b/gramps/gui/spell.py index 404eb96ea..ec8acfe25 100644 --- a/gramps/gui/spell.py +++ b/gramps/gui/spell.py @@ -86,13 +86,13 @@ class Spell(object): """Attach a gtkspell instance to the passed TextView instance. """ _spellcheck_options = {'off': _('Off')} - + if HAVE_GTKSPELL: _spellcheck_options['on'] = _('On') - + def __init__(self, textview): self.textview = textview - + if HAVE_GTKSPELL and config.get('behavior.spellcheck'): self.spellcheck = 'on' else: @@ -102,7 +102,7 @@ class Spell(object): self.__real_set_active_spellcheck(self.spellcheck) # Private - + def __real_set_active_spellcheck(self, spellcheck_code): """Set active spellcheck by its code.""" if self._active_spellcheck == 'off': @@ -157,7 +157,7 @@ class Spell(object): self._active_spellcheck = spellcheck_code # Public API - + def get_all_spellchecks(self): """Get the list of installed spellcheck names.""" return list(self._spellcheck_options.values()) @@ -168,7 +168,7 @@ class Spell(object): if name == spellcheck: self.__real_set_active_spellcheck(code) return - + def get_active_spellcheck(self): """Get the name of the active spellcheck.""" return self._spellcheck_options[self._active_spellcheck] diff --git a/gramps/gui/test/user_test.py b/gramps/gui/test/user_test.py index 908fa48ba..6d6794612 100644 --- a/gramps/gui/test/user_test.py +++ b/gramps/gui/test/user_test.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -33,7 +33,7 @@ try: from unittest.mock import Mock, patch MOCKING = True - + except: MOCKING = False print ("Mocking disabled", sys.exc_info()[0:2]) @@ -45,9 +45,9 @@ class TestUser_prompt(unittest.TestCase): @unittest.skipUnless(MOCKING, "Requires unittest.mock to run") def test_prompt_runs_QuestionDialog2(self): with patch('gramps.gui.user.QuestionDialog2') as MockQD: - self.user.prompt(TestUser.TITLE, TestUser.MSG, + self.user.prompt(TestUser.TITLE, TestUser.MSG, TestUser.ACCEPT, TestUser.REJECT, None) - MockQD.assert_called_once_with(TestUser.TITLE, TestUser.MSG, + MockQD.assert_called_once_with(TestUser.TITLE, TestUser.MSG, TestUser.ACCEPT, TestUser.REJECT, None) MockQD.return_value.run.assert_called_once_with() # TODO test that run's return is the one returned by prompt()... diff --git a/gramps/gui/tipofday.py b/gramps/gui/tipofday.py index e83106509..ac8f28593 100644 --- a/gramps/gui/tipofday.py +++ b/gramps/gui/tipofday.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -59,14 +59,14 @@ class TipOfDay(ManagedWindow): def __init__(self, uistate): ManagedWindow.__init__(self, uistate, [], self) - + xml = Glade() window = xml.toplevel - self.set_window(window, - xml.get_object("title"), - _("Tip of the Day"), + self.set_window(window, + xml.get_object("title"), + _("Tip of the Day"), _("Tip of the Day")) - + self.tip = xml.get_object("tip") self.use = xml.get_object('usetips') self.use.set_active(config.get('behavior.use-tips')) @@ -77,7 +77,7 @@ class TipOfDay(ManagedWindow): next.connect("clicked", self.next_tip_cb) close = xml.get_object('close') close.connect("clicked", self.close_cb) - + try: tparser = TipParser() except (IOError,ExpatError) as e: @@ -93,7 +93,7 @@ class TipOfDay(ManagedWindow): self.index = 0 self.next_tip_cb() - + window.show_all() def escape(self,text): @@ -106,7 +106,7 @@ class TipOfDay(ManagedWindow): tip_text = _(self.escape(self.tip_list[self.new_index[self.index]])) newtext = '' for line in tip_text.split('
'): - newtext += line + '\n\n' + newtext += line + '\n\n' self.tip.set_text(newtext[:-2]) self.tip.set_use_markup(True) self.index = (self.index + 1) % len(self.tip_list) @@ -114,7 +114,7 @@ class TipOfDay(ManagedWindow): def close_cb(self, dummy=None): config.set('behavior.use-tips', self.use.get_active()) self.close() - + def build_menu_names(self, obj): return (_("Tip of the Day"), None) @@ -152,7 +152,7 @@ class TipParser(object): Return the list of tips """ return self.mylist - + def setDocumentLocator(self, locator): """Set the XML document locator""" self.locator = locator diff --git a/gramps/gui/undohistory.py b/gramps/gui/undohistory.py index 29832e191..af2509ed2 100644 --- a/gramps/gui/undohistory.py +++ b/gramps/gui/undohistory.py @@ -57,7 +57,7 @@ class UndoHistory(ManagedWindow): steps available for undo/redo. Selecting a line in the list will revert/advance to the appropriate step in editing history. """ - + def __init__(self, dbstate, uistate): self.title = _("Undo History") @@ -77,16 +77,16 @@ class UndoHistory(ManagedWindow): Gtk.ResponseType.APPLY) self.close_button = window.add_button(_('_Close'), Gtk.ResponseType.CLOSE) - + self.set_window(window, None, self.title) self.window.set_size_request(400, 200) self.window.connect('response', self._response) scrolled_window = Gtk.ScrolledWindow() - scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, + scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.tree = Gtk.TreeView() - self.model = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING, + self.model = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) self.selection = self.tree.get_selection() @@ -111,7 +111,7 @@ class UndoHistory(ManagedWindow): self._build_model() self._update_ui() - + self.selection.connect('changed', self._selection_changed) self.show() @@ -146,7 +146,7 @@ class UndoHistory(ManagedWindow): the_iter = self.model.get_iter( (idx,) ) self.model.set(the_iter, 2, fg) self.model.set(the_iter, 3, bg) - + def _response(self, obj, response_id): if response_id == Gtk.ResponseType.CLOSE: self.close(obj) @@ -219,7 +219,7 @@ class UndoHistory(ManagedWindow): mod_text = _('Database opened') else: mod_text = _('History cleared') - time_text = time.ctime(self.undodb.undo_history_timestamp) + time_text = time.ctime(self.undodb.undo_history_timestamp) self.model.append(row=[time_text, mod_text, fg, bg]) # Add the undo and redo queues to the model @@ -255,7 +255,7 @@ def get_colors(obj, state): def bug_fix(column, renderer, model, iter_, data): """ Cell data function to set the column colors. - + There is a bug in pygobject which prevents us from setting a value to None using the TreeModel set_value method. Instead we set it to an empty string and convert it to None here. diff --git a/gramps/gui/user.py b/gramps/gui/user.py index 046329e3c..7358be5ee 100644 --- a/gramps/gui/user.py +++ b/gramps/gui/user.py @@ -36,7 +36,7 @@ import sys #------------------------------------------------------------------------- from gramps.gen import user from .utils import ProgressMeter -from .dialog import (WarningDialog, ErrorDialog, DBErrorDialog, +from .dialog import (WarningDialog, ErrorDialog, DBErrorDialog, InfoDialog, QuestionDialog2) #------------------------------------------------------------------------- # @@ -52,11 +52,11 @@ class User(user.User): user.User.__init__(self, callback, error) self._progress = None self.uistate = uistate - + def begin_progress(self, title, message, steps): """ Start showing a progress indicator to the user. - + :param title: the title of the progress meter :type title: str :param message: the message associated with the progress meter @@ -75,7 +75,7 @@ class User(user.User): self._progress.set_pass(message, steps, ProgressMeter.MODE_FRACTION) else: self._progress.set_pass(message, mode=ProgressMeter.MODE_ACTIVITY) - + def step_progress(self): """ Advance the progress meter. @@ -90,11 +90,11 @@ class User(user.User): if self._progress: self._progress.close() self._progress = None - + def prompt(self, title, message, accept_label, reject_label, parent=None): """ Prompt the user with a message to select an alternative. - + :param title: the title of the question, e.g.: "Undo history warning" :type title: str :param message: the message, e.g.: "Proceeding with the tool will erase @@ -112,11 +112,11 @@ class User(user.User): dialog = QuestionDialog2(title, message, accept_label, reject_label, parent) return dialog.run() - + def warn(self, title, warning=""): """ Warn the user. - + :param title: the title of the warning :type title: str :param warning: the warning @@ -124,11 +124,11 @@ class User(user.User): :returns: none """ WarningDialog(title, warning) - + def notify_error(self, title, error=""): """ Notify the user of an error. - + :param title: the title of the error :type title: str :param error: the error message @@ -143,7 +143,7 @@ class User(user.User): def notify_db_error(self, error): """ Notify the user of a DB error. - + :param error: the DB error message :type error: str :returns: none diff --git a/gramps/gui/utils.py b/gramps/gui/utils.py index 241812a4b..1c20f2207 100644 --- a/gramps/gui/utils.py +++ b/gramps/gui/utils.py @@ -315,7 +315,7 @@ class ProgressMeter(object): class SystemFonts(object): """ - Define fonts available to Gramps + Define fonts available to Gramps This is a workaround for bug which prevents the list_families method being called more than once. @@ -323,7 +323,7 @@ class SystemFonts(object): The bug is described here: https://bugzilla.gnome.org/show_bug.cgi?id=679654 This code generates a warning: - /usr/local/lib/python2.7/site-packages/gi/types.py:47: + /usr/local/lib/python2.7/site-packages/gi/types.py:47: Warning: g_value_get_object: assertion `G_VALUE_HOLDS_OBJECT (value)' failed To get a list of fonts, instantiate this class and call @@ -582,7 +582,7 @@ def edit_object(dbstate, uistate, reftype, ref): "To edit the citation, close the source " "editor and open an editor for the citation " "alone") - + from .dialog import WarningDialog WarningDialog(_("Cannot open new citation editor"), blocked_text) @@ -630,7 +630,7 @@ class AvailableUpdates(threading.Thread): if len(self.addon_update_list) > 0: GLib.idle_add(self.emit_update_available) -def model_to_text(model, cols=None, treeiter=None, indent="", +def model_to_text(model, cols=None, treeiter=None, indent="", level=None, sep=", "): """ Given a model, return the text from the rows as a string. @@ -656,20 +656,20 @@ def model_to_text(model, cols=None, treeiter=None, indent="", if model.iter_has_child(treeiter): childiter = model.iter_children(treeiter) if level is not None: - text += model_to_text(model, cols, childiter, indent + (" " * 4), + text += model_to_text(model, cols, childiter, indent + (" " * 4), level + 1, sep) else: - text += model_to_text(model, cols, childiter, indent + (" " * 4), + text += model_to_text(model, cols, childiter, indent + (" " * 4), sep=sep) treeiter = model.iter_next(treeiter) return text - + def text_to_clipboard(text): """ Put any text into the clipboard """ from gi.repository import Gdk from gi.repository import Gtk - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_CLIPBOARD) clipboard.set_text(text, -1) diff --git a/gramps/gui/utilscairo.py b/gramps/gui/utilscairo.py index dc9640ee5..30af20721 100644 --- a/gramps/gui/utilscairo.py +++ b/gramps/gui/utilscairo.py @@ -11,7 +11,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. diff --git a/gramps/gui/viewmanager.py b/gramps/gui/viewmanager.py index 16146abef..235947ad0 100644 --- a/gramps/gui/viewmanager.py +++ b/gramps/gui/viewmanager.py @@ -74,8 +74,8 @@ from .utils import AvailableUpdates from .pluginmanager import GuiPluginManager from gramps.gen.relationship import get_relationship_calculator from .displaystate import DisplayState, RecentDocsMenu -from gramps.gen.const import (HOME_DIR, ICON, URL_BUGTRACKER, URL_HOMEPAGE, - URL_MAILINGLIST, URL_MANUAL_PAGE, URL_WIKISTRING, +from gramps.gen.const import (HOME_DIR, ICON, URL_BUGTRACKER, URL_HOMEPAGE, + URL_MAILINGLIST, URL_MANUAL_PAGE, URL_WIKISTRING, WIKI_EXTRAPLUGINS, URL_BUGHOME) from gramps.gen.constfunc import is_quartz, conv_to_unicode from gramps.gen.config import config @@ -610,7 +610,7 @@ class ViewManager(CLIManager): def __gocat(self, action): """ - Callback that is called on ctrl+number press. It moves to the + Callback that is called on ctrl+number press. It moves to the requested category like __next_view/__prev_view. 0 is 10 """ cat = int(action.get_name()[-1]) @@ -625,7 +625,7 @@ class ViewManager(CLIManager): def __next_view(self, action): """ Callback that is called when the next category action is selected. - It selects the next category as the active category. If we reach the end, + It selects the next category as the active category. If we reach the end, we wrap around to the first. """ curpage = self.notebook.get_current_page() @@ -945,7 +945,7 @@ class ViewManager(CLIManager): from .views.pageview import DummyPage return DummyPage(pdata.name, pdata, self.dbstate, self.uistate, _("View failed to load. Check error output."), error) - + def __create_page(self, pdata, page_def): """ Create a new page and set it as the current page. @@ -1627,8 +1627,8 @@ def run_plugin(pdata, dbstate, uistate): tool.gui_tool(dbstate = dbstate, user = User(uistate = uistate), tool_class = getattr(mod, pdata.toolclass), options_class = getattr(mod, pdata.optionclass), - translated_name = pdata.name, - name = pdata.id, + translated_name = pdata.name, + name = pdata.id, category = pdata.category, callback = dbstate.db.request_rebuild) diff --git a/gramps/gui/views/__init__.py b/gramps/gui/views/__init__.py index 42df0aaa8..f52aa5d48 100644 --- a/gramps/gui/views/__init__.py +++ b/gramps/gui/views/__init__.py @@ -21,6 +21,6 @@ Package init for the views package. """ -# DO NOT IMPORT METHODS/CLASSES FROM src/gui/views HERE ! Only __all__ +# DO NOT IMPORT METHODS/CLASSES FROM src/gui/views HERE ! Only __all__ __all__ = [ "treemodels" ] diff --git a/gramps/gui/views/bookmarks.py b/gramps/gui/views/bookmarks.py index 33c94136e..7c846a049 100644 --- a/gramps/gui/views/bookmarks.py +++ b/gramps/gui/views/bookmarks.py @@ -76,7 +76,7 @@ DISABLED = -1 class Bookmarks : "Handle the bookmarks interface for Gramps." - + def __init__(self, dbstate, uistate, callback=None): """ Create the bookmark editor. @@ -115,7 +115,7 @@ class Bookmarks : def update_bookmarks(self): """ - Assign bookmarks + Assign bookmarks """ self.bookmarks = self.get_bookmarks() @@ -164,7 +164,7 @@ class Bookmarks : except AttributeError: pass text.write('') - + text.write(BTM) self.action_group.add_actions(actions) self.uistate.uimanager.insert_action_group(self.action_group, 1) @@ -214,7 +214,7 @@ class Bookmarks : self.top.vbox.pack_start(label, 0, 0, 5) box = Gtk.Box() self.top.vbox.pack_start(box, 1, 1, 5) - + name_titles = [(_('Name'), -1, 200), (_('ID'), -1, 50), ('', -1, 0)] self.namelist = Gtk.TreeView() self.namemodel = ListModel(self.namelist, name_titles) @@ -241,7 +241,7 @@ class Bookmarks : bbox.add(delete) box.pack_start(bbox, 0, 0, 5) self.top.show_all() - + def close(self, widget, event): """Stop the bookmark organizer""" self.top.response(Gtk.ResponseType.CLOSE) @@ -312,7 +312,7 @@ class ListBookmarks(Bookmarks): def __init__(self, dbstate, uistate, change_active): self.change_active = change_active Bookmarks.__init__(self, dbstate, uistate) - + def callback(self, handle): return make_callback(handle, self.do_callback) @@ -321,25 +321,25 @@ class ListBookmarks(Bookmarks): class PersonBookmarks(ListBookmarks) : "Handle the bookmarks interface for Gramps." - + def __init__(self, dbstate, uistate, change_active): ListBookmarks.__init__(self, dbstate, uistate, change_active) - + def make_label(self, handle): return navigation_label(self.dbstate.db, 'Person', handle) def connect_signals(self): self.dbstate.db.connect('person-delete', self.remove_handles) - + def get_bookmarks(self): return self.dbstate.db.get_bookmarks() - + class FamilyBookmarks(ListBookmarks) : "Handle the bookmarks interface for Gramps." - + def __init__(self, dbstate, uistate, change_active): ListBookmarks.__init__(self, dbstate, uistate, change_active) - + def make_label(self, handle): return navigation_label(self.dbstate.db, 'Family', handle) @@ -348,13 +348,13 @@ class FamilyBookmarks(ListBookmarks) : def get_bookmarks(self): return self.dbstate.db.get_family_bookmarks() - + class EventBookmarks(ListBookmarks) : "Handle the bookmarks interface for Gramps." - + def __init__(self, dbstate, uistate, change_active): ListBookmarks.__init__(self, dbstate, uistate, change_active) - + def make_label(self, handle): return navigation_label(self.dbstate.db, 'Event', handle) @@ -363,13 +363,13 @@ class EventBookmarks(ListBookmarks) : def get_bookmarks(self): return self.dbstate.db.get_event_bookmarks() - + class SourceBookmarks(ListBookmarks) : "Handle the bookmarks interface for Gramps." def __init__(self, dbstate, uistate, change_active): ListBookmarks.__init__(self, dbstate, uistate, change_active) - + def make_label(self, handle): return navigation_label(self.dbstate.db, 'Source', handle) @@ -378,13 +378,13 @@ class SourceBookmarks(ListBookmarks) : def get_bookmarks(self): return self.dbstate.db.get_source_bookmarks() - + class CitationBookmarks(ListBookmarks) : "Handle the bookmarks interface for Gramps." def __init__(self, dbstate, uistate, change_active): ListBookmarks.__init__(self, dbstate, uistate, change_active) - + def make_label(self, handle): return navigation_label(self.dbstate.db, 'Citation', handle) @@ -399,7 +399,7 @@ class CitationBookmarks(ListBookmarks) : # Probably trying to bookmark a source when the navigation type is # citation. This can occur when in the Citation Tree View and we # bookmark a source. - + # FIXME: See http://www.gramps-project.org/bugs/view.php?id=6352 a # more comprehensive solution is needed in the long term. See also # change_active in CitatinTreeView @@ -416,13 +416,13 @@ class CitationBookmarks(ListBookmarks) : def get_bookmarks(self): return self.dbstate.db.get_citation_bookmarks() - + class MediaBookmarks(ListBookmarks) : "Handle the bookmarks interface for Gramps." - + def __init__(self, dbstate, uistate, change_active): ListBookmarks.__init__(self, dbstate, uistate, change_active) - + def make_label(self, handle): return navigation_label(self.dbstate.db, 'Media', handle) @@ -431,13 +431,13 @@ class MediaBookmarks(ListBookmarks) : def get_bookmarks(self): return self.dbstate.db.get_media_bookmarks() - + class RepoBookmarks(ListBookmarks) : "Handle the bookmarks interface for Gramps." - + def __init__(self, dbstate, uistate, change_active): ListBookmarks.__init__(self, dbstate, uistate, change_active) - + def make_label(self, handle): return navigation_label(self.dbstate.db, 'Repository', handle) @@ -446,13 +446,13 @@ class RepoBookmarks(ListBookmarks) : def get_bookmarks(self): return self.dbstate.db.get_repo_bookmarks() - + class PlaceBookmarks(ListBookmarks) : "Handle the bookmarks interface for Gramps." - + def __init__(self, dbstate, uistate, change_active): ListBookmarks.__init__(self, dbstate, uistate, change_active) - + def make_label(self, handle): return navigation_label(self.dbstate.db, 'Place', handle) @@ -461,13 +461,13 @@ class PlaceBookmarks(ListBookmarks) : def get_bookmarks(self): return self.dbstate.db.get_place_bookmarks() - + class NoteBookmarks(ListBookmarks) : "Handle the bookmarks interface for Gramps." - + def __init__(self, dbstate, uistate, change_active): ListBookmarks.__init__(self, dbstate, uistate, change_active) - + def make_label(self, handle): return navigation_label(self.dbstate.db, 'Note', handle) @@ -476,7 +476,7 @@ class NoteBookmarks(ListBookmarks) : def get_bookmarks(self): return self.dbstate.db.get_note_bookmarks() - + def make_callback(handle, function): """ Build a unique call to the function with the associated handle. diff --git a/gramps/gui/views/listview.py b/gramps/gui/views/listview.py index 05f209d4f..aa59ccdba 100644 --- a/gramps/gui/views/listview.py +++ b/gramps/gui/views/listview.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -46,7 +46,7 @@ from gi.repository import Pango #---------------------------------------------------------------- # -# GRAMPS +# GRAMPS # #---------------------------------------------------------------- from .pageview import PageView @@ -102,11 +102,11 @@ class ListView(NavigationView): def __init__(self, title, pdata, dbstate, uistate, make_model, signal_map, bm_type, nav_group, multiple=False, filter_class=None): - NavigationView.__init__(self, title, pdata, dbstate, uistate, + NavigationView.__init__(self, title, pdata, dbstate, uistate, bm_type, nav_group) #default is listviews keep themself in sync with database self._dirty_on_change_inactive = False - + self.filter_class = filter_class self.pb_renderer = Gtk.CellRendererPixbuf() self.renderer = Gtk.CellRendererText() @@ -123,14 +123,14 @@ class ListView(NavigationView): self.connect_signals() def no_database(self): - ## TODO GTK3: This is never called!! Dbguielement disconnects + ## TODO GTK3: This is never called!! Dbguielement disconnects ## signals on database changed, so it cannot be called ## Undo part of Revision 20296 if all works good. self.list.set_model(None) self.model.destroy() self.model = None self.build_tree() - + #################################################################### # Build interface #################################################################### @@ -143,8 +143,8 @@ class ListView(NavigationView): self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.vbox.set_border_width(4) self.vbox.set_spacing(4) - - self.search_bar = SearchBar(self.dbstate, self.uistate, + + self.search_bar = SearchBar(self.dbstate, self.uistate, self.search_build_tree) filter_box = self.search_bar.build() @@ -155,19 +155,19 @@ class ListView(NavigationView): self.list.connect('button-press-event', self._button_press) self.list.connect('key-press-event', self._key_press) self.searchbox = InteractiveSearchBox(self.list) - + if self.drag_info(): self.list.connect('drag_data_get', self.drag_data_get) self.list.connect('drag_begin', self.drag_begin) if self.drag_dest_info(): self.list.connect('drag_data_received', self.drag_data_received) self.list.drag_dest_set(Gtk.DestDefaults.MOTION | - Gtk.DestDefaults.DROP, - [self.drag_dest_info().target()], + Gtk.DestDefaults.DROP, + [self.drag_dest_info().target()], Gdk.DragAction.MOVE | Gdk.DragAction.COPY) tglist = Gtk.TargetList.new([]) - tglist.add(self.drag_dest_info().atom_drag_type, + tglist.add(self.drag_dest_info().atom_drag_type, self.drag_dest_info().target_flags, self.drag_dest_info().app_id) self.list.drag_dest_set_target_list(tglist) @@ -197,11 +197,11 @@ class ListView(NavigationView): def define_actions(self): """ Required define_actions function for PageView. Builds the action - group information required. We extend beyond the normal here, + group information required. We extend beyond the normal here, since we want to have more than one action group for the PersonView. Most PageViews really won't care about this. """ - + NavigationView.define_actions(self) self.edit_action = ActionGroup(name=self.title + '/ChangeOrder') @@ -222,10 +222,10 @@ class ListView(NavigationView): accel="Return", tip=self.EDIT_MSG, callback=self.edit) - + def build_columns(self): list(map(self.list.remove_column, self.columns)) - + self.columns = [] index = 0 @@ -249,7 +249,7 @@ class ListView(NavigationView): image.set_tooltip_text(col_name) image.show() column.set_widget(image) - + if self.model and self.model.color_column() is not None: column.set_cell_data_func(self.renderer, self.foreground_color) @@ -259,7 +259,7 @@ class ListView(NavigationView): column.set_clickable(True) column.set_sizing(Gtk.TreeViewColumnSizing.FIXED) column.set_fixed_width(pair[2]) - + self.columns.append(column) self.list.append_column(column) index += 1 @@ -292,8 +292,8 @@ class ListView(NavigationView): """ NavigationView.set_active(self) self.uistate.viewmanager.tags.tag_enable() - self.uistate.show_filter_results(self.dbstate, - self.model.displayed(), + self.uistate.show_filter_results(self.dbstate, + self.model.displayed(), self.model.total()) def set_inactive(self): @@ -319,7 +319,7 @@ class ListView(NavigationView): if self.model: self.list.set_model(None) self.model.destroy() - self.model = self.make_model(self.dbstate.db, self.sort_col, + self.model = self.make_model(self.dbstate.db, self.sort_col, search=filter_info, sort_map=self.column_order()) else: @@ -328,7 +328,7 @@ class ListView(NavigationView): self.list.set_model(None) self.model.set_search(filter_info) self.model.rebuild_data() - + cput1 = time.clock() self.build_columns() cput2 = time.clock() @@ -339,17 +339,17 @@ class ListView(NavigationView): self.dirty = False cput4 = time.clock() - self.uistate.show_filter_results(self.dbstate, - self.model.displayed(), + self.uistate.show_filter_results(self.dbstate, + self.model.displayed(), self.model.total()) LOG.debug(self.__class__.__name__ + ' build_tree ' + str(time.clock() - cput0) + ' sec') - LOG.debug('parts ' + str(cput1-cput0) + ' , ' - + str(cput2-cput1) + ' , ' - + str(cput3-cput2) + ' , ' - + str(cput4-cput3) + ' , ' + LOG.debug('parts ' + str(cput1-cput0) + ' , ' + + str(cput2-cput1) + ' , ' + + str(cput3-cput2) + ' , ' + + str(cput4-cput3) + ' , ' + str(time.clock() - cput4)) - + else: self.dirty = True @@ -369,7 +369,7 @@ class ListView(NavigationView): def filter_editor(self, obj): try: - FilterEditor(self.FILTER_TYPE , CUSTOM_FILTERS, + FilterEditor(self.FILTER_TYPE , CUSTOM_FILTERS, self.dbstate, self.uistate) except WindowActiveError: return @@ -396,14 +396,14 @@ class ListView(NavigationView): """ Go to a given handle in the list. Required by the NavigationView interface. - + We have a bit of a problem due to the nature of how GTK works. - We have to unselect the previous path and select the new path. However, + We have to unselect the previous path and select the new path. However, these cause a row change, which calls the row_change callback, which can end up calling change_active_person, which can call goto_active_person, causing a bit of recusion. Confusing, huh? - Unfortunately, row_change has to be able to call change_active_person, + Unfortunately, row_change has to be able to call change_active_person, because this can occur from the interface in addition to programatically. To handle this, we set the self.inactive variable that we can check @@ -433,7 +433,7 @@ class ListView(NavigationView): self.list.scroll_to_cell(path, None, 1, 0.5, 0) else: self.selection.unselect_all() - self.uistate.push_message(self.dbstate, + self.uistate.push_message(self.dbstate, _("Active object not visible")) def add_bookmark(self, obj): @@ -445,12 +445,12 @@ class ListView(NavigationView): else: from ..dialog import WarningDialog WarningDialog( - _("Could Not Set a Bookmark"), + _("Could Not Set a Bookmark"), _("A bookmark could not be set because " "nothing was selected.")) #################################################################### - # + # #################################################################### def drag_info(self): @@ -473,11 +473,11 @@ class ListView(NavigationView): def drag_begin(self, widget, context): widget.drag_source_set_icon_name(self.get_stock()) - + def drag_data_get(self, widget, context, sel_data, info, time): selected_ids = self.selected_handles() - #Gtk.selection_add_target(widget, sel_data.get_selection(), + #Gtk.selection_add_target(widget, sel_data.get_selection(), # Gdk.atom_intern(self.drag_info().drag_type, False), # self.drag_info().app_id) @@ -485,9 +485,9 @@ class ListView(NavigationView): data = (self.drag_info().drag_type, id(self), selected_ids[0], 0) sel_data.set(self.drag_info().atom_drag_type, 8, pickle.dumps(data)) elif len(selected_ids) > 1: - data = (self.drag_list_info().drag_type, id(self), + data = (self.drag_list_info().drag_type, id(self), [(self.drag_list_info().drag_type, handle) - for handle in selected_ids], + for handle in selected_ids], 0) sel_data.set(self.drag_list_info().atom_drag_type, 8, pickle.dumps(data)) else: @@ -502,8 +502,8 @@ class ListView(NavigationView): """ #now we need to rebuild the model so it contains correct column info self.dirty = True - #make sure we sort on first column. We have no idea where the - # column that was sorted on before is situated now. + #make sure we sort on first column. We have no idea where the + # column that was sorted on before is situated now. self.sort_col = 0 self.sort_order = Gtk.SortType.ASCENDING self.setup_filter() @@ -511,7 +511,7 @@ class ListView(NavigationView): def column_order(self): """ - Column order is obtained from the config file of the listview. + Column order is obtained from the config file of the listview. A column order is a list of 3-tuples. The order in the list is the order the columns must appear in. For a column, the 3-tuple should be (enable, modelcol, sizecol), where @@ -543,7 +543,7 @@ class ListView(NavigationView): _("Delete All"), _("Confirm Each Delete")) prompt = not q.run() - + if not prompt: self.uistate.set_busy_cursor(True) @@ -556,7 +556,7 @@ class ListView(NavigationView): 'from all other items that reference it.') else: msg = _('Deleting item will remove it from the database.') - + msg += ' ' + data_recover_msg #descr = object.get_description() #if descr == "": @@ -570,7 +570,7 @@ class ListView(NavigationView): if not prompt: self.uistate.set_busy_cursor(False) - + def blist(self, store, path, iter_, sel_list): '''GtkTreeSelectionForeachFunc construct a list sel_list with all selected handles @@ -639,9 +639,9 @@ class ListView(NavigationView): self.model.reverse_order() self.list.set_model(self.model) else: - self.model = self.make_model(self.dbstate.db, self.sort_col, - self.sort_order, - search=filter_info, + self.model = self.make_model(self.dbstate.db, self.sort_col, + self.sort_order, + search=filter_info, sort_map=self.column_order()) self.list.set_model(self.model) @@ -654,9 +654,9 @@ class ListView(NavigationView): # set the search column to be the sorted column search_col = self.column_order()[data][1] self.list.set_search_column(search_col) - + self.uistate.set_busy_cursor(False) - + LOG.debug(' ' + self.__class__.__name__ + ' column_clicked ' + str(time.clock() - cput) + ' sec') @@ -703,8 +703,8 @@ class ListView(NavigationView): if len(selected_ids) == 1: if self.drag_info(): - self.list.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, - [], + self.list.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, + [], Gdk.DragAction.COPY) #TODO GTK3: wourkaround here for bug https://bugzilla.gnome.org/show_bug.cgi?id=680638 tglist = Gtk.TargetList.new([]) @@ -713,8 +713,8 @@ class ListView(NavigationView): self.list.drag_source_set_target_list(tglist) elif len(selected_ids) > 1: if self.drag_list_info(): - self.list.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, - [], + self.list.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, + [], Gdk.DragAction.COPY) #TODO GTK3: wourkaround here for bug https://bugzilla.gnome.org/show_bug.cgi?id=680638 tglist = Gtk.TargetList.new([]) @@ -735,8 +735,8 @@ class ListView(NavigationView): LOG.debug(' ' + self.__class__.__name__ + ' row_add ' + str(time.clock() - cput) + ' sec') if self.active: - self.uistate.show_filter_results(self.dbstate, - self.model.displayed(), + self.uistate.show_filter_results(self.dbstate, + self.model.displayed(), self.model.total()) else: self.dirty = True @@ -775,8 +775,8 @@ class ListView(NavigationView): LOG.debug(' ' + self.__class__.__name__ + ' row_delete ' + str(time.clock() - cput) + ' sec') if self.active: - self.uistate.show_filter_results(self.dbstate, - self.model.displayed(), + self.uistate.show_filter_results(self.dbstate, + self.model.displayed(), self.model.total()) else: self.dirty = True @@ -830,8 +830,8 @@ class ListView(NavigationView): get_widget('/Popup/QuickReport') if qr_menu and self.QR_CATEGORY > -1 : (ui, qr_actions) = create_quickreport_menu( - self.QR_CATEGORY, - self.dbstate, + self.QR_CATEGORY, + self.dbstate, self.uistate, self.first_selected()) self.__build_menu(qr_menu, qr_actions) @@ -841,7 +841,7 @@ class ListView(NavigationView): get_widget('/Popup/WebConnect') if web_menu: web_actions = create_web_connect_menu( - self.dbstate, + self.dbstate, self.uistate, self.navigation_type(), self.first_selected()) @@ -849,7 +849,7 @@ class ListView(NavigationView): menu.popup(None, None, None, None, event.button, event.time) return True - + return False def __build_menu(self, menu, actions): @@ -877,7 +877,7 @@ class ListView(NavigationView): else: # Tree return self._key_press_tree(obj, event) - + def _key_press_flat(self, obj, event): """ Called when a key is pressed on a flat listview @@ -967,8 +967,8 @@ class ListView(NavigationView): """ NavigationView.change_page(self) if self.model: - self.uistate.show_filter_results(self.dbstate, - self.model.displayed(), + self.uistate.show_filter_results(self.dbstate, + self.model.displayed(), self.model.total()) self.edit_action.set_visible(True) self.edit_action.set_sensitive(not self.dbstate.db.readonly) @@ -996,9 +996,9 @@ class ListView(NavigationView): #################################################################### def export(self, obj): chooser = Gtk.FileChooserDialog( - _("Export View as Spreadsheet"), - self.uistate.window, - Gtk.FileChooserAction.SAVE, + _("Export View as Spreadsheet"), + self.uistate.window, + Gtk.FileChooserAction.SAVE, (_('_Cancel'), Gtk.ResponseType.CANCEL, _('_Save'), Gtk.ResponseType.OK)) chooser.set_do_overwrite_confirmation(True) @@ -1031,8 +1031,8 @@ class ListView(NavigationView): def write_tabbed_file(self, name, type): """ - Write a tabbed file to the specified name. - + Write a tabbed file to the specified name. + The output file type is determined by the type variable. """ from gramps.gen.utils.docgen import CSVTab, ODSTab @@ -1041,10 +1041,10 @@ class ListView(NavigationView): column_names = [self.COLUMNS[i][0] for i in data_cols] if type == 0: - ofile = CSVTab(len(column_names)) + ofile = CSVTab(len(column_names)) else: ofile = ODSTab(len(column_names)) - + ofile.open(name) ofile.start_page() ofile.start_row() @@ -1072,10 +1072,10 @@ class ListView(NavigationView): iter_ = self.model.get_iter((0,)) if iter_: self.write_node(iter_, len(levels), [], ofile, data_cols) - + ofile.end_page() ofile.close() - + def write_node(self, iter_, depth, level, ofile, data_cols): while iter_: @@ -1102,7 +1102,7 @@ class ListView(NavigationView): We could implement this in the NavigationView """ raise NotImplementedError - + def edit(self, obj, data=None): """ Template function to allow the editing of the selected object @@ -1136,7 +1136,7 @@ class ListView(NavigationView): def open_all_nodes(self, obj): """ Method for Treeviews to open all groups - obj: for use of method in event callback + obj: for use of method in event callback """ self.uistate.status_text(_("Updating display...")) self.uistate.set_busy_cursor(True) @@ -1160,14 +1160,14 @@ class ListView(NavigationView): """ self.uistate.status_text(_("Updating display...")) self.uistate.set_busy_cursor(True) - + store, selected = self.selection.get_selected_rows() for path in selected: self.list.expand_row(path, False) self.uistate.set_busy_cursor(False) self.uistate.modify_statusbar(self.dbstate) - + def close_branch(self, obj): """ Collapse the selected branches. @@ -1180,7 +1180,7 @@ class ListView(NavigationView): def can_configure(self): """ - See :class:`~gui.views.pageview.PageView + See :class:`~gui.views.pageview.PageView :return: bool """ return True @@ -1198,9 +1198,9 @@ class ListView(NavigationView): def _get_configure_page_funcs(self): """ - Return a list of functions that create gtk elements to use in the + Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog - + :return: list of functions """ def columnpage(configdialog): diff --git a/gramps/gui/views/navigationview.py b/gramps/gui/views/navigationview.py index 4a5c0eda5..639eae2a7 100644 --- a/gramps/gui/views/navigationview.py +++ b/gramps/gui/views/navigationview.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -42,7 +42,7 @@ from gi.repository import Gtk #---------------------------------------------------------------- # -# GRAMPS +# GRAMPS # #---------------------------------------------------------------- from .pageview import PageView @@ -79,7 +79,7 @@ class NavigationView(PageView): navigation functionalilty. Views that need bookmarks and forward/backward should derive from this class. """ - + def __init__(self, title, pdata, state, uistate, bm_type, nav_group): PageView.__init__(self, title, pdata, state, uistate) self.bookmarks = bm_type(self.dbstate, self.uistate, self.change_active) @@ -95,11 +95,11 @@ class NavigationView(PageView): self.uistate.register(state, self.navigation_type(), self.nav_group) - + def navigation_type(self): """ Indictates the navigation type. Navigation type can be the string - name of any of the primary Objects. A History object will be + name of any of the primary Objects. A History object will be created for it, see DisplayState.History """ return None @@ -111,26 +111,26 @@ class NavigationView(PageView): PageView.define_actions(self) self.bookmark_actions() self.navigation_actions() - + def disable_action_group(self): """ - Normally, this would not be overridden from the base class. However, + Normally, this would not be overridden from the base class. However, in this case, we have additional action groups that need to be handled correctly. """ PageView.disable_action_group(self) - + self.fwd_action.set_visible(False) self.back_action.set_visible(False) def enable_action_group(self, obj): """ - Normally, this would not be overridden from the base class. However, + Normally, this would not be overridden from the base class. However, in this case, we have additional action groups that need to be handled correctly. """ PageView.enable_action_group(self, obj) - + self.fwd_action.set_visible(True) self.back_action.set_visible(True) hobj = self.get_history() @@ -153,12 +153,12 @@ class NavigationView(PageView): """ PageView.set_active(self) self.bookmarks.display() - + hobj = self.get_history() self.active_signal = hobj.connect('active-changed', self.goto_active) self.mru_signal = hobj.connect('mru-changed', self.update_mru_menu) self.update_mru_menu(hobj.mru) - + self.goto_active(None) def set_inactive(self): @@ -178,7 +178,7 @@ class NavigationView(PageView): Return the navigation group. """ return self.nav_group - + def get_history(self): """ Return the history object. @@ -195,7 +195,7 @@ class NavigationView(PageView): self.navigation_group()) if active_handle: self.goto_handle(active_handle) - + hobj = self.get_history() self.fwd_action.set_sensitive(not hobj.at_end()) self.back_action.set_sensitive(not hobj.at_front()) @@ -207,14 +207,14 @@ class NavigationView(PageView): hobj = self.uistate.get_history(self.navigation_type(), self.navigation_group()) return hobj.present() - + def change_active(self, handle): """ Changes the active object. """ hobj = self.get_history() if handle and not hobj.lock and not (handle == hobj.present()): - hobj.push(handle) + hobj.push(handle) def goto_handle(self, handle): """ @@ -227,7 +227,7 @@ class NavigationView(PageView): """ Return the active person's handle in a list. Used for compatibility with those list views that can return multiply - selected items. + selected items. """ active_handle = self.uistate.get_active(self.navigation_type(), self.navigation_group()) @@ -247,12 +247,12 @@ class NavigationView(PageView): if active_person: self.bookmarks.add(active_handle) name = name_displayer.display(active_person) - self.uistate.push_message(self.dbstate, + self.uistate.push_message(self.dbstate, _("%s has been bookmarked") % name) else: from ..dialog import WarningDialog WarningDialog( - _("Could Not Set a Bookmark"), + _("Could Not Set a Bookmark"), _("A bookmark could not be set because " "no one was selected.")) @@ -268,12 +268,12 @@ class NavigationView(PageView): """ self.book_action = ActionGroup(name=self.title + '/Bookmark') self.book_action.add_actions([ - ('AddBook', 'gramps-bookmark-new', _('_Add Bookmark'), - 'd', None, self.add_bookmark), - ('EditBook', 'gramps-bookmark-edit', - _("%(title)s...") % {'title': _("Organize Bookmarks")}, - 'D', None, - self.edit_bookmarks), + ('AddBook', 'gramps-bookmark-new', _('_Add Bookmark'), + 'd', None, self.add_bookmark), + ('EditBook', 'gramps-bookmark-edit', + _("%(title)s...") % {'title': _("Organize Bookmarks")}, + 'D', None, + self.edit_bookmarks), ]) self._add_action_group(self.book_action) @@ -332,11 +332,11 @@ class NavigationView(PageView): self.change_active(defperson.get_handle()) else: from ..dialog import WarningDialog - WarningDialog(_("No Home Person"), + WarningDialog(_("No Home Person"), _("You need to set a 'default person' to go to. " "Select the People View, select the person you want as " "'Home Person', then confirm your choice " - "via the menu Edit ->Set Home Person."), + "via the menu Edit ->Set Home Person."), parent=self.uistate.window) def jump(self): @@ -345,7 +345,7 @@ class NavigationView(PageView): """ dialog = Gtk.Dialog(_('Jump to by Gramps ID')) dialog.set_border_width(12) - label = Gtk.Label(label='%s' % + label = Gtk.Label(label='%s' % _('Jump to by Gramps ID')) label.set_use_markup(True) dialog.vbox.add(label) @@ -361,7 +361,7 @@ class NavigationView(PageView): _('_Jump to'), Gtk.ResponseType.OK) dialog.set_default_response(Gtk.ResponseType.OK) dialog.vbox.show_all() - + if dialog.run() == Gtk.ResponseType.OK: gid = text.get_text() handle = self.get_handle_from_gramps_id(gid) @@ -369,7 +369,7 @@ class NavigationView(PageView): self.change_active(handle) else: self.uistate.push_message( - self.dbstate, + self.dbstate, _("Error: %s is not a valid Gramps ID") % gid) dialog.destroy() @@ -405,11 +405,11 @@ class NavigationView(PageView): self.back_action.set_sensitive(not hobj.at_front()) self.fwd_action.set_sensitive(True) hobj.lock = False - + #################################################################### # MRU functions #################################################################### - + def mru_disable(self): """ Remove the UI and action groups for the MRU list. @@ -436,11 +436,11 @@ class NavigationView(PageView): nav_type = self.navigation_type() hobj = self.get_history() menu_len = min(len(items) - 1, MRU_SIZE) - + entry = '' data = [entry % (nav_type, index) for index in range(0, menu_len)] self.mru_ui = "".join(MRU_TOP) + "".join(data) + "".join(MRU_BTM) - + mitems = items[-MRU_SIZE - 1:-1] # Ignore current handle mitems.reverse() data = [] @@ -449,7 +449,7 @@ class NavigationView(PageView): data.append(('%s%02d'%(nav_type, index), None, name, "%s%d" % (mod_key(), index), None, make_callback(hobj.push, handle))) - + self.mru_action = ActionGroup(name=self.title + '/MRU') self.mru_action.add_actions(data) self.mru_enable() @@ -463,7 +463,7 @@ class NavigationView(PageView): We could implement this here based on navigation_type() """ raise NotImplementedError - + def edit(self, obj): """ Template function to allow the editing of the selected object @@ -501,14 +501,14 @@ class NavigationView(PageView): the base class. Returns a gtk container widget. """ raise NotImplementedError - + def key_press_handler(self, widget, event): """ Handle the control+c (copy) and control+v (paste), or pass it on. """ if self.active: if event.type == Gdk.EventType.KEY_PRESS: - if (event.keyval == Gdk.KEY_c and + if (event.keyval == Gdk.KEY_c and (event.get_state() & Gdk.ModifierType.CONTROL_MASK)): self.call_copy() return True diff --git a/gramps/gui/views/pageview.py b/gramps/gui/views/pageview.py index 15dd311b6..ec675a2d4 100644 --- a/gramps/gui/views/pageview.py +++ b/gramps/gui/views/pageview.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -42,7 +42,7 @@ _ = glocale.translation.gettext #---------------------------------------------------------------- # -# GRAMPS +# GRAMPS # #---------------------------------------------------------------- from gramps.gen.errors import WindowActiveError @@ -59,10 +59,10 @@ from ..actiongroup import ActionGroup #------------------------------------------------------------------------------ class PageView(DbGUIElement): """ - The PageView class is the base class for all Data Views in GRAMPS. All + The PageView class is the base class for all Data Views in GRAMPS. All Views should derive from this class. The ViewManager understands the public interface of this class - + The following attributes are available ..attribute:: active is the view active at the moment (visible in Gramps as the main view) @@ -70,11 +70,11 @@ class PageView(DbGUIElement): bool, is the view current with the database or not. A dirty view triggers a rebuild when it becomes active ..attribute:: _dirty_on_change_inactive - read/write bool by inheriting classes. + read/write bool by inheriting classes. Views can behave two ways to signals: - 1. if the view is inactive, set it dirty, and rebuild the view when + 1. if the view is inactive, set it dirty, and rebuild the view when it becomes active. In this case, this method returns True - 2. if the view is inactive, try to stay in sync with database. Only + 2. if the view is inactive, try to stay in sync with database. Only rebuild or other large changes make view dirty ..attribute:: title title of the view @@ -115,7 +115,7 @@ class PageView(DbGUIElement): self.active = False self._dirty_on_change_inactive = True self.func_list = {} - + if isinstance(self.pdata.category, tuple): self.category, self.translated_category = self.pdata.category else: @@ -125,11 +125,11 @@ class PageView(DbGUIElement): self.dbstate.connect('no-database', self.disable_action_group) self.dbstate.connect('database-changed', self.enable_action_group) self.uistate.window.connect("key-press-event", self.key_press_handler) - + self.model = None self.selection = None self.handle_col = 0 - + self._config = None self.init_config() @@ -202,7 +202,7 @@ class PageView(DbGUIElement): Returns a 2-tuple. The first element is a tuple of sidebar gramplets and the second element is a tuple of bottombar gramplets. - Views should override this method to define default gramplets. + Views should override this method to define default gramplets. """ return ((), ()) @@ -262,7 +262,7 @@ class PageView(DbGUIElement): handled = True return handled - def call_paste(self): + def call_paste(self): """ This code is called on Control+V in a navigation view. If the copy can be handled, it returns true, otherwise false. @@ -290,7 +290,7 @@ class PageView(DbGUIElement): Called after a page is created. """ pass - + def set_active(self): """ Called with the PageView is set as active. If the page is "dirty", @@ -303,7 +303,7 @@ class PageView(DbGUIElement): self.uistate.set_busy_cursor(True) self.build_tree() self.uistate.set_busy_cursor(False) - + def set_inactive(self): """ Marks page as being inactive (not currently displayed) @@ -318,7 +318,7 @@ class PageView(DbGUIElement): class. """ raise NotImplementedError - + def ui_definition(self): """ returns the XML UI definition for the UIManager @@ -348,7 +348,7 @@ class PageView(DbGUIElement): def get_stock(self): """ - Return image associated with the view category, which is used for the + Return image associated with the view category, which is used for the icon for the button. """ return 'image-missing' @@ -399,20 +399,20 @@ class PageView(DbGUIElement): def define_actions(self): """ Defines the UIManager actions. Called by the ViewManager to set up the - View. The user typically defines self.action_list and - self.action_toggle_list in this function. + View. The user typically defines self.action_list and + self.action_toggle_list in this function. """ - self._add_toggle_action('Sidebar', None, _('_Sidebar'), + self._add_toggle_action('Sidebar', None, _('_Sidebar'), "R", None, self.__sidebar_toggled, self.sidebar.get_property('visible')) - self._add_toggle_action('Bottombar', None, _('_Bottombar'), + self._add_toggle_action('Bottombar', None, _('_Bottombar'), "B", None, self.__bottombar_toggled, self.bottombar.get_property('visible')) def __build_action_group(self): """ Create an UIManager ActionGroup from the values in self.action_list - and self.action_toggle_list. The user should define these in + and self.action_toggle_list. The user should define these in self.define_actions """ self.action_group = ActionGroup(name=self.title) @@ -424,7 +424,7 @@ class PageView(DbGUIElement): def _add_action(self, name, icon_name, label, accel=None, tip=None, callback=None): """ - Add an action to the action list for the current view. + Add an action to the action list for the current view. """ self.action_list.append((name, icon_name, label, accel, tip, callback)) @@ -432,15 +432,15 @@ class PageView(DbGUIElement): def _add_toggle_action(self, name, icon_name, label, accel=None, tip=None, callback=None, value=False): """ - Add a toggle action to the action list for the current view. + Add a toggle action to the action list for the current view. """ self.action_toggle_list.append((name, icon_name, label, accel, tip, callback, value)) - - def _add_toolmenu_action(self, name, label, tooltip, callback, + + def _add_toolmenu_action(self, name, label, tooltip, callback, arrowtooltip): """ - Add a menu action to the action list for the current view. + Add a menu action to the action list for the current view. """ self.action_toolmenu_list.append((name, label, tooltip, callback, arrowtooltip)) @@ -448,13 +448,13 @@ class PageView(DbGUIElement): def get_actions(self): """ Return the actions that should be used for the view. This includes the - standard action group (which handles the main toolbar), along with + standard action group (which handles the main toolbar), along with additional action groups. - If the action group is not defined, we build it the first time. This + If the action group is not defined, we build it the first time. This allows us to delay the intialization until it is really needed. - The ViewManager uses this function to extract the actions to install + The ViewManager uses this function to extract the actions to install into the UIManager. """ if not self.action_group: @@ -463,7 +463,7 @@ class PageView(DbGUIElement): def _add_action_group(self, group): """ - Allows additional action groups to be added to the view. + Allows additional action groups to be added to the view. """ self.additional_action_groups.append(group) @@ -496,7 +496,7 @@ class PageView(DbGUIElement): Template function to allow the adding of a new object """ raise NotImplementedError - + def _key_press(self, obj, event): """ Define the action for a key press event @@ -518,21 +518,21 @@ class PageView(DbGUIElement): def init_config(self): """ - If you need a view with a config, then call this method in the - build_widget or __init__ method. It will set up a config file for the - view, and use CONFIGSETTINGS to set the config defaults. + If you need a view with a config, then call this method in the + build_widget or __init__ method. It will set up a config file for the + view, and use CONFIGSETTINGS to set the config defaults. The config is later accessbile via self._config - So you can do + So you can do self._config.get("section.variable1") self._config.set("section.variable1", value) self._config.save() - - CONFIGSETTINGS should be a list with tuples like + + CONFIGSETTINGS should be a list with tuples like ("section.variable1", value) """ if self._config: return - self._config = config.register_manager(self.ident, + self._config = config.register_manager(self.ident, use_config_path=True) for section, value in self.CONFIGSETTINGS: self._config.register(section, value) @@ -564,9 +564,9 @@ class PageView(DbGUIElement): def _get_configure_page_funcs(self): """ - Return a list of functions that create gtk elements to use in the + Return a list of functions that create gtk elements to use in the notebook pages of the Configure view - + :return: list of functions """ raise NotImplementedError @@ -576,7 +576,7 @@ class PageView(DbGUIElement): Open the configure dialog for the view. """ title = _("Configure %(cat)s - %(view)s") % \ - {'cat': self.get_translated_category(), + {'cat': self.get_translated_category(), 'view': self.get_title()} if self.can_configure(): @@ -589,10 +589,10 @@ class PageView(DbGUIElement): config_funcs += self.bottombar.get_config_funcs() try: - ViewConfigureDialog(self.uistate, self.dbstate, + ViewConfigureDialog(self.uistate, self.dbstate, config_funcs, self, self._config, dialogtitle=title, - ident=_("%(cat)s - %(view)s") % + ident=_("%(cat)s - %(view)s") % {'cat': self.get_translated_category(), 'view': self.get_title()}) except WindowActiveError: @@ -609,7 +609,7 @@ class ViewConfigureDialog(ConfigureDialog): ConfigureDialog.__init__(self, uistate, dbstate, configure_page_funcs, configobj, configmanager, dialogtitle=dialogtitle, on_close=on_close) - + def build_menu_names(self, obj): return (_('Configure %s View') % self.ident, None) @@ -621,7 +621,7 @@ class DummyPage(PageView): self.msg = msg1 self.msg2 = msg2 PageView.__init__(self, title, pdata, dbstate, uistate) - + def build_widget(self): box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=1) #top widget at the top diff --git a/gramps/gui/views/tags.py b/gramps/gui/views/tags.py index 1148ea641..1e6575fe3 100644 --- a/gramps/gui/views/tags.py +++ b/gramps/gui/views/tags.py @@ -214,7 +214,7 @@ class Tags(DbGUIElement): tag_menu += '' % handle actions.append(('TAG_%s' % handle, None, tag_name, None, None, make_callback(self.tag_selected_rows, handle))) - + self.tag_ui = TAG_1 + tag_menu + TAG_2 + tag_menu + TAG_3 actions.append(('Tag', 'gramps-tag', _('Tag'), None, None, None)) @@ -224,10 +224,10 @@ class Tags(DbGUIElement): self.cb_organize_tags)) actions.append(('TagButton', 'gramps-tag', _('Tag'), None, _('Tag selected rows'), self.cb_tag_button)) - + self.tag_action = ActionGroup(name='Tag') self.tag_action.add_actions(actions) - + def cb_tag_button(self, action): """ Display the popup menu when the toolbar button is clicked. @@ -235,7 +235,7 @@ class Tags(DbGUIElement): menu = self.uistate.uimanager.get_widget('/TagPopup') button = self.uistate.uimanager.get_widget('/ToolBar/TagTool/TagButton') menu.popup(None, None, cb_menu_position, button, 0, 0) - + def cb_organize_tags(self, action): """ Display the Organize Tags dialog. @@ -263,7 +263,7 @@ class Tags(DbGUIElement): selected = view.selected_handles() # Make the dialog modal so that the user can't start another # database transaction while the one setting tags is still running. - pmon = progressdlg.ProgressMonitor(progressdlg.GtkProgressDialog, + pmon = progressdlg.ProgressMonitor(progressdlg.GtkProgressDialog, ("", self.uistate.window, Gtk.DialogFlags.MODAL), popup_time=2) status = progressdlg.LongOpStatus(msg=_("Adding Tags"), total_steps=len(selected), @@ -293,7 +293,7 @@ def cb_menu_position(*args): ret_val, x_pos, y_pos = button.get_window().get_origin() x_pos += button.get_allocation().x y_pos += button.get_allocation().y + button.get_allocation().height - + return (x_pos, y_pos, False) def make_callback(func, tag_handle): @@ -372,7 +372,7 @@ class OrganizeTagsDialog(object): for row in sorted(tags): self.namemodel.add(row) - + def _create_dialog(self): """ Create a dialog box to organize tags. @@ -390,7 +390,7 @@ class OrganizeTagsDialog(object): top.vbox.pack_start(label, 0, 0, 5) box = Gtk.Box() top.vbox.pack_start(box, 1, 1, 5) - + name_titles = [('', NOSORT, 20, INTEGER), # Priority ('', NOSORT, 100), # Handle (_('Name'), NOSORT, 200), @@ -466,10 +466,10 @@ class OrganizeTagsDialog(object): tag = self.db.get_tag_from_handle(store.get_value(iter_, 1)) edit_dialog = EditTag(self.db, top, tag) edit_dialog.run() - + store.set_value(iter_, 2, tag.get_name()) store.set_value(iter_, 3, tag.get_color()) - + def cb_remove_clicked(self, button, top): """ Remove the selected tag. @@ -479,7 +479,7 @@ class OrganizeTagsDialog(object): return tag_handle = store.get_value(iter_, 1) tag_name = store.get_value(iter_, 2) - + yes_no = QuestionDialog2( _("Remove tag '%s'?") % tag_name, _("The tag definition will be removed. " @@ -511,7 +511,7 @@ class OrganizeTagsDialog(object): links = [link for link in self.db.find_backlink_handles(tag_handle)] # Make the dialog modal so that the user can't start another # database transaction while the one removing tags is still running. - pmon = progressdlg.ProgressMonitor(progressdlg.GtkProgressDialog, + pmon = progressdlg.ProgressMonitor(progressdlg.GtkProgressDialog, ("", self.parent_window, Gtk.DialogFlags.MODAL), popup_time=2) status = progressdlg.LongOpStatus(msg=_("Removing Tags"), total_steps=len(links), @@ -615,7 +615,7 @@ class EditTag(object): hbox.pack_start(label, False, False, 5) hbox.pack_start(self.entry, True, True, 5) hbox.pack_start(self.color, False, False, 5) - + top.add_button(_('_OK'), Gtk.ResponseType.OK) top.add_button(_('_Cancel'), Gtk.ResponseType.CANCEL) top.show_all() diff --git a/gramps/gui/views/treemodels/basemodel.py b/gramps/gui/views/treemodels/basemodel.py index 598178206..01d27ca11 100644 --- a/gramps/gui/views/treemodels/basemodel.py +++ b/gramps/gui/views/treemodels/basemodel.py @@ -46,7 +46,7 @@ class BaseModel(object): def clear_cache(self, handle=None): """ - Clear the LRU cache. Always clear lru_path, because paths may have + Clear the LRU cache. Always clear lru_path, because paths may have changed. """ if handle: @@ -77,7 +77,7 @@ class BaseModel(object): if handle not in self.lru_data: self.lru_data[handle] = {} self.lru_data[handle][col] = data - + ## Cached Path's for TreeView: def get_cached_path(self, handle): """ diff --git a/gramps/gui/views/treemodels/citationbasemodel.py b/gramps/gui/views/treemodels/citationbasemodel.py index 372f7347b..59bc29493 100644 --- a/gramps/gui/views/treemodels/citationbasemodel.py +++ b/gramps/gui/views/treemodels/citationbasemodel.py @@ -106,8 +106,8 @@ class CitationBaseModel(object): return INVALID_DATE_FORMAT % retval else: return retval - return '' - + return '' + def citation_id(self, data): return str(data[COLUMN_ID]) @@ -151,13 +151,13 @@ class CitationBaseModel(object): def citation_change(self, data): return format_time(data[COLUMN_CHANGE]) - + def citation_sort_change(self, data): return "%012x" % data[COLUMN_CHANGE] def citation_source(self, data): return data[COLUMN_SOURCE] - + def citation_src_title(self, data): source_handle = data[COLUMN_SOURCE] cached, value = self.get_cached_value(source_handle, "SRC_TITLE") diff --git a/gramps/gui/views/treemodels/citationtreemodel.py b/gramps/gui/views/treemodels/citationtreemodel.py index bb0862539..7d623736e 100644 --- a/gramps/gui/views/treemodels/citationtreemodel.py +++ b/gramps/gui/views/treemodels/citationtreemodel.py @@ -71,7 +71,7 @@ class CitationTreeModel(CitationBaseModel, TreeBaseModel): self.number_items = self.db.get_number_of_sources self.map = self.db.get_raw_source_data self.gen_cursor = self.db.get_source_cursor - # The items here must correspond, in order, with data in + # The items here must correspond, in order, with data in # CitationTreeView, and with the items in the secondary fmap, fmap2 self.fmap = [ self.source_src_title, # COL_TITLE_PAGE (both Source & Citation) @@ -99,7 +99,7 @@ class CitationTreeModel(CitationBaseModel, TreeBaseModel): self.source_src_pinfo, self.source_src_tag_color ] - + TreeBaseModel.__init__(self, self.db, scol=scol, order=order, search=search, skip=skip, sort_map=sort_map, nrgroups=1, @@ -199,7 +199,7 @@ class CitationTreeModel(CitationBaseModel, TreeBaseModel): source_sort_key = self.sort_func(self.map(data[5])) # parent child sortkey handle self.add_node(None, data[5], source_sort_key, data[5]) - + # parent child sortkey handle self.add_node(data[5], handle, sort_key, handle, secondary=True) @@ -208,7 +208,7 @@ class CitationTreeModel(CitationBaseModel, TreeBaseModel): def column_header(self, node): """ - Return a column heading. This is called for nodes with no associated + Return a column heading. This is called for nodes with no associated Gramps handle. """ return node.name diff --git a/gramps/gui/views/treemodels/eventmodel.py b/gramps/gui/views/treemodels/eventmodel.py index b3597b274..2e1f6e344 100644 --- a/gramps/gui/views/treemodels/eventmodel.py +++ b/gramps/gui/views/treemodels/eventmodel.py @@ -133,7 +133,7 @@ class EventModel(FlatBaseModel): value = get_participant_from_event(self.db, data[COLUMN_HANDLE]) self.set_cached_value(handle, "PARTICIPANT", value) return value - + def column_place(self,data): if data[COLUMN_PLACE]: cached, value = self.get_cached_value(data[0], "PLACE") @@ -174,7 +174,7 @@ class EventModel(FlatBaseModel): return INVALID_DATE_FORMAT % retval else: return retval - + return '' def column_private(self, data): @@ -183,7 +183,7 @@ class EventModel(FlatBaseModel): else: # There is a problem returning None here. return '' - + def sort_change(self,data): return "%012x" % data[COLUMN_CHANGE] @@ -200,7 +200,7 @@ class EventModel(FlatBaseModel): value = self.db.get_tag_from_handle(tag_handle).get_name() self.set_cached_value(tag_handle, "TAG_NAME", value) return value - + def column_tag_color(self, data): """ Return the tag color. diff --git a/gramps/gui/views/treemodels/familymodel.py b/gramps/gui/views/treemodels/familymodel.py index 6d8a24e06..d3e22ed78 100644 --- a/gramps/gui/views/treemodels/familymodel.py +++ b/gramps/gui/views/treemodels/familymodel.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -56,30 +56,30 @@ invalid_date_format = config.get('preferences.invalid-date-format') #------------------------------------------------------------------------- class FamilyModel(FlatBaseModel): - def __init__(self, db, scol=0, order=Gtk.SortType.ASCENDING, search=None, + def __init__(self, db, scol=0, order=Gtk.SortType.ASCENDING, search=None, skip=set(), sort_map=None): self.gen_cursor = db.get_family_cursor self.map = db.get_raw_family_data self.fmap = [ - self.column_id, - self.column_father, - self.column_mother, - self.column_type, - self.column_marriage, + self.column_id, + self.column_father, + self.column_mother, + self.column_type, + self.column_marriage, self.column_private, self.column_tags, - self.column_change, + self.column_change, self.column_tag_color, ] self.smap = [ - self.column_id, - self.sort_father, - self.sort_mother, - self.column_type, - self.sort_marriage, + self.column_id, + self.sort_father, + self.sort_mother, + self.column_type, + self.sort_marriage, self.column_private, self.column_tags, - self.sort_change, + self.sort_change, self.column_tag_color, ] FlatBaseModel.__init__(self, db, scol, order, search=search, skip=skip, @@ -199,7 +199,7 @@ class FamilyModel(FlatBaseModel): def sort_change(self, data): return "%012x" % data[12] - + def column_change(self, data): return format_time(data[12]) @@ -212,7 +212,7 @@ class FamilyModel(FlatBaseModel): value = self.db.get_tag_from_handle(tag_handle).get_name() self.set_cached_value(tag_handle, "TAG_NAME", value) return value - + def column_tag_color(self, data): """ Return the tag color. diff --git a/gramps/gui/views/treemodels/flatbasemodel.py b/gramps/gui/views/treemodels/flatbasemodel.py index 7030309a4..0f0111c93 100644 --- a/gramps/gui/views/treemodels/flatbasemodel.py +++ b/gramps/gui/views/treemodels/flatbasemodel.py @@ -24,25 +24,25 @@ This module provides the flat treemodel that is used for all flat treeviews. For performance, GRAMPS does not use Gtk.TreeStore, as that would mean keeping -the entire database table of an object in memory. -Instead, it suffices to keep in memory the sortkey and the matching handle, -as well as a map of sortkey,handle to treeview path, and vice versa. +the entire database table of an object in memory. +Instead, it suffices to keep in memory the sortkey and the matching handle, +as well as a map of sortkey,handle to treeview path, and vice versa. For a flat view, the index of sortkey,handle will be the path, so it suffices to keep in memory a map that given a sortkey,handle returns the path. As we need to be able to insert/delete/update objects, and for that the handle -is all we know initially, and as sortkey,handle is uniquely determined by +is all we know initially, and as sortkey,handle is uniquely determined by handle, instead of keeping a map of sortkey,handle to path, we keep a map of handle to path As a user selects another column to sort, the sortkey must be rebuild, and the -map remade. +map remade. The class FlatNodeMap keeps a sortkeyhandle list with (sortkey, handle) entries, and a handle2path dictionary. As the Map is flat, the index in sortkeyhandle corresponds to the path. -The class FlatBaseModel, is the base class for all flat treeview models. +The class FlatBaseModel, is the base class for all flat treeview models. It keeps a FlatNodeMap, and obtains data from database as needed """ @@ -56,7 +56,7 @@ import bisect import time _LOG = logging.getLogger(".gui.basetreemodel") - + #------------------------------------------------------------------------- # # GNOME/GTK modules @@ -88,27 +88,27 @@ class FlatNodeMap(object): A NodeMap for a flat treeview. In such a TreeView, the paths possible are 0, 1, 2, ..., n-1, where n is the number of items to show. For the model it is needed to keep the Path to Iter mappings of the TreeView in memory - + The order of what is shown is based on the unique key: (sortkey, handle) Naming: * srtkey : key on which to sort - * hndl : handle of the object, makes it possible to retrieve the + * hndl : handle of the object, makes it possible to retrieve the object from the database. As handle is unique, it is used in the iter for the TreeView - * index : the index in the internal lists. When a view is in reverse, + * index : the index in the internal lists. When a view is in reverse, this is not kept physically, but instead via an offset * path : integer path in the TreeView. This will be index if view is ascending, but will begin at back of list if view shows the entries in reverse. - * index2hndl : list of (srtkey, hndl) tuples. The index gives the - (srtkey, hndl) it belongs to. - This normally is only a part of all possible data + * index2hndl : list of (srtkey, hndl) tuples. The index gives the + (srtkey, hndl) it belongs to. + This normally is only a part of all possible data * hndl2index : dictionary of *hndl: index* values - + The implementation provides a list of (srtkey, hndl) of which the index is the path, and a dictionary mapping hndl to index. To obtain index given a path, method real_index() is available - + ..Note: glocale.sort_key is applied to the underlying sort key, so as to have localized sort """ @@ -124,11 +124,11 @@ class FlatNodeMap(object): self._reverse = False self.__corr = (0, 1) #We create a stamp to recognize invalid iterators. From the docs: - #Set the stamp to be equal to your model's stamp, to mark the - #iterator as valid. When your model's structure changes, you should - #increment your model's stamp to mark all older iterators as invalid. - #They will be recognised as invalid because they will then have an - #incorrect stamp. + #Set the stamp to be equal to your model's stamp, to mark the + #iterator as valid. When your model's structure changes, you should + #increment your model's stamp to mark all older iterators as invalid. + #They will be recognised as invalid because they will then have an + #incorrect stamp. self.stamp = 0 def destroy(self): @@ -145,20 +145,20 @@ class FlatNodeMap(object): This is the core method to set up the FlatNodeMap Input is a list of (srtkey, handle), of which the index is the path Calling this method sets the index2hndllist, and creates the hndl2index - map. - fullhndllist is the entire list of (srtkey, handle) that is possible, + map. + fullhndllist is the entire list of (srtkey, handle) that is possible, normally index2hndllist is only part of this list as determined by filtering. To avoid memory, if both lists are the same, pass only one list twice and set identical to True. Reverse sets up how the path is determined from the index. If True the first index is the last path - - :param index2hndllist: the ascending sorted (sortkey, handle) values - as they will appear in the flat treeview. This often is + + :param index2hndllist: the ascending sorted (sortkey, handle) values + as they will appear in the flat treeview. This often is a subset of all possible data. :type index2hndllist: a list of (sortkey, handle) tuples - :param fullhndllist: the list of all possilbe ascending sorted - (sortkey, handle) values as they will appear in the flat + :param fullhndllist: the list of all possilbe ascending sorted + (sortkey, handle) values as they will appear in the flat treeview if all data is shown. :type fullhndllist: a list of (sortkey, handl) tuples :param identical: identify if index2hndllist and fullhndllist are the @@ -172,25 +172,25 @@ class FlatNodeMap(object): self._fullhndl = self._index2hndl if identical else fullhndllist self._reverse = reverse self.reverse_order() - + def full_srtkey_hndl_map(self): """ - The list of all possible (sortkey, handle) tuples. - This is stored in FlatNodeMap so that it would not be needed to + The list of all possible (sortkey, handle) tuples. + This is stored in FlatNodeMap so that it would not be needed to reiterate over the database to obtain all posibilities. """ return self._fullhndl def reverse_order(self): """ - This method keeps the index2hndl map, but sets it up the index in + This method keeps the index2hndl map, but sets it up the index in reverse order. If the hndl2index map does not exist yet, it is created in the acending order as given in index2hndl The result is always a hndl2index map wich is correct, so or ascending order, or reverse order. """ if self._hndl2index: - #if hndl2index is build already, invert order, otherwise keep + #if hndl2index is build already, invert order, otherwise keep # requested order self._reverse = not self._reverse if self._reverse: @@ -200,19 +200,19 @@ class FlatNodeMap(object): if not self._hndl2index: self._hndl2index = dict((key[1], index) for index, key in enumerate(self._index2hndl)) - + def real_path(self, index): """ - Given the index in the maps, return the real path. - If reverse = False, then index is path, otherwise however, the + Given the index in the maps, return the real path. + If reverse = False, then index is path, otherwise however, the path must be calculated so that the last index is the first path """ return self.__corr[0] + self.__corr[1] * index - + def real_index(self, path): """ Given the path in the view, return the real index. - If reverse = False, then path is index, otherwise however, the + If reverse = False, then path is index, otherwise however, the index must be calculated so that the last index is the first path """ return self.__corr[0] + self.__corr[1] * path @@ -229,7 +229,7 @@ class FlatNodeMap(object): def get_path(self, iter): """ Return the path from the passed iter. - + :param handle: the key of the object for which the path in the treeview is needed :type handle: an object handle @@ -247,7 +247,7 @@ class FlatNodeMap(object): def get_path_from_handle(self, handle): """ Return the path from the passed handle - + :param handle: the key of the object for which the path in the treeview is needed :type handle: an object handle @@ -262,7 +262,7 @@ class FlatNodeMap(object): def get_sortkey(self, handle): """ Return the sortkey used for the passed handle. - + :param handle: the key of the object for which the sortkey is needed :type handle: an object handle @@ -289,10 +289,10 @@ class FlatNodeMap(object): Return an iter from the path. The path is assumed to be an integer. This is accomplished by indexing into the index2hndl iters are always created afresh - + Will raise IndexError if the maps are not filled yet, or if it is empty. Caller should take care of this if it allows calling with invalid path - + :param path: path as it appears in the treeview :type path: integer """ @@ -303,10 +303,10 @@ class FlatNodeMap(object): """ Return the handle from the path. The path is assumed to be an integer. This is accomplished by indexing into the index2hndl - + Will raise IndexError if the maps are not filled yet, or if it is empty. Caller should take care of this if it allows calling with invalid path - + :param path: path as it appears in the treeview :type path: integer :return handle: unicode form of the handle @@ -321,7 +321,7 @@ class FlatNodeMap(object): Increments the iter y finding the index associated with the iter, adding or substracting one. False is returned if no next handle - + :param iter: Gtk.TreeModel iterator :param type: Gtk.TreeIter """ @@ -333,7 +333,7 @@ class FlatNodeMap(object): ##upstream bug: https://bugzilla.gnome.org/show_bug.cgi?id=698366 index = 0 - if self._reverse : + if self._reverse : index -= 1 if index < 0: # -1 does not raise IndexError, as -1 is last element. Catch. @@ -344,11 +344,11 @@ class FlatNodeMap(object): return False iter.user_data = index return True - + def get_first_iter(self): """ Return the first handle that must be shown (corresponding to path 0) - + Will raise IndexError if the maps are not filled yet, or if it is empty. Caller should take care of this if it allows calling with invalid path """ @@ -359,23 +359,23 @@ class FlatNodeMap(object): Return the number of entries in the map. """ return len(self._index2hndl) - + def max_rows(self): """ - Return maximum number of entries that might be present in the + Return maximum number of entries that might be present in the map """ return len(self._fullhndl) - + def insert(self, srtkey_hndl, allkeyonly=False): """ Insert a node. Given is a tuple (sortkey, handle), and this is added in the correct place, while the hndl2index map is updated. Returns the path of the inserted row - + :param srtkey_hndl: the (sortkey, handle) tuple that must be inserted :type srtkey_hndl: sortkey key already transformed by self.sort_func, object handle - + :Returns: path of the row inserted in the treeview :Returns type: Gtk.TreePath or None """ @@ -398,7 +398,7 @@ class FlatNodeMap(object): if self._reverse: self.__corr = (len(self._index2hndl) - 1, -1) return Gtk.TreePath((self.real_path(insert_pos),)) - + def delete(self, srtkey_hndl): """ Delete the row with the given (sortkey, handle). @@ -406,9 +406,9 @@ class FlatNodeMap(object): greater than the deleted index. path of deleted row is returned If handle is not present, None is returned - + :param srtkey_hndl: the (sortkey, handle) tuple that must be inserted - + :Returns: path of the row deleted from the treeview :Returns type: Gtk.TreePath or None """ @@ -445,7 +445,7 @@ class FlatNodeMap(object): #------------------------------------------------------------------------- class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): """ - The base class for all flat treeview models. + The base class for all flat treeview models. It keeps a FlatNodeMap, and obtains data from database as needed ..Note: glocale.sort_key is applied to the underlying sort key, so as to have localized sort @@ -482,7 +482,7 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): self.node_map = FlatNodeMap() self.set_search(search) - + self._reverse = (order == Gtk.SortType.DESCENDING) self.rebuild_data() @@ -504,9 +504,9 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): def set_search(self, search): """ - Change the search function that filters the data in the model. + Change the search function that filters the data in the model. When this method is called, make sure: - # you call self.rebuild_data() to recalculate what should be seen + # you call self.rebuild_data() to recalculate what should be seen in the model # you reattach the model to the treeview so that the treeview updates with the new entries @@ -561,12 +561,12 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): def sort_keys(self): """ - Return the (sort_key, handle) list of all data that can maximally - be shown. - This list is sorted ascending, via localized string sort. + Return the (sort_key, handle) list of all data that can maximally + be shown. + This list is sorted ascending, via localized string sort. """ # use cursor as a context manager - with self.gen_cursor() as cursor: + with self.gen_cursor() as cursor: #loop over database and store the sort field, and the handle srt_keys=[(self.sort_func(data), key.decode('utf8')) for key, data in cursor] @@ -596,7 +596,7 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): ident = False dlist = [h for h in allkeys if h[1] not in self.skip and h[1] != ignore] - self.node_map.set_path_map(dlist, allkeys, identical=ident, + self.node_map.set_path_map(dlist, allkeys, identical=ident, reverse=self._reverse) else: self.node_map.clear_map() @@ -617,7 +617,7 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): if ignore is None: dlist = self.search.apply(self.db, allkeys, tupleind=1) else: - dlist = self.search.apply(self.db, + dlist = self.search.apply(self.db, [ k for k in allkeys if k[1] != ignore], tupleind=1) elif ignore is None : @@ -626,12 +626,12 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): else: ident = False dlist = [ k for k in allkeys if k[1] != ignore ] - self.node_map.set_path_map(dlist, allkeys, identical=ident, + self.node_map.set_path_map(dlist, allkeys, identical=ident, reverse=self._reverse) else: self.node_map.clear_map() self._in_build = False - + def add_row_by_handle(self, handle): """ Add a row. This is called after object with handle is created. @@ -664,7 +664,7 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): delete_val = (self.node_map.get_sortkey(handle), handle) delete_path = self.node_map.delete(delete_val) #delete_path is an integer from 0 to n-1 - if delete_path is not None: + if delete_path is not None: self.row_deleted(delete_path) def update_row_by_handle(self, handle): @@ -678,7 +678,7 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): newsortkey = self.sort_func(self.map(handle)) if oldsortkey is None or oldsortkey != newsortkey: #or the changed object is not present in the view due to filtering - #or the order of the object must change. + #or the order of the object must change. self.delete_row_by_handle(handle) self.add_row_by_handle(handle) else: @@ -779,10 +779,10 @@ class FlatBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel): self.prev_data = data self.prev_handle = handle return self.fmap[col](self.prev_data) - + def do_get_value(self, iter, col): """ - See Gtk.TreeModel. + See Gtk.TreeModel. col is the model column that is needed, not the visible column! """ #print ('do_get_val', iter, iter.user_data, col) diff --git a/gramps/gui/views/treemodels/lru.py b/gramps/gui/views/treemodels/lru.py index 1c93c212e..ac798838c 100644 --- a/gramps/gui/views/treemodels/lru.py +++ b/gramps/gui/views/treemodels/lru.py @@ -34,7 +34,7 @@ class Node(object): self.value = value self.next = None -class LRU(object): +class LRU(object): """ Implementation of a length-limited O(1) LRU cache """ diff --git a/gramps/gui/views/treemodels/mediamodel.py b/gramps/gui/views/treemodels/mediamodel.py index 56795e8a7..17af42f21 100644 --- a/gramps/gui/views/treemodels/mediamodel.py +++ b/gramps/gui/views/treemodels/mediamodel.py @@ -58,7 +58,7 @@ class MediaModel(FlatBaseModel): skip=set(), sort_map=None): self.gen_cursor = db.get_media_cursor self.map = db.get_raw_object_data - + self.fmap = [ self.column_description, self.column_id, @@ -70,7 +70,7 @@ class MediaModel(FlatBaseModel): self.column_change, self.column_tag_color, ] - + self.smap = [ self.column_description, self.column_id, @@ -179,7 +179,7 @@ class MediaModel(FlatBaseModel): value = self.db.get_tag_from_handle(tag_handle).get_name() self.set_cached_value(tag_handle, "TAG_NAME", value) return value - + def column_tag_color(self, data): """ Return the tag color. diff --git a/gramps/gui/views/treemodels/notemodel.py b/gramps/gui/views/treemodels/notemodel.py index fe2784124..12d3e72fc 100644 --- a/gramps/gui/views/treemodels/notemodel.py +++ b/gramps/gui/views/treemodels/notemodel.py @@ -129,7 +129,7 @@ class NoteModel(FlatBaseModel): def sort_change(self, data): return "%012x" % data[Note.POS_CHANGE] - + def column_change(self,data): return format_time(data[Note.POS_CHANGE]) @@ -140,9 +140,9 @@ class NoteModel(FlatBaseModel): cached, value = self.get_cached_value(tag_handle, "TAG_NAME") if not cached: value = self.db.get_tag_from_handle(tag_handle).get_name() - self.set_cached_value(tag_handle, "TAG_NAME", value) - return value - + self.set_cached_value(tag_handle, "TAG_NAME", value) + return value + def column_tag_color(self, data): """ Return the tag color. @@ -160,8 +160,8 @@ class NoteModel(FlatBaseModel): tag_color = tag.get_color() tag_priority = this_priority value = tag_color - self.set_cached_value(tag_handle, "TAG_COLOR", value) - return value + self.set_cached_value(tag_handle, "TAG_COLOR", value) + return value def column_tags(self, data): """ diff --git a/gramps/gui/views/treemodels/peoplemodel.py b/gramps/gui/views/treemodels/peoplemodel.py index fb2168c6f..3b79c8529 100644 --- a/gramps/gui/views/treemodels/peoplemodel.py +++ b/gramps/gui/views/treemodels/peoplemodel.py @@ -200,7 +200,7 @@ class PeopleBaseModel(BaseModel): else: # There is a problem returning None here. return '' - + def _get_spouse_data(self, data): spouses_names = "" for family_handle in data[COLUMN_FAMILY]: @@ -236,7 +236,7 @@ class PeopleBaseModel(BaseModel): value = self._get_birth_data(data, False) self.set_cached_value(handle, "BIRTH_DAY", value) return value - + def sort_birth_day(self, data): handle = data[0] cached, value = self.get_cached_value(handle, "SORT_BIRTH_DAY") @@ -265,7 +265,7 @@ class PeopleBaseModel(BaseModel): return retval except: return '' - + for event_ref in data[COLUMN_EVENT]: er = EventRef() er.unserialize(event_ref) @@ -283,7 +283,7 @@ class PeopleBaseModel(BaseModel): return invalid_date_format % retval else: return retval - + return "" def column_death_day(self, data): @@ -293,7 +293,7 @@ class PeopleBaseModel(BaseModel): value = self._get_death_data(data, False) self.set_cached_value(handle, "DEATH_DAY", value) return value - + def sort_death_day(self, data): handle = data[0] cached, value = self.get_cached_value(handle, "SORT_DEATH_DAY") @@ -322,7 +322,7 @@ class PeopleBaseModel(BaseModel): return retval except: return '' - + for event_ref in data[COLUMN_EVENT]: er = EventRef() er.unserialize(event_ref) @@ -367,7 +367,7 @@ class PeopleBaseModel(BaseModel): value = '' self.set_cached_value(handle, "BIRTH_PLACE", value) return value - + for event_ref in data[COLUMN_EVENT]: er = EventRef() er.unserialize(event_ref) @@ -449,7 +449,7 @@ class PeopleBaseModel(BaseModel): for family_handle in data[COLUMN_FAMILY]: family = self.db.get_family_from_handle(family_handle) for child_ref in family.get_child_ref_list(): - if (child_ref.get_father_relation() == ChildRefType.BIRTH and + if (child_ref.get_father_relation() == ChildRefType.BIRTH and child_ref.get_mother_relation() == ChildRefType.BIRTH): children += 1 return children @@ -533,8 +533,8 @@ class PeopleBaseModel(BaseModel): cached, value = self.get_cached_value(tag_handle, "TAG_NAME") if not cached: value = self.db.get_tag_from_handle(tag_handle).get_name() - self.set_cached_value(tag_handle, "TAG_NAME", value) - return value + self.set_cached_value(tag_handle, "TAG_NAME", value) + return value def column_tag_color(self, data): """ @@ -553,8 +553,8 @@ class PeopleBaseModel(BaseModel): tag_color = tag.get_color() tag_priority = this_priority value = tag_color - self.set_cached_value(tag_handle, "TAG_COLOR", value) - return value + self.set_cached_value(tag_handle, "TAG_COLOR", value) + return value def column_tags(self, data): """ @@ -616,7 +616,7 @@ class PersonTreeModel(PeopleBaseModel, TreeBaseModel): def column_header(self, node): return node.name - + def add_row(self, handle, data): """ Add nodes to the node map for a single person. @@ -625,7 +625,7 @@ class PersonTreeModel(PeopleBaseModel, TreeBaseModel): data The object data. """ ngn = name_displayer.name_grouping_data - + name_data = data[COLUMN_NAME] group_name = ngn(self.db, name_data) #if isinstance(group_name, str): @@ -635,7 +635,7 @@ class PersonTreeModel(PeopleBaseModel, TreeBaseModel): #if group_name not in self.group_list: #self.group_list.append(group_name) #self.add_node(None, group_name, group_name, None) - - # add as node: parent, child, sortkey, handle; parent and child are + + # add as node: parent, child, sortkey, handle; parent and child are # nodes in the treebasemodel, and will be used as iters self.add_node(group_name, handle, sort_key, handle) diff --git a/gramps/gui/views/treemodels/placemodel.py b/gramps/gui/views/treemodels/placemodel.py index c7eedd251..c38347c7a 100644 --- a/gramps/gui/views/treemodels/placemodel.py +++ b/gramps/gui/views/treemodels/placemodel.py @@ -158,7 +158,7 @@ class PlaceBaseModel(object): value = conv_lat_lon(data[4], '0', format='ISO-DMS') if data[4] else '' if not value: return _("Error in format") - return value + return value def column_id(self, data): return str(data[1]) @@ -175,10 +175,10 @@ class PlaceBaseModel(object): else: # There is a problem returning None here. return '' - + def sort_change(self, data): return "%012x" % data[15] - + def column_change(self, data): return format_time(data[15]) @@ -189,9 +189,9 @@ class PlaceBaseModel(object): cached, value = self.get_cached_value(tag_handle, "TAG_NAME") if not cached: value = self.db.get_tag_from_handle(tag_handle).get_name() - self.set_cached_value(tag_handle, "TAG_NAME", value) - return value - + self.set_cached_value(tag_handle, "TAG_NAME", value) + return value + def column_tag_color(self, data): """ Return the tag color. @@ -209,8 +209,8 @@ class PlaceBaseModel(object): tag_color = tag.get_color() tag_priority = this_priority value = tag_color - self.set_cached_value(tag_handle, "TAG_COLOR", value) - return value + self.set_cached_value(tag_handle, "TAG_COLOR", value) + return value def column_tags(self, data): """ diff --git a/gramps/gui/views/treemodels/repomodel.py b/gramps/gui/views/treemodels/repomodel.py index 4ebfc05a5..b33fb64c8 100644 --- a/gramps/gui/views/treemodels/repomodel.py +++ b/gramps/gui/views/treemodels/repomodel.py @@ -72,7 +72,7 @@ class RepositoryModel(FlatBaseModel): self.column_change, self.column_tag_color ] - + self.smap = [ self.column_name, self.column_id, @@ -88,10 +88,10 @@ class RepositoryModel(FlatBaseModel): self.column_search_url, self.column_private, self.column_tags, - self.sort_change, + self.sort_change, self.column_tag_color ] - + FlatBaseModel.__init__(self, db, scol, order, search=search, skip=skip, sort_map=sort_map) @@ -144,7 +144,7 @@ class RepositoryModel(FlatBaseModel): except: pass return '' - + def column_locality(self,data): try: if data[5]: @@ -154,7 +154,7 @@ class RepositoryModel(FlatBaseModel): except: pass return '' - + def column_state(self,data): try: if data[5]: @@ -212,7 +212,7 @@ class RepositoryModel(FlatBaseModel): if url.get_type() == UrlType.WEB_SEARCH: return str(url.path) return '' - + def column_home_url(self,data): if data[6]: for i in data[6]: @@ -245,7 +245,7 @@ class RepositoryModel(FlatBaseModel): value = self.db.get_tag_from_handle(tag_handle).get_name() self.set_cached_value(tag_handle, "TAG_NAME", value) return value - + def column_tag_color(self, data): """ Return the tag color. diff --git a/gramps/gui/views/treemodels/sourcemodel.py b/gramps/gui/views/treemodels/sourcemodel.py index f445e9e02..1e506f76f 100644 --- a/gramps/gui/views/treemodels/sourcemodel.py +++ b/gramps/gui/views/treemodels/sourcemodel.py @@ -122,7 +122,7 @@ class SourceModel(FlatBaseModel): def column_change(self,data): return format_time(data[8]) - + def sort_change(self,data): return "%012x" % data[8] @@ -133,9 +133,9 @@ class SourceModel(FlatBaseModel): cached, value = self.get_cached_value(tag_handle, "TAG_NAME") if not cached: value = self.db.get_tag_from_handle(tag_handle).get_name() - self.set_cached_value(tag_handle, "TAG_NAME", value) - return value - + self.set_cached_value(tag_handle, "TAG_NAME", value) + return value + def column_tag_color(self, data): """ Return the tag color. @@ -153,8 +153,8 @@ class SourceModel(FlatBaseModel): tag_color = tag.get_color() tag_priority = this_priority value = tag_color - self.set_cached_value(tag_handle, "TAG_COLOR", value) - return value + self.set_cached_value(tag_handle, "TAG_COLOR", value) + return value def column_tags(self, data): """ diff --git a/gramps/gui/widgets/__init__.py b/gramps/gui/widgets/__init__.py index 5d4daa585..8aec265e2 100644 --- a/gramps/gui/widgets/__init__.py +++ b/gramps/gui/widgets/__init__.py @@ -43,4 +43,4 @@ from .undoablestyledbuffer import * from .validatedcomboentry import * from .validatedmaskedentry import * from .valueaction import * -from .valuetoolitem import * +from .valuetoolitem import * diff --git a/gramps/gui/widgets/basicentry.py b/gramps/gui/widgets/basicentry.py index 43c3db879..336af5bfd 100644 --- a/gramps/gui/widgets/basicentry.py +++ b/gramps/gui/widgets/basicentry.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. diff --git a/gramps/gui/widgets/buttons.py b/gramps/gui/widgets/buttons.py index ed2cf74da..002091082 100644 --- a/gramps/gui/widgets/buttons.py +++ b/gramps/gui/widgets/buttons.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -119,7 +119,7 @@ class SimpleButton(Gtk.Button): ## Unset all elements that can prevent garbage collection ## """ ## Gtk.Button.destroy(self) - + #------------------------------------------------------------------------- # # PrivacyButton class diff --git a/gramps/gui/widgets/dateentry.py b/gramps/gui/widgets/dateentry.py index 92983a1cd..216a07eb7 100644 --- a/gramps/gui/widgets/dateentry.py +++ b/gramps/gui/widgets/dateentry.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -50,7 +50,7 @@ from gramps.gen.lib.date import Date # #------------------------------------------------------------------------- class DateEntry(Gtk.Box): - + def __init__(self, uistate, track): Gtk.Box.__init__(self) self.entry = ValidatableMaskedEntry() @@ -58,12 +58,12 @@ class DateEntry(Gtk.Box): self.pack_start(self.entry, True, True, 0) image = Gtk.Image() image.set_from_icon_name('gramps-date-edit', Gtk.IconSize.BUTTON) - button = Gtk.Button() + button = Gtk.Button() button.set_image(image) button.set_relief(Gtk.ReliefStyle.NORMAL) self.pack_start(button, False, True, 0) self.date = Date() - self.date_entry = MonitoredDate(self.entry, button, self.date, + self.date_entry = MonitoredDate(self.entry, button, self.date, uistate, track) self.show_all() diff --git a/gramps/gui/widgets/expandcollapsearrow.py b/gramps/gui/widgets/expandcollapsearrow.py index 9bfb524aa..e38b44f81 100644 --- a/gramps/gui/widgets/expandcollapsearrow.py +++ b/gramps/gui/widgets/expandcollapsearrow.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -72,7 +72,7 @@ class ExpandCollapseArrow(Gtk.EventBox): """ Constructor for the ExpandCollapseArrow class. - :param collapsed: True if arrow must be shown collapsed, + :param collapsed: True if arrow must be shown collapsed, False otherwise :type collapsed: bool :param onbuttonpress: The callback function for button press diff --git a/gramps/gui/widgets/fanchart.py b/gramps/gui/widgets/fanchart.py index 0343b47c6..7f22227b4 100644 --- a/gramps/gui/widgets/fanchart.py +++ b/gramps/gui/widgets/fanchart.py @@ -11,7 +11,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -67,29 +67,29 @@ from gramps.gen.utils.db import (find_children, find_parents, find_witnessed_peo from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import ( PIXELS_PER_GENERATION, - BORDER_EDGE_WIDTH, - CHILDRING_WIDTH, - TRANSLATE_PX, - PAD_PX, - PAD_TEXT, - BACKGROUND_SCHEME1, - BACKGROUND_SCHEME2, - BACKGROUND_GENDER, - BACKGROUND_WHITE, - BACKGROUND_GRAD_GEN, - BACKGROUND_GRAD_AGE, - BACKGROUND_SINGLE_COLOR, - BACKGROUND_GRAD_PERIOD, + BORDER_EDGE_WIDTH, + CHILDRING_WIDTH, + TRANSLATE_PX, + PAD_PX, + PAD_TEXT, + BACKGROUND_SCHEME1, + BACKGROUND_SCHEME2, + BACKGROUND_GENDER, + BACKGROUND_WHITE, + BACKGROUND_GRAD_GEN, + BACKGROUND_GRAD_AGE, + BACKGROUND_SINGLE_COLOR, + BACKGROUND_GRAD_PERIOD, GENCOLOR, - MAX_AGE, - GRADIENTSCALE, - FORM_CIRCLE, - FORM_HALFCIRCLE, - FORM_QUADRANT, - COLLAPSED, - NORMAL, - EXPANDED, - TYPE_BOX_NORMAL, + MAX_AGE, + GRADIENTSCALE, + FORM_CIRCLE, + FORM_HALFCIRCLE, + FORM_QUADRANT, + COLLAPSED, + NORMAL, + EXPANDED, + TYPE_BOX_NORMAL, TYPE_BOX_FAMILY) _ = glocale.translation.gettext from gramps.gui.utilscairo import warpPath @@ -103,7 +103,7 @@ def gender_code(is_male): """ Given boolean is_male (means position in FanChart) return code. """ - if is_male: + if is_male: return Person.MALE else: return Person.FEMALE @@ -141,7 +141,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): #we want to grab key events also self.set_can_focus(True) self.connect("key-press-event", self.on_key_press) - + self.connect("draw", self.on_draw) self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | @@ -187,15 +187,15 @@ class FanChartBaseWidget(Gtk.DrawingArea): def reset(self): """ - Reset the fan chart. This should trigger computation of all data + Reset the fan chart. This should trigger computation of all data structures needed """ self.cache_fontcolor = {} - + # fill the data structure self._fill_data_structures() - - # prepare the colors for the boxes + + # prepare the colors for the boxes self.prepare_background_box() def _fill_data_structures(self): @@ -203,7 +203,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): fill in the data structures that will be needed to draw the chart """ raise NotImplementedError - + def do_size_request(self, requisition): """ Overridden method to handle size request events. @@ -219,7 +219,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): requisition.height = requisition.width def do_get_preferred_width(self): - """ GTK3 uses width for height sizing model. This method will + """ GTK3 uses width for height sizing model. This method will override the virtual method """ req = Gtk.Requisition() @@ -227,7 +227,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): return req.width, req.width def do_get_preferred_height(self): - """ GTK3 uses width for height sizing model. This method will + """ GTK3 uses width for height sizing model. This method will override the virtual method """ req = Gtk.Requisition() @@ -305,9 +305,9 @@ class FanChartBaseWidget(Gtk.DrawingArea): maxgen = self.generations cstart = hex_to_rgb(self.grad_start) cend = hex_to_rgb(self.grad_end) - self.cstart_hsv = colorsys.rgb_to_hsv(cstart[0]/255, cstart[1]/255, + self.cstart_hsv = colorsys.rgb_to_hsv(cstart[0]/255, cstart[1]/255, cstart[2]/255) - self.cend_hsv = colorsys.rgb_to_hsv(cend[0]/255, cend[1]/255, + self.cend_hsv = colorsys.rgb_to_hsv(cend[0]/255, cend[1]/255, cend[2]/255) if self.background in [BACKGROUND_GENDER, BACKGROUND_SINGLE_COLOR]: # nothing to precompute @@ -317,7 +317,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): #compute the colors, -1, 0, ..., maxgen divs = [x/(maxgen-1) for x in range(maxgen)] if maxgen>1 else [0] rgb_colors = [colorsys.hsv_to_rgb( - (1-x) * self.cstart_hsv[0] + x * self.cend_hsv[0], + (1-x) * self.cstart_hsv[0] + x * self.cend_hsv[0], (1-x) * self.cstart_hsv[1] + x * self.cend_hsv[1], (1-x) * self.cstart_hsv[2] + x * self.cend_hsv[2], ) for x in divs] @@ -349,11 +349,11 @@ class FanChartBaseWidget(Gtk.DrawingArea): if i % 2 == 1: self.gradval[i] = '' self.gradcol = [colorsys.hsv_to_rgb( - (1-div) * self.cstart_hsv[0] + div * self.cend_hsv[0], + (1-div) * self.cstart_hsv[0] + div * self.cend_hsv[0], (1-div) * self.cstart_hsv[1] + div * self.cend_hsv[1], (1-div) * self.cstart_hsv[2] + div * self.cend_hsv[2], ) for div in divs] - + elif self.background == BACKGROUND_GRAD_AGE: # we fill in in the data structure what the color age is, white if no age self.colors = None @@ -373,7 +373,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): if i % 2 == 1: self.gradval[i] = '' self.gradcol = [colorsys.hsv_to_rgb( - (1-div) * self.cstart_hsv[0] + div * self.cend_hsv[0], + (1-div) * self.cstart_hsv[0] + div * self.cend_hsv[0], (1-div) * self.cstart_hsv[1] + div * self.cend_hsv[1], (1-div) * self.cstart_hsv[2] + div * self.cend_hsv[2], ) for div in divs] @@ -386,7 +386,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): determine red, green, blue value of background of the box of person, which has gender gender, and is in ring generation """ - if generation == 0 and self.background in [BACKGROUND_GENDER, + if generation == 0 and self.background in [BACKGROUND_GENDER, BACKGROUND_GRAD_GEN, BACKGROUND_SCHEME1, BACKGROUND_SCHEME2]: # white for center person: @@ -413,7 +413,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): else: periodfrac = 0.5 periodcol = colorsys.hsv_to_rgb( - (1-periodfrac) * self.cstart_hsv[0] + periodfrac * self.cend_hsv[0], + (1-periodfrac) * self.cstart_hsv[0] + periodfrac * self.cend_hsv[0], (1-periodfrac) * self.cstart_hsv[1] + periodfrac * self.cend_hsv[1], (1-periodfrac) * self.cstart_hsv[2] + periodfrac * self.cend_hsv[2], ) @@ -432,7 +432,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): alpha = self.alpha_filter else: alpha = 1. - + return color[0], color[1], color[2], alpha def fontcolor(self, r, g, b, a): @@ -518,12 +518,12 @@ class FanChartBaseWidget(Gtk.DrawingArea): cr.arc_negative(0, 0, rmax, thetamax, thetamin) cr.close_path() ##cr.append_path(path) # not working correct - cr.set_source_rgba(r/255., g/255., b/255., a) + cr.set_source_rgba(r/255., g/255., b/255., a) cr.fill() def wrap_truncate_layout(self, layout, font, width_pixels): """Uses the layout to wrap and truncate its text to given width - + Returns: (w,h) as returned by layout.get_pixel_size() """ @@ -557,7 +557,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): layout.set_font_description(font) layout.set_wrap(Pango.WrapMode.CHAR) - # NOTE: for radial text, the sector radius height is the text width + # NOTE: for radial text, the sector radius height is the text width w, h = self.wrap_truncate_layout(layout, font, height - 2*PAD_TEXT) w = w + 5 # 5 pixel padding @@ -673,7 +673,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): def phi(x): return (x - x0) * dphi * arc_used_ratio / w \ + (1 - arc_used_ratio) * dphi / 2 \ - - math.pi/2 + - math.pi/2 def rho(y): return (y - y0) * (radiusin - radiusout)/h + radiusout @@ -714,8 +714,8 @@ class FanChartBaseWidget(Gtk.DrawingArea): def person_under_cursor(self, curx, cury): """ - Determine the generation and the position in the generation at - position x and y, as well as the type of box. + Determine the generation and the position in the generation at + position x and y, as well as the type of box. generation = -1 on center black dot generation >= self.generations outside of diagram """ @@ -727,7 +727,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): radius = math.sqrt((curx - cx) ** 2 + (cury - cy) ** 2) if radius < TRANSLATE_PX: generation = -1 - elif (self.childring and self.angle[-2] and + elif (self.childring and self.angle[-2] and radius < TRANSLATE_PX + CHILDRING_WIDTH): generation = -2 # indication of one of the children elif radius < self.CENTER: @@ -746,7 +746,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): if rads < math.pi: rads += 2 * math.pi # if generation is in expand zone: - # FIXME: add a way of expanding + # FIXME: add a way of expanding # find what person is in this position: selected = None if (0 <= generation < self.generations): @@ -757,7 +757,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): if start <= rads <= stop: selected = p break - + return generation, selected, btype def boxtype(self, radius): @@ -814,7 +814,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): # we edit the family self.edit_fam_cb(None, family.handle) return True - + return False def on_mouse_down(self, widget, event): @@ -826,7 +826,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): self.grab_focus() # left mouse on center dot, we translate on left click - if generation == -1: + if generation == -1: if event.button == 1: # left mouse # save the mouse location for movements self.translating = True @@ -846,7 +846,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): self._mouse_click_sel = selected self._mouse_click_btype = btype return False - + #right click on person, context menu # Do things based on state, event.get_state(), or button, event.button if is_right_click(event): @@ -874,7 +874,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): tooltip = self.format_helper.format_person(person, 11) self.set_tooltip_text(tooltip) return False - + #translate or rotate should happen alloc = self.get_allocation() x, y, w, h = alloc.x, alloc.y, alloc.width, alloc.height @@ -926,7 +926,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): self.center_xy = w/2 - event.x, h - self.CENTER - PAD_PX - event.y elif self.form == FORM_QUADRANT: self.center_xy = self.CENTER + PAD_PX - event.x, h - self.CENTER - PAD_PX - event.y - + self.last_x, self.last_y = None, None self.queue_draw() return True @@ -986,7 +986,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): pass return True return False - + #------------------------------------------------------------------------- # # FanChartWidget @@ -995,7 +995,7 @@ class FanChartBaseWidget(Gtk.DrawingArea): class FanChartWidget(FanChartBaseWidget): """ - Interactive Fan Chart Widget. + Interactive Fan Chart Widget. """ def __init__(self, dbstate, uistate, callback_popup=None): @@ -1012,7 +1012,7 @@ class FanChartWidget(FanChartBaseWidget): filter, alpha_filter, form): """ Reset the values to be used: - + :param root_person_handle: person to show :param maxgen: maximum generations to show :param background: config setting of which background procedure to use @@ -1025,7 +1025,7 @@ class FanChartWidget(FanChartBaseWidget): :param filter: the person filter to apply to the people in the chart :param alpha: the alpha transparency value (0-1) to apply to filtered out data - :param form: the ``FORM_`` constant for the fanchart + :param form: the ``FORM_`` constant for the fanchart """ self.rootpersonh = root_person_handle self.generations = maxgen @@ -1069,7 +1069,7 @@ class FanChartWidget(FanChartBaseWidget): def _fill_data_structures(self): self.set_generations() person = self.dbstate.db.get_person_from_handle(self.rootpersonh) - if not person: + if not person: name = None else: name = name_displayer.display(person) @@ -1125,7 +1125,7 @@ class FanChartWidget(FanChartBaseWidget): def _have_parents(self, person): """ - Returns True if a person has parents. + Returns True if a person has parents. TODO: is there no util function for this """ if person: @@ -1201,7 +1201,7 @@ class FanChartWidget(FanChartBaseWidget): def on_draw(self, widget, cr, scale=1.): """ The main method to do the drawing. - If widget is given, we assume we draw in GTK3 and use the allocation. + If widget is given, we assume we draw in GTK3 and use the allocation. To draw raw on the cairo context cr, set widget=None. """ # first do size request of what we will need @@ -1213,7 +1213,7 @@ class FanChartWidget(FanChartBaseWidget): self.set_size_request(2 * halfdist, halfdist + self.CENTER + PAD_PX) elif self.form == FORM_QUADRANT: self.set_size_request(halfdist + self.CENTER + PAD_PX, halfdist + self.CENTER + PAD_PX) - + #obtain the allocation alloc = self.get_allocation() x, y, w, h = alloc.x, alloc.y, alloc.width, alloc.height @@ -1240,8 +1240,8 @@ class FanChartWidget(FanChartBaseWidget): if person: start, stop, state = self.angle[generation][p] if state in [NORMAL, EXPANDED]: - self.draw_person(cr, gender_code(p%2 == 0), - text, start, stop, + self.draw_person(cr, gender_code(p%2 == 0), + text, start, stop, generation, state, parents, child, person, userdata) cr.set_source_rgb(1, 1, 1) # white @@ -1264,8 +1264,8 @@ class FanChartWidget(FanChartBaseWidget): cr.fill() cr.save() name = name_displayer.display(person) - self.draw_text(cr, name, self.CENTER - - (self.CENTER - (CHILDRING_WIDTH + TRANSLATE_PX))/2, 95, 455, + self.draw_text(cr, name, self.CENTER - + (self.CENTER - (CHILDRING_WIDTH + TRANSLATE_PX))/2, 95, 455, 10, False, self.fontcolor(r, g, b, a), self.fontbold(a)) cr.restore() @@ -1282,11 +1282,11 @@ class FanChartWidget(FanChartBaseWidget): if self.background in [BACKGROUND_GRAD_AGE, BACKGROUND_GRAD_PERIOD]: self.draw_gradient(cr, widget, halfdist) - def draw_person(self, cr, gender, name, start, stop, generation, + def draw_person(self, cr, gender, name, start, stop, generation, state, parents, child, person, userdata): """ Display the piece of pie for a given person. start and stop - are in degrees. Gender is indication of father position or mother + are in degrees. Gender is indication of father position or mother position in the chart """ cr.save() @@ -1323,7 +1323,7 @@ class FanChartWidget(FanChartBaseWidget): cr.arc_negative(0, 0, radmin, stop_rad, start_rad) cr.close_path() ##path = cr.copy_path() # not working correct - cr.set_source_rgba(r/255., g/255., b/255., a) + cr.set_source_rgba(r/255., g/255., b/255., a) cr.fill() #and again for the border cr.move_to(radius * math.cos(start_rad), radius * math.sin(start_rad)) @@ -1340,7 +1340,7 @@ class FanChartWidget(FanChartBaseWidget): cr.set_line_width(3) cr.stroke() cr.set_line_width(1) - if self.last_x is None or self.last_y is None: + if self.last_x is None or self.last_y is None: #we are not in a move, so draw text radial = False radstart = radius - PIXELS_PER_GENERATION/2 @@ -1350,8 +1350,8 @@ class FanChartWidget(FanChartBaseWidget): # more space to print it radial radial = True radstart = radius - PIXELS_PER_GENERATION - self.draw_text(cr, name, radstart, start, stop, - PIXELS_PER_GENERATION, radial, + self.draw_text(cr, name, radstart, start, stop, + PIXELS_PER_GENERATION, radial, self.fontcolor(r, g, b, a), self.fontbold(a)) cr.restore() @@ -1420,7 +1420,7 @@ class FanChartWidget(FanChartBaseWidget): start, stop, state = self.angle[generation][selected] if state in [NORMAL, EXPANDED]: slice = (stop - start) / 2.0 - self.angle[generation][selected] = [current, current + slice, + self.angle[generation][selected] = [current, current + slice, state] self.shrink_parents(generation + 1, selected, current) current += slice @@ -1529,7 +1529,7 @@ class FanChartGrampsGUI(object): self.fan = None self.on_childmenu_changed = on_childmenu_changed self.format_helper = FormattingHelper(self.dbstate) - + def set_fan(self, fan): """ Set the fanchartwidget to work on @@ -1540,7 +1540,7 @@ class FanChartGrampsGUI(object): def main(self): """ - Fill the data structures with the active data. This initializes all + Fill the data structures with the active data. This initializes all data. """ root_person_handle = self.get_active('Person') @@ -1553,7 +1553,7 @@ class FanChartGrampsGUI(object): def on_popup(self, obj, event, person_handle, family_handle=None): """ - Builds the full menu (including Siblings, Spouses, Children, + Builds the full menu (including Siblings, Spouses, Children, and Parents) with navigation. """ #store menu for GTK3 to avoid it being destroyed before showing @@ -1619,7 +1619,7 @@ class FanChartGrampsGUI(object): # collect all spouses, parents and children linked_persons = [] - + # Go over spouses and build their menu item = Gtk.MenuItem(label=_("Spouses")) fam_list = person.get_family_handle_list() @@ -1653,7 +1653,7 @@ class FanChartGrampsGUI(object): item.show() menu.append(item) - + # Go over siblings and build their menu item = Gtk.MenuItem(label=_("Siblings")) pfam_list = person.get_parent_family_handle_list() @@ -1696,7 +1696,7 @@ class FanChartGrampsGUI(object): item.set_sensitive(0) item.show() menu.append(item) - + # Go over children and build their menu item = Gtk.MenuItem(label=_("Children")) no_children = 1 @@ -1705,7 +1705,7 @@ class FanChartGrampsGUI(object): child = self.dbstate.db.get_person_from_handle(child_handle) if not child: continue - + if no_children: no_children = 0 item.set_submenu(Gtk.Menu()) @@ -1774,17 +1774,17 @@ class FanChartGrampsGUI(object): add_item.connect("activate", self.on_add_parents, person_handle) add_item.show() par_menu.append(add_item) - + item.show() menu.append(item) - + # Go over parents and build their menu item = Gtk.MenuItem(label=_("Related")) no_related = 1 for p_id in find_witnessed_people(self.dbstate.db,person): #if p_id in linked_persons: # continue # skip already listed family members - + per = self.dbstate.db.get_person_from_handle(p_id) if not per: continue @@ -1807,12 +1807,12 @@ class FanChartGrampsGUI(object): per_item.connect("activate", self.on_childmenu_changed, p_id) per_item.show() per_menu.append(per_item) - + if no_related: item.set_sensitive(0) item.show() menu.append(item) - + #we now construct an add menu item = Gtk.MenuItem(label=_("Add")) item.set_submenu(Gtk.Menu()) @@ -1837,7 +1837,7 @@ class FanChartGrampsGUI(object): person_handle) add_partner_item.show() add_menu.append(add_partner_item) - + add_pers_item = Gtk.ImageMenuItem() img = Gtk.Image.new_from_icon_name('list-add', Gtk.IconSize.MENU) add_pers_item.set_image(img) @@ -1847,10 +1847,10 @@ class FanChartGrampsGUI(object): add_menu.append(add_pers_item) item.show() menu.append(item) - + menu.popup(None, None, None, None, event.button, event.time) return 1 - + def edit_person_cb(self, obj, person_handle): person = self.dbstate.db.get_person_from_handle(person_handle) if person: @@ -1905,17 +1905,17 @@ class FanChartGrampsGUI(object): preset_name(father, name) person.set_primary_name(name) try: - EditPerson(self.dbstate, self.uistate, [], person, + EditPerson(self.dbstate, self.uistate, [], person, callback=callback) except WindowActiveError: pass - + def callback_add_child(self, person, family_handle): ref = ChildRef() ref.ref = person.get_handle() family = self.dbstate.db.get_family_from_handle(family_handle) family.add_child_ref(ref) - + with DbTxn(_("Add Child to Family"), self.dbstate.db) as trans: #add parentref to child person.add_parent_family_handle(family_handle) @@ -1933,7 +1933,7 @@ class FanChartGrampsGUI(object): if not person: return - + if person.gender == Person.MALE: family.set_father_handle(person.handle) else: @@ -1958,7 +1958,7 @@ class FanChartGrampsGUI(object): """Renders the person data into some lines of text and puts that into the clipboard""" person = self.dbstate.db.get_person_from_handle(person_handle) if person: - cb = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + cb = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_CLIPBOARD) cb.set_text( self.format_helper.format_person(person,11), -1) return True diff --git a/gramps/gui/widgets/fanchartdesc.py b/gramps/gui/widgets/fanchartdesc.py index ecee93cb1..c2d7a6b61 100644 --- a/gramps/gui/widgets/fanchartdesc.py +++ b/gramps/gui/widgets/fanchartdesc.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -69,7 +69,7 @@ from .fanchart import * pi = math.pi PIXELS_PER_GENPERSON = 30 # size of radius for generation of children -PIXELS_PER_GENFAMILY = 20 # size of radius for family +PIXELS_PER_GENFAMILY = 20 # size of radius for family PIXELS_PER_RECLAIM = 4 # size of the radius of pixels taken from family to reclaim space PARENTRING_WIDTH = 12 # width of the parent ring inside the person @@ -85,7 +85,7 @@ ANGLE_WEIGHT = 1 #Algorithm for angle computation based on nr of descendants class FanChartDescWidget(FanChartBaseWidget): """ - Interactive Fan Chart Widget. + Interactive Fan Chart Widget. """ CENTER = 60 # we require a larger center @@ -144,7 +144,7 @@ class FanChartDescWidget(FanChartBaseWidget): """ self.handle2desc = {} self.famhandle2desc = {} - self.handle2fam = {} + self.handle2fam = {} self.gen2people = {} self.gen2fam = {} self.parentsroot = [] @@ -168,12 +168,12 @@ class FanChartDescWidget(FanChartBaseWidget): def _fill_data_structures(self): self.set_generations() person = self.dbstate.db.get_person_from_handle(self.rootpersonh) - if not person: + if not person: #nothing to do, just return return else: name = name_displayer.display(person) - + # person, duplicate or not, start angle, slice size, # text, parent pos in fam, nrfam, userdata, status self.gen2people[0] = [[person, False, 0, 2*pi, name, 0, 0, [], NORMAL]] @@ -229,7 +229,7 @@ class FanChartDescWidget(FanChartBaseWidget): famdup = True else: famdup = False - # family, duplicate or not, start angle, slice size, + # family, duplicate or not, start angle, slice size, # text, spouse pos in gen, nrchildren, userdata, parnter, status self.gen2fam[gen].append([family, famdup, 0, 0, spname, pos, 0, [], spouse, NORMAL]) @@ -248,7 +248,7 @@ class FanChartDescWidget(FanChartBaseWidget): self.handle2desc[child_ref.ref] = 0 # person, duplicate or not, start angle, slice size, # text, parent pos in fam, nrfam, userdata, status - self.gen2people[gen+1].append([child, dup, 0, 0, chname, + self.gen2people[gen+1].append([child, dup, 0, 0, chname, posfam, 0, [], NORMAL]) totdescfam += 1 #add this person as descendant pospers = len(self.gen2people[gen+1]) - 1 @@ -310,13 +310,13 @@ class FanChartDescWidget(FanChartBaseWidget): slice = 0 elif data[9] == EXPANDED: slice = partslice - + data[2] = partstart + offset data[3] = slice offset += slice - + ## if nrdescpartner == 0: -## #no offspring, draw as large as fraction of +## #no offspring, draw as large as fraction of ## #nr families ## nrfam = partnerdata[6] ## slice = partslice/nrfam @@ -324,9 +324,9 @@ class FanChartDescWidget(FanChartBaseWidget): ## data[3] = slice ## offset += slice ## elif nrdescfam == 0: -## #no offspring this family, but there is another +## #no offspring this family, but there is another ## #family. We draw this as a weight of 1 -## nrfam = partnerdata[6] +## nrfam = partnerdata[6] ## slice = partslice/(nrdescpartner + nrfam - 1)*(nrdescfam+1) ## data[2] = partstart + offset ## data[3] = slice @@ -339,7 +339,7 @@ class FanChartDescWidget(FanChartBaseWidget): ## data[2] = partstart + offset ## data[3] = slice ## offset += slice - + prevfamdatahandle = None offset = 0 for data in self.gen2people[gen]: @@ -415,7 +415,7 @@ class FanChartDescWidget(FanChartBaseWidget): def on_draw(self, widget, cr, scale=1.): """ The main method to do the drawing. - If widget is given, we assume we draw in GTK3 and use the allocation. + If widget is given, we assume we draw in GTK3 and use the allocation. To draw raw on the cairo context cr, set widget=None. """ # first do size request of what we will need @@ -424,12 +424,12 @@ class FanChartDescWidget(FanChartBaseWidget): if self.form == FORM_CIRCLE: self.set_size_request(2 * halfdist, 2 * halfdist) elif self.form == FORM_HALFCIRCLE: - self.set_size_request(2 * halfdist, halfdist + self.CENTER + self.set_size_request(2 * halfdist, halfdist + self.CENTER + PAD_PX) elif self.form == FORM_QUADRANT: self.set_size_request(halfdist + self.CENTER + PAD_PX, halfdist + self.CENTER + PAD_PX) - + #obtain the allocation alloc = self.get_allocation() x, y, w, h = alloc.x, alloc.y, alloc.width, alloc.height @@ -472,9 +472,9 @@ class FanChartDescWidget(FanChartBaseWidget): cr.fill() cr.save() name = name_displayer.display(person) - self.draw_text(cr, name, self.CENTER - PIXELS_PER_GENFAMILY - - (self.CENTER - PIXELS_PER_GENFAMILY - - (CHILDRING_WIDTH + TRANSLATE_PX))/2, + self.draw_text(cr, name, self.CENTER - PIXELS_PER_GENFAMILY + - (self.CENTER - PIXELS_PER_GENFAMILY + - (CHILDRING_WIDTH + TRANSLATE_PX))/2, 95, 455, 10, False, self.fontcolor(r, g, b, a), self.fontbold(a)) cr.restore() @@ -494,13 +494,13 @@ class FanChartDescWidget(FanChartBaseWidget): for gen in range(self.generations-1): radstart += PIXELS_PER_GENPERSON for famdata in self.gen2fam[gen]: - # family, duplicate or not, start angle, slice size, + # family, duplicate or not, start angle, slice size, # text, spouse pos in gen, nrchildren, userdata, status fam, dup, start, slice, text, posfam, nrchild, userdata,\ partner, status = famdata if status != COLLAPSED: - self.draw_person(cr, text, start, slice, radstart, - radstart + PIXELS_PER_GENFAMILY, gen, dup, + self.draw_person(cr, text, start, slice, radstart, + radstart + PIXELS_PER_GENFAMILY, gen, dup, partner, userdata, family=True, thick=status != NORMAL) radstart += PIXELS_PER_GENFAMILY for pdata in self.gen2people[gen+1]: @@ -509,19 +509,19 @@ class FanChartDescWidget(FanChartBaseWidget): pers, dup, start, slice, text, pospar, nrfam, userdata, status = \ pdata if status != COLLAPSED: - self.draw_person(cr, text, start, slice, radstart, - radstart + PIXELS_PER_GENPERSON, gen+1, dup, + self.draw_person(cr, text, start, slice, radstart, + radstart + PIXELS_PER_GENPERSON, gen+1, dup, pers, userdata, thick=status != NORMAL) cr.restore() - + if self.background in [BACKGROUND_GRAD_AGE, BACKGROUND_GRAD_PERIOD]: self.draw_gradient(cr, widget, halfdist) - def draw_person(self, cr, name, start_rad, slice, radius, radiusend, + def draw_person(self, cr, name, start_rad, slice, radius, radiusend, generation, dup, person, userdata, family=False, thick=False): """ Display the piece of pie for a given person. start_rad and slice - are in radial. + are in radial. """ if slice == 0: return @@ -531,7 +531,7 @@ class FanChartDescWidget(FanChartBaseWidget): full = True stop_rad = start_rad + slice if not person: - #an family with partner not set. Don't have a color for this, + #an family with partner not set. Don't have a color for this, # let's make it transparent r, g, b, a = (255, 255, 255, 0) elif not dup: @@ -541,7 +541,7 @@ class FanChartDescWidget(FanChartBaseWidget): a = 1 r, g, b = self.dupcolor #(136, 138, 133) # If max generation, and they have children: - if (not family and generation == self.generations - 1 + if (not family and generation == self.generations - 1 and self._have_children(person)): # draw an indicator radmax = radiusend + BORDER_EDGE_WIDTH @@ -576,7 +576,7 @@ class FanChartDescWidget(FanChartBaseWidget): radial = True radstart = radius self.draw_text(cr, name, radstart, start_rad/ math.pi*180, - stop_rad/ math.pi*180, width, radial, + stop_rad/ math.pi*180, width, radial, self.fontcolor(r, g, b, a), self.fontbold(a)) cr.restore() @@ -659,7 +659,7 @@ class FanChartDescWidget(FanChartBaseWidget): # text, parent pos in fam, nrfam, userdata, status person = self.gen2people[generation][pos][0] elif btype == TYPE_BOX_FAMILY: - # family, duplicate or not, start angle, slice size, + # family, duplicate or not, start angle, slice size, # text, spouse pos in gen, nrchildren, userdata, person, status person = self.gen2fam[generation][pos][8] return person @@ -674,7 +674,7 @@ class FanChartDescWidget(FanChartBaseWidget): def do_mouse_click(self): # no drag occured, expand or collapse the section - self.change_slice(self._mouse_click_gen, self._mouse_click_sel, + self.change_slice(self._mouse_click_gen, self._mouse_click_sel, self._mouse_click_btype) self._mouse_click = False self.queue_draw() @@ -712,7 +712,7 @@ class FanChartDescWidget(FanChartBaseWidget): for entry in self.gen2fam[generation]: if entry[5] == parpos: entry[9] = NORMAL - + self.__compute_angles() class FanChartDescGrampsGUI(FanChartGrampsGUI): @@ -721,7 +721,7 @@ class FanChartDescGrampsGUI(FanChartGrampsGUI): def main(self): """ - Fill the data structures with the active data. This initializes all + Fill the data structures with the active data. This initializes all data. """ root_person_handle = self.get_active('Person') diff --git a/gramps/gui/widgets/grabbers.py b/gramps/gui/widgets/grabbers.py index 3f0242084..c1f579d62 100644 --- a/gramps/gui/widgets/grabbers.py +++ b/gramps/gui/widgets/grabbers.py @@ -37,7 +37,7 @@ GRABBER_OUTSIDE = 1 MIN_CORNER_GRABBER = 20 MIN_SIDE_GRABBER = 20 MIN_GRABBER_PADDING = 10 -MIN_SIDE_FOR_INSIDE_GRABBERS = (2 * (MIN_CORNER_GRABBER + MIN_GRABBER_PADDING) + +MIN_SIDE_FOR_INSIDE_GRABBERS = (2 * (MIN_CORNER_GRABBER + MIN_GRABBER_PADDING) + MIN_SIDE_GRABBER) INSIDE = 0 @@ -54,8 +54,8 @@ def upper_left_grabber_inner(x1, y1, x2, y2): return (x1, y1, x1 + MIN_CORNER_GRABBER, y1 + MIN_CORNER_GRABBER) def upper_grabber_inner(x1, y1, x2, y2): - return (x1 + MIN_CORNER_GRABBER + MIN_GRABBER_PADDING, - y1, + return (x1 + MIN_CORNER_GRABBER + MIN_GRABBER_PADDING, + y1, x2 - MIN_CORNER_GRABBER - MIN_GRABBER_PADDING, y1 + MIN_CORNER_GRABBER) @@ -72,8 +72,8 @@ def lower_right_grabber_inner(x1, y1, x2, y2): return (x2 - MIN_CORNER_GRABBER, y2 - MIN_CORNER_GRABBER, x2, y2) def lower_grabber_inner(x1, y1, x2, y2): - return (x1 + MIN_CORNER_GRABBER + MIN_GRABBER_PADDING, - y2 - MIN_CORNER_GRABBER, + return (x1 + MIN_CORNER_GRABBER + MIN_GRABBER_PADDING, + y2 - MIN_CORNER_GRABBER, x2 - MIN_CORNER_GRABBER - MIN_GRABBER_PADDING, y2) @@ -183,7 +183,7 @@ MOTION_FUNCTIONS = [inside_moved, lower_left_moved, left_moved] -GRABBERS_SWITCH = [ +GRABBERS_SWITCH = [ [INSIDE, INSIDE, INSIDE], [GRABBER_UPPER_RIGHT, GRABBER_LOWER_RIGHT, GRABBER_LOWER_LEFT], [GRABBER_UPPER, GRABBER_LOWER, GRABBER_LOWER], @@ -229,7 +229,7 @@ CURSORS = [None, def grabber_position(rect): x1, y1, x2, y2 = rect - if (x2 - x1 >= MIN_SIDE_FOR_INSIDE_GRABBERS and + if (x2 - x1 >= MIN_SIDE_FOR_INSIDE_GRABBERS and y2 - y1 >= MIN_SIDE_FOR_INSIDE_GRABBERS): return GRABBER_INSIDE else: @@ -263,7 +263,7 @@ def can_grab(rect, x, y): Checks if (x,y) lies within one of the grabbers of rect. """ (x1, y1, x2, y2) = rect - if (x2 - x1 >= MIN_SIDE_FOR_INSIDE_GRABBERS and + if (x2 - x1 >= MIN_SIDE_FOR_INSIDE_GRABBERS and y2 - y1 >= MIN_SIDE_FOR_INSIDE_GRABBERS): # grabbers are inside if x < x1 or x > x2 or y < y1 or y > y2: diff --git a/gramps/gui/widgets/grampletbar.py b/gramps/gui/widgets/grampletbar.py index 90610e2e5..4f1c246e3 100644 --- a/gramps/gui/widgets/grampletbar.py +++ b/gramps/gui/widgets/grampletbar.py @@ -62,12 +62,12 @@ from gramps.gen.config import config from gramps.gen.constfunc import win from ..managedwindow import ManagedWindow from ..display import display_help, display_url -from .grampletpane import (AVAILABLE_GRAMPLETS, - GET_AVAILABLE_GRAMPLETS, - GET_GRAMPLET_LIST, - get_gramplet_opts, - get_gramplet_options_by_name, - make_requested_gramplet, +from .grampletpane import (AVAILABLE_GRAMPLETS, + GET_AVAILABLE_GRAMPLETS, + GET_GRAMPLET_LIST, + get_gramplet_opts, + get_gramplet_options_by_name, + make_requested_gramplet, GuiGramplet) from .undoablebuffer import UndoableBuffer from ..utils import is_right_click @@ -109,7 +109,7 @@ class GrampletBar(Gtk.Notebook): book_button = Gtk.Button() # Arrow is too small unless in a box box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) - arrow = Gtk.Arrow(arrow_type=Gtk.ArrowType.DOWN, + arrow = Gtk.Arrow(arrow_type=Gtk.ArrowType.DOWN, shadow_type=Gtk.ShadowType.NONE) arrow.show() box.add(arrow) @@ -130,7 +130,7 @@ class GrampletBar(Gtk.Notebook): for opts in opts_list: if opts["name"] in AVAILABLE_GRAMPLETS(): all_opts = get_gramplet_opts(opts["name"], opts) - gramplet = make_requested_gramplet(TabGramplet, self, all_opts, + gramplet = make_requested_gramplet(TabGramplet, self, all_opts, self.dbstate, self.uistate) if gramplet: self.__add_tab(gramplet) @@ -209,7 +209,7 @@ class GrampletBar(Gtk.Notebook): fp.write("[Bar Options]" + NL) fp.write(("visible=%s" + NL) % self.get_property('visible')) fp.write(("page=%d" + NL) % self.get_current_page()) - fp.write(NL) + fp.write(NL) if self.empty: gramplet_list = [] @@ -226,7 +226,7 @@ class GrampletBar(Gtk.Notebook): base_opts[key] = gramplet.__dict__[key] fp.write(("[%s]" + NL) % gramplet.gname) for key in base_opts: - if key in ["content", "title", "tname", "row", "column", + if key in ["content", "title", "tname", "row", "column", "page", "version", "gramps"]: # don't save continue elif key == "data": @@ -440,7 +440,7 @@ class GrampletBar(Gtk.Notebook): if self.get_n_pages() == 0: self.empty = True self.__create_empty_tab() - + def __create_window(self, grampletbar, gramplet, x_pos, y_pos): """ Called when the user has switched to a new GrampletBar page. @@ -650,7 +650,7 @@ class DetachedWindow(ManagedWindow): else: display_help(self.gramplet.help_url) else: - display_help(WIKI_HELP_PAGE, + display_help(WIKI_HELP_PAGE, self.gramplet.tname.replace(" ", "_")) def get_notebook(self): @@ -693,7 +693,7 @@ class TabLabel(Gtk.Box): """ def __init__(self, gramplet, callback): Gtk.Box.__init__(self) - + self.text = gramplet.title self.set_spacing(4) @@ -745,5 +745,5 @@ def cb_menu_position(*args): ret_val, x_pos, y_pos = button.get_window().get_origin() x_pos += button.get_allocation().x y_pos += button.get_allocation().y + button.get_allocation().height - + return (x_pos, y_pos, False) diff --git a/gramps/gui/widgets/grampletpane.py b/gramps/gui/widgets/grampletpane.py index 6fa669937..5aba8bd02 100644 --- a/gramps/gui/widgets/grampletpane.py +++ b/gramps/gui/widgets/grampletpane.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -73,7 +73,7 @@ WIKI_HELP_PAGE = URL_MANUAL_PAGE + '_-_Gramplets' # #------------------------------------------------------------------------- PLUGMAN = GuiPluginManager.get_instance() -NL = "\n" +NL = "\n" def AVAILABLE_GRAMPLETS(): return [gplug.id for gplug in PLUGMAN.get_reg_gramplets()] @@ -86,14 +86,14 @@ def GET_AVAILABLE_GRAMPLETS(name): "tname": gplug.name, "version": gplug.version, "height": gplug.height, - "expand": gplug.expand, + "expand": gplug.expand, "title": gplug.gramplet_title, # translated "content": gplug.gramplet, "detached_width": gplug.detached_width, "detached_height": gplug.detached_height, "state": "maximized", "gramps": "0.0.0", - "column": -1, + "column": -1, "row": -1, "page": 0, "data": [], @@ -203,7 +203,7 @@ class LinkTag(Gtk.TextTag): linkcolor[1].blue)) else: linkcolor = 'blue' - + def __init__(self, buffer): LinkTag.lid += 1 GObject.GObject.__init__(self, name=str(LinkTag.lid)) @@ -230,7 +230,7 @@ class GrampletWindow(ManagedWindow): # Keep track of what state it was in: self.docked_state = gramplet.gstate # Now detach it - self.gramplet.set_state("detached") + self.gramplet.set_state("detached") ManagedWindow.__init__(self, gramplet.uistate, [], self.title) self.set_window(Gtk.Dialog("", gramplet.uistate.window, @@ -270,9 +270,9 @@ class GrampletWindow(ManagedWindow): else: display_help(self.gramplet.help_url) else: - display_help(WIKI_HELP_PAGE, + display_help(WIKI_HELP_PAGE, self.gramplet.tname.replace(" ", "_")) - + def build_menu_names(self, obj): """ Part of the GRAMPS window interface. @@ -384,7 +384,7 @@ class GuiGramplet(object): def set_tooltip(self, tip): self.tooltips_text = tip self.scrolledwindow.set_tooltip_text(tip) - + def undo(self): self.buffer.undo() self.text_length = len(self.get_text()) @@ -395,12 +395,12 @@ class GuiGramplet(object): def on_key_press_event(self, widget, event): """Signal handler. - + Handle formatting shortcuts. - + """ if ((Gdk.keyval_name(event.keyval) == 'Z') and - (event.get_state() & Gdk.ModifierType.CONTROL_MASK) and + (event.get_state() & Gdk.ModifierType.CONTROL_MASK) and (event.get_state() & Gdk.ModifierType.SHIFT_MASK)): self.redo() return True @@ -479,7 +479,7 @@ class GuiGramplet(object): retval += text[i] r += 1 i += 1 - offset = self.text_length + offset = self.text_length self.append_text(retval) for items in markup_pos["TT"]: if len(items) == 3: @@ -548,7 +548,7 @@ class GuiGramplet(object): def make_gui_options(self): if not self.pui: return - # BEGIN WORKAROUND: + # BEGIN WORKAROUND: # This is necessary because gtk doesn't redisplay these widgets # correctly so we replace them with new ones self.pui.save_options() @@ -593,8 +593,8 @@ class GuiGramplet(object): buffer.apply_tag(link_data[0], start, end) def on_motion(self, view, event): - buffer_location = view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, - int(event.x), + buffer_location = view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, + int(event.x), int(event.y)) iter = view.get_iter_at_location(*buffer_location) cursor = self.standard_cursor @@ -615,8 +615,8 @@ class GuiGramplet(object): def on_button_press(self, view, event): # pylint: disable-msg=W0212 - buffer_location = view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, - int(event.x), + buffer_location = view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, + int(event.x), int(event.y)) iter = view.get_iter_at_location(*buffer_location) for (tag, link_type, handle, tooltip) in self._tags: @@ -627,8 +627,8 @@ class GuiGramplet(object): if event.button == 1: # left mouse if event.type == Gdk.EventType._2BUTTON_PRESS: # double try: - EditPerson(self.dbstate, - self.uistate, + EditPerson(self.dbstate, + self.uistate, [], person) return True # handled event except WindowActiveError: @@ -639,8 +639,8 @@ class GuiGramplet(object): elif is_right_click(event): #FIXME: add a popup menu with options try: - EditPerson(self.dbstate, - self.uistate, + EditPerson(self.dbstate, + self.uistate, [], person) return True # handled event except WindowActiveError: @@ -648,25 +648,25 @@ class GuiGramplet(object): elif link_type == 'Surname': if event.button == 1: # left mouse if event.type == Gdk.EventType._2BUTTON_PRESS: # double - run_quick_report_by_name(self.dbstate, - self.uistate, - 'samesurnames', + run_quick_report_by_name(self.dbstate, + self.uistate, + 'samesurnames', handle) return True elif link_type == 'Given': if event.button == 1: # left mouse if event.type == Gdk.EventType._2BUTTON_PRESS: # double - run_quick_report_by_name(self.dbstate, - self.uistate, - 'samegivens_misc', + run_quick_report_by_name(self.dbstate, + self.uistate, + 'samegivens_misc', handle) return True elif link_type == 'Filter': if event.button == 1: # left mouse if event.type == Gdk.EventType._2BUTTON_PRESS: # double - run_quick_report_by_name(self.dbstate, - self.uistate, - 'filterbyname', + run_quick_report_by_name(self.dbstate, + self.uistate, + 'filterbyname', handle) return True elif link_type == 'URL': @@ -688,8 +688,8 @@ class GuiGramplet(object): if event.button == 1: # left mouse if event.type == Gdk.EventType._2BUTTON_PRESS: # double try: - EditFamily(self.dbstate, - self.uistate, + EditFamily(self.dbstate, + self.uistate, [], family) return True # handled event except WindowActiveError: @@ -700,8 +700,8 @@ class GuiGramplet(object): elif is_right_click(event): #FIXME: add a popup menu with options try: - EditFamily(self.dbstate, - self.uistate, + EditFamily(self.dbstate, + self.uistate, [], family) return True # handled event except WindowActiveError: @@ -709,18 +709,18 @@ class GuiGramplet(object): elif link_type == 'PersonList': if event.button == 1: # left mouse if event.type == Gdk.EventType._2BUTTON_PRESS: # double - run_quick_report_by_name(self.dbstate, - self.uistate, - 'filterbyname', + run_quick_report_by_name(self.dbstate, + self.uistate, + 'filterbyname', 'list of people', handles=handle) return True elif link_type == 'Attribute': if event.button == 1: # left mouse if event.type == Gdk.EventType._2BUTTON_PRESS: # double - run_quick_report_by_name(self.dbstate, - self.uistate, - 'attribute_match', + run_quick_report_by_name(self.dbstate, + self.uistate, + 'attribute_match', handle) return True else: # overzealous l10n while setting the link? @@ -838,7 +838,7 @@ class GridGramplet(GuiGramplet): def close(self, *obj): """ - Remove (delete) the gramplet from view. + Remove (delete) the gramplet from view. """ if self.gstate == "detached": return @@ -851,7 +851,7 @@ class GridGramplet(GuiGramplet): Detach the gramplet from the GrampletView, and open in own window. """ # hide buttons: - #self.set_state("detached") + #self.set_state("detached") self.pane.detached_gramplets.append(self) # make a window, and attach it there self.detached_window = GrampletWindow(self) @@ -894,7 +894,7 @@ class GridGramplet(GuiGramplet): self.set_state("minimized") else: self.set_state("maximized") - + def set_properties(self, obj): """ Set the properties of a gramplet. @@ -957,17 +957,17 @@ class GridGramplet(GuiGramplet): if new_title in self.pane.gramplet_map: return False if set_override: self.title_override = True - del self.pane.gramplet_map[self.title] + del self.pane.gramplet_map[self.title] self.title = new_title if self.detached_window: - self.detached_window.window.set_title("%s %s - Gramps" % + self.detached_window.window.set_title("%s %s - Gramps" % (new_title, _("Gramplet"))) self.pane.gramplet_map[self.title] = self self.titlelabel.get_children()[0].set_text("%s" % self.title) self.titlelabel.get_children()[0].set_use_markup(True) return True - + class GrampletPane(Gtk.ScrolledWindow): def __init__(self, configfile, pageview, dbstate, uistate, **kwargs): self._config = Configuration(self) @@ -975,12 +975,12 @@ class GrampletPane(Gtk.ScrolledWindow): GObject.GObject.__init__(self) self.configfile = os.path.join(VERSION_DIR, "%s.ini" % configfile) # default for new user; may be overridden in config: - self.column_count = kwargs.get("column_count", 2) + self.column_count = kwargs.get("column_count", 2) # width of window, if sidebar; may be overridden in config: - self.pane_position = kwargs.get("pane_position", -1) - self.pane_orientation = kwargs.get("pane_orientation", "horizontal") - self.splitview = kwargs.get("splitview", None) - self.default_gramplets = kwargs.get("default_gramplets", + self.pane_position = kwargs.get("pane_position", -1) + self.pane_orientation = kwargs.get("pane_orientation", "horizontal") + self.splitview = kwargs.get("splitview", None) + self.default_gramplets = kwargs.get("default_gramplets", ["Top Surnames", "Welcome"]) self.dbstate = dbstate self.uistate = uistate @@ -1060,7 +1060,7 @@ class GrampletPane(Gtk.ScrolledWindow): def show_all(self): """ - This seems to be necessary to hide the hidden + This seems to be necessary to hide the hidden parts of a collapsed gramplet on main view. """ super(GrampletPane, self).show_all() @@ -1087,7 +1087,7 @@ class GrampletPane(Gtk.ScrolledWindow): """ Detach all of the mainframe gramplets from the columns. """ - gramplets = (g for g in self.gramplet_map.values() + gramplets = (g for g in self.gramplet_map.values() if g is not None) for gramplet in gramplets: if (gramplet.gstate == "detached" or gramplet.gstate == "closed"): @@ -1100,7 +1100,7 @@ class GrampletPane(Gtk.ScrolledWindow): """ Place the gramplet mainframes in the columns. """ - gramplets = [g for g in self.gramplet_map.values() + gramplets = [g for g in self.gramplet_map.values() if g is not None] # put the gramplets where they go: # sort by row @@ -1132,9 +1132,9 @@ class GrampletPane(Gtk.ScrolledWindow): # gramplet.set_state("minimized") # minimize it # set minimized is called in page subclass hack (above) if gramplet.gstate == "detached": - gramplet.detach() + gramplet.detach() elif gramplet.gstate == "closed": - gramplet.close() + gramplet.close() def load_gramplets(self): retval = [] @@ -1156,7 +1156,7 @@ class GrampletPane(Gtk.ScrolledWindow): if "pane_orientation" in cp.options(sec): self.pane_orientation = cp.get(sec, "pane_orientation") else: - data = {} + data = {} for opt in cp.options(sec): if opt.startswith("data["): temp = data.get("data", {}) @@ -1211,7 +1211,7 @@ class GrampletPane(Gtk.ScrolledWindow): fp.write("[%s]\n" % gramplet.gname) for key in base_opts: if key == "content": continue - elif key == "title": + elif key == "title": if gramplet.title_override: fp.write("title=%s\n" % base_opts[key]) elif key == "tname": continue @@ -1285,7 +1285,7 @@ class GrampletPane(Gtk.ScrolledWindow): # first, find column: col = 0 for i in range(len(self.columns)): - if x < (sx/len(self.columns) * (i + 1)): + if x < (sx/len(self.columns) * (i + 1)): col = i break if button: @@ -1346,7 +1346,7 @@ class GrampletPane(Gtk.ScrolledWindow): #gramplet.gstate = "maximized" self.closed_gramplets.remove(gramplet) if self._popup_xy is not None: - self.drop_widget(self, gramplet, + self.drop_widget(self, gramplet, self._popup_xy[0], self._popup_xy[1], 0) else: self.drop_widget(self, gramplet, 0, 0, 0) @@ -1376,7 +1376,7 @@ class GrampletPane(Gtk.ScrolledWindow): gramplet.scrolledwindow.set_size_request(-1, gramplet.height) ## now drop it in right place if self._popup_xy is not None: - self.drop_widget(self, gramplet, + self.drop_widget(self, gramplet, self._popup_xy[0], self._popup_xy[1], 0) else: self.drop_widget(self, gramplet, 0, 0, 0) @@ -1399,7 +1399,7 @@ class GrampletPane(Gtk.ScrolledWindow): cnt += 1 all_opts["title"] = unique if all_opts["title"] not in self.gramplet_map: - g = make_requested_gramplet(GridGramplet, self, all_opts, + g = make_requested_gramplet(GridGramplet, self, all_opts, self.dbstate, self.uistate) if g: self.gramplet_map[all_opts["title"]] = g @@ -1415,7 +1415,7 @@ class GrampletPane(Gtk.ScrolledWindow): gramplet.scrolledwindow.set_size_request(-1, gramplet.height) ## now drop it in right place if self._popup_xy is not None: - self.drop_widget(self, gramplet, + self.drop_widget(self, gramplet, self._popup_xy[0], self._popup_xy[1], 0) else: self.drop_widget(self, gramplet, 0, 0, 0) @@ -1477,7 +1477,7 @@ class GrampletPane(Gtk.ScrolledWindow): self.gramplet_map[title].pui.update() def on_delete(self): - gramplets = (g for g in self.gramplet_map.values() + gramplets = (g for g in self.gramplet_map.values() if g is not None) for gramplet in gramplets: # this is the only place where the gui runs user code directly @@ -1495,18 +1495,18 @@ class GrampletPane(Gtk.ScrolledWindow): def _get_configure_page_funcs(self): """ - Return a list of functions that create gtk elements to use in the + Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog - + :return: list of functions """ def generate_pages(): return [self.config_panel] + \ - [self.build_panel(gramplet) for gramplet in - sorted(list(self.gramplet_map.values()), key=lambda g: g.title) + [self.build_panel(gramplet) for gramplet in + sorted(list(self.gramplet_map.values()), key=lambda g: g.title) if gramplet.gstate != "closed"] return generate_pages - + def get_columns(self): return self.column_count @@ -1524,26 +1524,26 @@ class GrampletPane(Gtk.ScrolledWindow): self.get_columns, # pane self.set_columns) # pane - configdialog.add_pos_int_entry(grid, - _('Number of Columns'), - 0, + configdialog.add_pos_int_entry(grid, + _('Number of Columns'), + 0, 'Gramplet View Options.column_count', self._config.set, config=self._config) return _('Gramplet Layout'), grid - + def build_panel(self, gramplet): - self._config.register("%s.title" % gramplet.title, + self._config.register("%s.title" % gramplet.title, str, gramplet.get_title, gramplet.set_title) - self._config.register("%s.height" % gramplet.title, + self._config.register("%s.height" % gramplet.title, int, gramplet.get_height, gramplet.set_height) - self._config.register("%s.detached_height" % gramplet.title, + self._config.register("%s.detached_height" % gramplet.title, int, gramplet.get_detached_height, gramplet.set_detached_height) - self._config.register("%s.detached_width" % gramplet.title, + self._config.register("%s.detached_width" % gramplet.title, int, gramplet.get_detached_width, gramplet.set_detached_width) - self._config.register("%s.expand" % gramplet.title, + self._config.register("%s.expand" % gramplet.title, bool, gramplet.get_expand, gramplet.set_expand) def gramplet_panel(configdialog): configdialog.window.set_size_request(600, -1) @@ -1552,36 +1552,36 @@ class GrampletPane(Gtk.ScrolledWindow): grid.set_column_spacing(6) grid.set_row_spacing(6) # Title: - configdialog.add_entry(grid, - _('Title'), - 0, + configdialog.add_entry(grid, + _('Title'), + 0, "%s.title" % gramplet.title, self._config.set, config=self._config) # Expand to max height - configdialog.add_checkbox(grid, - _("Use maximum height available"), - 1, - "%s.expand" % gramplet.title, + configdialog.add_checkbox(grid, + _("Use maximum height available"), + 1, + "%s.expand" % gramplet.title, config=self._config) # Height - configdialog.add_pos_int_entry(grid, - _('Height if not maximized'), - 2, + configdialog.add_pos_int_entry(grid, + _('Height if not maximized'), + 2, "%s.height" % gramplet.title, self._config.set, config=self._config) # Detached height - configdialog.add_pos_int_entry(grid, - _('Detached width'), - 3, + configdialog.add_pos_int_entry(grid, + _('Detached width'), + 3, "%s.detached_width" % gramplet.title, self._config.set, config=self._config) # Detached width - configdialog.add_pos_int_entry(grid, - _('Detached height'), - 4, + configdialog.add_pos_int_entry(grid, + _('Detached height'), + 4, "%s.detached_height" % gramplet.title, self._config.set, config=self._config) diff --git a/gramps/gui/widgets/interactivesearchbox.py b/gramps/gui/widgets/interactivesearchbox.py index 920ef8862..8dd0a86c5 100644 --- a/gramps/gui/widgets/interactivesearchbox.py +++ b/gramps/gui/widgets/interactivesearchbox.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -487,7 +487,7 @@ class InteractiveSearchBox(): """ Search among the currently set search-column for a cell starting with text - It assumes that this column is currently sorted, and as + It assumes that this column is currently sorted, and as a LIST_ONLY view it therefore contains index2hndl = model.node_map._index2hndl which is a _sorted_ list of (sortkey, handle) tuples """ diff --git a/gramps/gui/widgets/labels.py b/gramps/gui/widgets/labels.py index 76f9dc597..93b84417f 100644 --- a/gramps/gui/widgets/labels.py +++ b/gramps/gui/widgets/labels.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -79,7 +79,7 @@ class LinkLabel(Gtk.EventBox): self.emph = emph GObject.GObject.__init__(self) - + st_cont = self.get_style_context() col = st_cont.lookup_color('link_color') if col[0]: @@ -123,7 +123,7 @@ class LinkLabel(Gtk.EventBox): 'Click Edit icon (enable in configuration dialog) to edit') self.set_tooltip_text(msg) - + self.label = Gtk.Label(label=text) self.label.set_use_markup(True) self.label.set_halign(Gtk.Align.START) @@ -143,7 +143,7 @@ class LinkLabel(Gtk.EventBox): def set_padding(self, x, y): self.label.set_padding(x, y) - + def enter_text(self, obj, event, handle): if self.emph: #emphasize a link @@ -171,7 +171,7 @@ class LinkLabel(Gtk.EventBox): format = 'underline="single" foreground="' + self.color + '"' else: raise AttributeError("invalid theme: '%s'" % theme) - + text = '%s' % (format, self.orig_text) self.label.set_text(text) self.label.set_use_markup(True) diff --git a/gramps/gui/widgets/linkbox.py b/gramps/gui/widgets/linkbox.py index adf36e83d..d3fabd868 100644 --- a/gramps/gui/widgets/linkbox.py +++ b/gramps/gui/widgets/linkbox.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. diff --git a/gramps/gui/widgets/menuitem.py b/gramps/gui/widgets/menuitem.py index a72b448b2..2f4a2304b 100644 --- a/gramps/gui/widgets/menuitem.py +++ b/gramps/gui/widgets/menuitem.py @@ -44,15 +44,15 @@ from gi.repository import Gtk # #------------------------------------------------------------------------- - + class MenuItemWithData(Gtk.MenuItem): - """ A MenuItem that stores a data property. As set_data in GTK3 is not + """ A MenuItem that stores a data property. As set_data in GTK3 is not working, this is a workaround to have set_data""" data = GObject.Property(type=object) def __init__(self, label=''): GObject.GObject.__init__(self, label=label) - + def set_data(self, data): self.data = data diff --git a/gramps/gui/widgets/monitoredwidgets.py b/gramps/gui/widgets/monitoredwidgets.py index 47d5f4514..0c14497ac 100644 --- a/gramps/gui/widgets/monitoredwidgets.py +++ b/gramps/gui/widgets/monitoredwidgets.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -__all__ = ["MonitoredCheckbox", "MonitoredEntry", +__all__ = ["MonitoredCheckbox", "MonitoredEntry", "MonitoredEntryIndicator", "MonitoredSpinButton", "MonitoredText", "MonitoredType", "MonitoredDataType", "MonitoredMenu", "MonitoredStrMenu", "MonitoredDate", @@ -94,7 +94,7 @@ class MonitoredCheckbox(object): ## self.set_val = None ## self.get_val = None ## self.obj = None - + #------------------------------------------------------------------------- # # MonitoredEntry class @@ -102,7 +102,7 @@ class MonitoredCheckbox(object): #------------------------------------------------------------------------- class MonitoredEntry(object): - def __init__(self, obj, set_val, get_val, read_only=False, + def __init__(self, obj, set_val, get_val, read_only=False, autolist=None, changed=None): self.obj = obj self.set_val = set_val @@ -132,7 +132,7 @@ class MonitoredEntry(object): def set_text(self, text): self.obj.set_text(text) - + def connect(self, signal, callback, *data): self.obj.connect(signal, callback, *data) @@ -165,10 +165,10 @@ class MonitoredEntry(object): #------------------------------------------------------------------------- class MonitoredEntryIndicator(MonitoredEntry): """ - Show an Entry box with an indicator in it that disappears when + Show an Entry box with an indicator in it that disappears when entry becomes active """ - def __init__(self, obj, set_val, get_val, indicator, read_only=False, + def __init__(self, obj, set_val, get_val, indicator, read_only=False, autolist=None, changed=None): MonitoredEntry.__init__(self, obj, set_val, get_val, read_only, autolist, changed) @@ -183,9 +183,9 @@ class MonitoredEntryIndicator(MonitoredEntry): Gdk.RGBA.parse(rgba, 'grey') self.obj.override_color(Gtk.StateType.NORMAL, rgba) self.obj.override_font(Pango.FontDescription('sans italic')) - self.fockey = self.obj.connect('focus-in-event', + self.fockey = self.obj.connect('focus-in-event', self._obj_focus) - + def _on_change(self, obj): if not self.indicatorshown: self.set_val(str(obj.get_text())) @@ -223,7 +223,7 @@ class MonitoredSpinButton(object): :param get_val: callback to be called to retrieve value for obj :param read_only: If SpinButton is read only. """ - + self.obj = obj self.set_val = set_val self.get_val = get_val @@ -252,7 +252,7 @@ class MonitoredSpinButton(object): :param set_val: callback to be called when SpinButton is changed :param get_val: callback to be called to retrieve value for SpinButton """ - + self.set_val = set_val self.get_val = get_val self.update() @@ -263,9 +263,9 @@ class MonitoredSpinButton(object): :param value: Value to be set. """ - + self.obj.set_value(value) - + def connect(self, signal, callback): """ Connect the signal of monitored widget to the specified callback. @@ -273,7 +273,7 @@ class MonitoredSpinButton(object): :param signal: Signal prototype for which a connection should be set up. :param callback: Callback function to be called when signal is emitted. """ - + self.obj.connect(signal, callback) def _on_change(self, obj): @@ -283,7 +283,7 @@ class MonitoredSpinButton(object): :param obj: Widget that has been changed. :type obj: Gtk.SpinButton """ - + self.set_val(obj.get_value()) if self.changed: self.changed(obj) @@ -294,7 +294,7 @@ class MonitoredSpinButton(object): :param value: Value to be set. """ - + self.obj.set_value(value) def get_value(self): @@ -314,7 +314,7 @@ class MonitoredSpinButton(object): :param value: If widget should be editable or deactivated. :type value: bool """ - + self.obj.set_sensitive(value) self.obj.set_editable(value) @@ -322,7 +322,7 @@ class MonitoredSpinButton(object): """ Assign the keyboard focus to the monitored widget. """ - + self.obj.grab_focus() def update(self): @@ -330,7 +330,7 @@ class MonitoredSpinButton(object): Updates value of monitored SpinButton with the value returned by the get_val callback. """ - + if self.get_val(): self.obj.set_value(self.get_val()) @@ -370,7 +370,7 @@ class MonitoredText(object): #------------------------------------------------------------------------- class MonitoredType(object): - def __init__(self, obj, set_val, get_val, mapping, custom, readonly=False, + def __init__(self, obj, set_val, get_val, mapping, custom, readonly=False, custom_values=None): self.set_val = set_val self.get_val = get_val @@ -416,9 +416,9 @@ class MonitoredType(object): # #------------------------------------------------------------------------- class MonitoredDataType(object): - - def __init__(self, obj, set_val, get_val, readonly=False, + + def __init__(self, obj, set_val, get_val, readonly=False, custom_values=None, ignore_values=None): """ Constructor for the MonitoredDataType class. @@ -437,7 +437,7 @@ class MonitoredDataType(object): :type custom_values: list of str, tuple or GrampsType :param ignore_values: list of values not to show in the combobox. If the result of get_val is in these, it is not ignored - :type ignore_values: list of int + :type ignore_values: list of int """ self.set_val = set_val self.get_val = get_val @@ -450,7 +450,7 @@ class MonitoredDataType(object): default = int(val) else: default = None - + map = get_val().get_map().copy() if ignore_values : for key in list(map.keys()): @@ -458,10 +458,10 @@ class MonitoredDataType(object): del map[key] self.sel = StandardCustomSelector( - map, - obj, - get_val().get_custom(), - default, + map, + obj, + get_val().get_custom(), + default, additional=custom_values, menu=get_val().get_menu()) @@ -506,7 +506,7 @@ class MonitoredDataType(object): #------------------------------------------------------------------------- class MonitoredMenu(object): - def __init__(self, obj, set_val, get_val, mapping, + def __init__(self, obj, set_val, get_val, mapping, readonly=False, changed=None): self.set_val = set_val self.get_val = get_val @@ -558,7 +558,7 @@ class MonitoredStrMenu(object): self.obj = obj self.model = Gtk.ListStore(GObject.TYPE_STRING) - + # Make sure that the menu is visible on small screen devices. # Some LDS temples were not visible on a 4 or 5 column layout. # See bug #7333 @@ -571,14 +571,14 @@ class MonitoredStrMenu(object): default = get_val() active = 0 - + for t, v in mapping: self.model.append(row=[v]) self.data.append(t) index += 1 if t == default: active = index - + self.obj.set_model(self.model) self.obj.set_active(active) self.obj.connect('changed', self.on_change) @@ -611,7 +611,7 @@ class MonitoredDate(object): Create a connection between the date_obj, text_obj and the pixmap_obj. Assigns callbacks to parse and change date when the text in text_obj is changed, and to invoke Date Editor when the LED - button_obj is pressed. + button_obj is pressed. """ self.uistate = uistate self.track = track @@ -624,24 +624,24 @@ class MonitoredDate(object): self.button_obj.set_image(image) self.button_obj.set_relief(Gtk.ReliefStyle.NORMAL) self.pixmap_obj = self.button_obj.get_child() - + self.text_obj.connect('validate', self.validate) self.text_obj.connect('content-changed', self.set_date) self.button_obj.connect('clicked', self.invoke_date_editor) - + self.text_obj.set_text(displayer.display(self.date_obj)) self.text_obj.validate() self.text_obj.set_editable(not readonly) self.button_obj.set_sensitive(not readonly) - + def set_date(self, widget): """ Parse date from text entry to date object """ date = parser.parse(str(self.text_obj.get_text())) self.date_obj.copy(date) - + def validate(self, widget, data): """ Validate current date in text entry @@ -684,7 +684,7 @@ class MonitoredComboSelectedEntry(object): A MonitoredEntry driven by a Combobox to select what the entry field works upon """ - def __init__(self, objcombo, objentry, textlist, set_val_list, + def __init__(self, objcombo, objentry, textlist, set_val_list, get_val_list, default=0, read_only=False): """ Create a MonitoredComboSelectedEntry @@ -699,14 +699,14 @@ class MonitoredComboSelectedEntry(object): self.objentry = objentry self.set_val_list = set_val_list self.get_val_list = get_val_list - + #fill the combobox, set on a specific entry self.mapping = dict([[i,x] for (i,x) in zip(list(range(len(textlist))), textlist)]) self.active_key = default self.active_index = 0 - + self.__fill() self.objcombo.clear() self.objcombo.set_model(self.store) @@ -715,11 +715,11 @@ class MonitoredComboSelectedEntry(object): self.objcombo.add_attribute(cell, 'text', 1) self.objcombo.set_active(self.active_index) self.objcombo.connect('changed', self.on_combochange) - + #fill the entrybox with required data self.entry_reinit() self.objentry.connect('changed', self._on_change_entry) - + #set correct editable self.enable(not read_only) @@ -760,13 +760,13 @@ class MonitoredComboSelectedEntry(object): def on_combochange(self, obj): """ - callback for change on the combo, change active iter, update + callback for change on the combo, change active iter, update associated entrybox """ self.active_key = self.store.get_value(self.objcombo.get_active_iter(), 0) self.entry_reinit() - + def reinit(self, set_val_list, get_val_list): """ The interface is attached to another object, so the methods need to be diff --git a/gramps/gui/widgets/multitreeview.py b/gramps/gui/widgets/multitreeview.py index e3e8221fa..d3cc8edca 100644 --- a/gramps/gui/widgets/multitreeview.py +++ b/gramps/gui/widgets/multitreeview.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -62,7 +62,7 @@ class MultiTreeView(Gtk.TreeView): # Here we intercept mouse clicks on selected items so that we can # drag multiple items without the click selecting only one target = self.get_path_at_pos(int(event.x), int(event.y)) - if (target + if (target and event.type == Gdk.EventType.BUTTON_PRESS and not (event.get_state() & (Gdk.ModifierType.CONTROL_MASK|Gdk.ModifierType.SHIFT_MASK)) and self.get_selection().path_is_selected(target[0])): @@ -73,12 +73,12 @@ class MultiTreeView(Gtk.TreeView): def on_button_release(self, widget, event): # re-enable selection self.get_selection().set_select_function(lambda *ignore: True, None) - - target = self.get_path_at_pos(int(event.x), int(event.y)) - if (self.defer_select and target + + target = self.get_path_at_pos(int(event.x), int(event.y)) + if (self.defer_select and target and self.defer_select == target[0] and not (event.x==0 and event.y==0)): # certain drag and drop self.set_cursor(target[0], target[1], False) - + self.defer_select=False diff --git a/gramps/gui/widgets/photo.py b/gramps/gui/widgets/photo.py index 80d0cc631..6fe6929da 100644 --- a/gramps/gui/widgets/photo.py +++ b/gramps/gui/widgets/photo.py @@ -85,7 +85,7 @@ class Photo(Gtk.EventBox): if self.handle and self.uistate: self.menu = Gtk.Menu() self.menu.set_title(_("Media Object")) - add_menuitem(self.menu, _("Make Active Media"), widget, + add_menuitem(self.menu, _("Make Active Media"), widget, lambda obj: self.uistate.set_active(self.handle, "Media")) self.menu.popup(None, None, None, None, event.button, event.time) return True diff --git a/gramps/gui/widgets/placeentry.py b/gramps/gui/widgets/placeentry.py index d517d165e..0df565aa3 100644 --- a/gramps/gui/widgets/placeentry.py +++ b/gramps/gui/widgets/placeentry.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -48,7 +48,7 @@ from ..selectors import SelectorFactory # #------------------------------------------------------------------------- class PlaceEntry(Gtk.Box): - + def __init__(self, dbstate, uistate, track): Gtk.Box.__init__(self) self.dbstate = dbstate @@ -59,7 +59,7 @@ class PlaceEntry(Gtk.Box): self.pack_start(self.entry, True, True, 0) image = Gtk.Image() image.set_from_icon_name('gtk-index', Gtk.IconSize.BUTTON) - button = Gtk.Button() + button = Gtk.Button() button.set_image(image) button.set_relief(Gtk.ReliefStyle.NORMAL) self.pack_start(button, False, True, 0) diff --git a/gramps/gui/widgets/progressdialog.py b/gramps/gui/widgets/progressdialog.py index 7bfb2ddf7..752a04a11 100644 --- a/gramps/gui/widgets/progressdialog.py +++ b/gramps/gui/widgets/progressdialog.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -18,7 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ -This module provides a progress dialog for displaying the status of +This module provides a progress dialog for displaying the status of long running operations. """ @@ -58,13 +58,13 @@ class LongOpStatus(Callback): LongOpStatus provides a way of communicating the status of a long running operations. The intended use is that when a long running operation is about to start it should create an instance of this class and emit - it so that any listeners can pick it up and use it to record the status + it so that any listeners can pick it up and use it to record the status of the operation. **Signals** - - * op-heartbeat - emitted every 'interval' calls to heartbeat. + + * op-heartbeat - emitted every 'interval' calls to heartbeat. * op-end - emitted once when the operation completes. Example usage:: @@ -74,7 +74,7 @@ class LongOpStatus(Callback): __signals__ = { 'op-start' : object } - + def long(self): status = LongOpStatus("doing long job", 100, 10) @@ -83,7 +83,7 @@ class LongOpStatus(Callback): status.heartbeat() status.end() - + class MyListener(object): def __init__(self): @@ -108,21 +108,21 @@ class LongOpStatus(Callback): 'op-end' : None } - def __init__(self, msg="", - total_steps=None, + def __init__(self, msg="", + total_steps=None, interval=1, can_cancel=False): """ :param msg: A Message to indicated the purpose of the operation. :type msg: string - :param total_steps: The total number of steps that the operation + :param total_steps: The total number of steps that the operation will perform. :type total_steps: :param interval: The number of iterations between emissions. :type interval: :param can_cancel: Set to True if the operation can be cancelled. If this is set the operation that creates the status - object should check the 'should_cancel' method + object should check the 'should_cancel' method regularly so that it can cancel the operation. :type can_cancel: """ @@ -130,9 +130,9 @@ class LongOpStatus(Callback): self._msg = msg self._total_steps = total_steps # don't allow intervals less that 1 - self._interval = max(interval, 1) + self._interval = max(interval, 1) self._can_cancel = can_cancel - + self._cancel = False self._count = 0 self._countdown = interval @@ -143,11 +143,11 @@ class LongOpStatus(Callback): def __del__(self): if self._running: self.emit('op-end') - + def heartbeat(self): """This should be called for each step in the operation. It will emit a 'op-heartbeat' every 'interval' steps. It recalcuates the - 'estimated_secs_to_complete' from the time taken for previous + 'estimated_secs_to_complete' from the time taken for previous steps. """ self._countdown -= 1 @@ -163,16 +163,16 @@ class LongOpStatus(Callback): def step(self): """ - Convenience function so LongOpStatus can be used as a ProgressBar + Convenience function so LongOpStatus can be used as a ProgressBar if set up correctly """ self.heartbeat() def estimated_secs_to_complete(self): """ - Return the number of seconds estimated left before operation + Return the number of seconds estimated left before operation completes. This will change as 'hearbeat' is called. - + :returns: estimated seconds to complete. :rtype: int """ @@ -193,7 +193,7 @@ class LongOpStatus(Callback): def end(self): """ - End the operation. Causes the 'op-end' signal to be emitted. + End the operation. Causes the 'op-end' signal to be emitted. """ self.emit('op-end') self._running = False @@ -201,7 +201,7 @@ class LongOpStatus(Callback): def should_cancel(self): """ Return true of the user has asked for the operation to be cancelled. - + :returns: True of the operation should be cancelled. :rtype: bool """ @@ -221,22 +221,22 @@ class LongOpStatus(Callback): """ return self._msg - def set_msg(self, msg): + def set_msg(self, msg): """ Set the current description message. - + :param msg: The description message. :type msg: string """ self._msg = msg - + def get_total_steps(self): """ - Get to total number of steps. NOTE: this is not the + Get to total number of steps. NOTE: this is not the number of times that the 'op-heartbeat' message will be emited. 'op-heartbeat' is emited get_total_steps/interval times. - + :returns: total number of steps. :rtype: int """ @@ -245,7 +245,7 @@ class LongOpStatus(Callback): def get_interval(self): """ Get the interval between 'op-hearbeat' signals. - + :returns: the interval between 'op-hearbeat' signals. :rtype: int """ @@ -261,10 +261,10 @@ class _StatusObjectFacade(object): This provides a simple structure for recording the information needs about a status object. """ - + def __init__(self, status_obj, heartbeat_cb_id=None, end_cb_id=None): """ - :param status_obj: + :param status_obj: :type status_obj: :class:`.LongOpStatus` :param heartbeat_cb_id: (default: None) :type heartbeat_cb_id: int @@ -285,16 +285,16 @@ class _StatusObjectFacade(object): class ProgressMonitor(object): """ A dialog for displaying the status of long running operations. - - It will work with :class:`.LongOpStatus` objects to track the - progress of long running operations. If the operations is going to - take longer than *popup_time* it will pop up a dialog with a - progress bar so that the user gets some feedback about what is + + It will work with :class:`.LongOpStatus` objects to track the + progress of long running operations. If the operations is going to + take longer than *popup_time* it will pop up a dialog with a + progress bar so that the user gets some feedback about what is happening. """ - + __default_popup_time = 5 # seconds - + def __init__(self, dialog_class, dialog_class_params=(), title=_("Progress Information"), popup_time = None): @@ -315,69 +315,69 @@ class ProgressMonitor(object): self._dialog_class_params = dialog_class_params self._title = title self._popup_time = popup_time - + if self._popup_time is None: self._popup_time = self.__class__.__default_popup_time - + self._status_stack = [] # list of current status objects self._dlg = None - + def _get_dlg(self): if self._dlg is None: self._dlg = self._dialog_class(self._dialog_class_params, self._title) - + #self._dlg.show() - + return self._dlg - + def add_op(self, op_status): """ Add a new status object to the progress dialog. - - :param op_status: the status object. + + :param op_status: the status object. :type op_status: :class:`.LongOpStatus` """ - + log.debug("adding op to Progress Monitor") facade = _StatusObjectFacade(op_status) self._status_stack.append(facade) idx = len(self._status_stack)-1 - + # wrap up the op_status object idx into the callback calls def heartbeat_cb(): self._heartbeat(idx) def end_cb(): self._end(idx) - - facade.heartbeat_cb_id = op_status.connect('op-heartbeat', + + facade.heartbeat_cb_id = op_status.connect('op-heartbeat', heartbeat_cb) facade.end_cb_id = op_status.connect('op-end', end_cb) - + def _heartbeat(self, idx): # check the estimated time to complete to see if we need # to pop up a progress dialog. - + log.debug("heartbeat in ProgressMonitor") - + if idx >= len(self._status_stack): # this item has been cancelled return facade = self._status_stack[idx] - + if facade.status_obj.estimated_secs_to_complete() > self._popup_time: facade.active = True - + if facade.active: dlg = self._get_dlg() - + if facade.pbar_idx is None: facade.pbar_idx = dlg.add(facade.status_obj) - + dlg.show() dlg.step(facade.pbar_idx) - + def _end(self, idx): # hide any progress dialog # remove the status object from the stack @@ -393,18 +393,18 @@ class ProgressMonitor(object): facade = self._status_stack[idx] if facade.active: dlg = self._get_dlg() - + if len(self._status_stack) == 1: dlg.hide() - + dlg.remove(facade.pbar_idx) - + facade.status_obj.disconnect(facade.heartbeat_cb_id) facade.status_obj.disconnect(facade.end_cb_id) del self._status_stack[idx] if len(self._status_stack) == 0 and self._dlg: self._dlg.close() - + #------------------------------------------------------------------------- # # _GtkProgressBar @@ -415,45 +415,45 @@ class _GtkProgressBar(Gtk.Box): This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar. """ - + def __init__(self, long_op_status): """ :param long_op_status: the status of the operation. :type long_op_status: :class:`.LongOpStatus` """ Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL) - + msg = long_op_status.get_msg() self._old_val = -1 self._lbl = Gtk.Label(label=msg) self._lbl.set_use_markup(True) #self.set_border_width(24) - + self._pbar = Gtk.ProgressBar() self._hbox = Gtk.Box() - + # Only display the cancel button is the operation # can be canceled. if long_op_status.can_cancel(): self._cancel = Gtk.Button.new_with_mnemonic(_('_Cancel')) - self._cancel.connect("clicked", + self._cancel.connect("clicked", lambda x: long_op_status.cancel()) self._cancel.show() self._hbox.pack_end(self._cancel, False, True, 0) - + self._hbox.pack_start(self._pbar, True, True, 0) - + self.pack_start(self._lbl, False, False, 0) self.pack_start(self._hbox, False, False, 0) - - + + self._pbar_max = (long_op_status.get_total_steps()/ long_op_status.get_interval()) self._pbar_index = 0.0 self._pbar.set_fraction(((100/float(long_op_status.get_total_steps())* float(long_op_status.get_interval())))/ 100.0) - + if msg != '': self._lbl.show() self._pbar.show() @@ -464,7 +464,7 @@ class _GtkProgressBar(Gtk.Box): Move the progress bar on a step. """ self._pbar_index = self._pbar_index + 1.0 - + if self._pbar_index > self._pbar_max: self._pbar_index = self._pbar_max @@ -488,7 +488,7 @@ class GtkProgressDialog(Gtk.Dialog): A gtk window to display the status of a long running process. """ - + def __init__(self, window_params, title): """ :param title: The title to display on the top of the window. @@ -510,36 +510,36 @@ class GtkProgressDialog(Gtk.Dialog): self.set_title(title) #self.set_resize_mode(Gtk.RESIZE_IMMEDIATE) #self.show() - + self._progress_bars = [] - + def add(self, long_op_status): """ Add a new status object to the progress dialog. - - :param long_op_status: the status object. + + :param long_op_status: the status object. :type long_op_status: :class:`.LongOpStatus` :returns: a key that can be used as the ``pbar_idx`` to the other methods. :rtype: int """ pbar = _GtkProgressBar(long_op_status) - + self.vbox.pack_start(pbar, False, False, 0) - + pbar.show() # this seems to cause an infinite loop: #self.resize_children() - + self._progress_bars.append(pbar) # This is a bad idea; could cause deletes while adding: #self._process_events() return len(self._progress_bars)-1 - + def remove(self, pbar_idx): """ Remove the specified status object from the progress dialog. - + :param pbar_idx: the index as returned from :meth:`add` :type pbar_idx: int """ @@ -547,19 +547,19 @@ class GtkProgressDialog(Gtk.Dialog): pbar = self._progress_bars[pbar_idx] self.vbox.remove(pbar) del self._progress_bars[pbar_idx] - + def step(self, pbar_idx): """ Click the progress bar over to the next value. Be paranoid and insure that it doesn't go over 100%. - + :param pbar_idx: the index as returned from :meth:`add` :type pbar_idx: int """ if pbar_idx < len(self._progress_bars): - self._progress_bars[pbar_idx].step() + self._progress_bars[pbar_idx].step() self._process_events() - + def _process_events(self): while Gtk.events_pending(): Gtk.main_iteration() @@ -570,39 +570,39 @@ class GtkProgressDialog(Gtk.Dialog): """ Gtk.Dialog.show(self) self._process_events() - + def hide(self): """ Hide the dialog and process any events. """ Gtk.Dialog.hide(self) self._process_events() - + def _warn(self, x, y): return True - + def close(self): self.destroy() - + if __name__ == '__main__': - + def test(a, b): d = ProgressMonitor(GtkProgressDialog) - + s = LongOpStatus("Doing very long operation", 100, 10, can_cancel=True) - + d.add_op(s) - + for i in range(0, 99): if s.should_cancel(): break time.sleep(0.1) if i == 30: - t = LongOpStatus("doing a shorter one", 100, 10, + t = LongOpStatus("doing a shorter one", 100, 10, can_cancel=True) d.add_op(t) for j in range(0, 99): - if s.should_cancel(): + if s.should_cancel(): t.cancel() break if t.should_cancel(): @@ -624,7 +624,7 @@ if __name__ == '__main__': s.heartbeat() if not s.was_cancelled(): s.end() - + w = Gtk.Window(Gtk.WindowType.TOPLEVEL) w.connect('destroy', Gtk.main_quit) button = Gtk.Button("Test") diff --git a/gramps/gui/widgets/reorderfam.py b/gramps/gui/widgets/reorderfam.py index 06029e676..e85627911 100644 --- a/gramps/gui/widgets/reorderfam.py +++ b/gramps/gui/widgets/reorderfam.py @@ -61,7 +61,7 @@ class Reorder(ManagedWindow): """ Interface to reorder the families a person is parent in """ - + def __init__(self, state, uistate, track, handle): xml = Glade('reorder.glade') top = xml.toplevel @@ -79,15 +79,15 @@ class Reorder(ManagedWindow): self.set_window(top, None, _("Reorder Relationships")) self.ptree = xml.get_object('ptree') - self.pmodel = ListModel(self.ptree, - [(_('Father'), -1, 200), - (_('Mother'), -1, 200), + self.pmodel = ListModel(self.ptree, + [(_('Father'), -1, 200), + (_('Mother'), -1, 200), ('', -1, 0)]) self.ftree = xml.get_object('ftree') - self.fmodel = ListModel(self.ftree, - [(_('Spouse'), -1, 200), - (_('Relationship'), -1, 200), + self.fmodel = ListModel(self.ftree, + [(_('Spouse'), -1, 200), + (_('Relationship'), -1, 200), ('', -1, 0)]) xml.get_object('ok').connect('clicked', self.ok_clicked) diff --git a/gramps/gui/widgets/selectionwidget.py b/gramps/gui/widgets/selectionwidget.py index 37faff741..365f23ec1 100644 --- a/gramps/gui/widgets/selectionwidget.py +++ b/gramps/gui/widgets/selectionwidget.py @@ -73,7 +73,7 @@ def scale_to_fit(orig_x, orig_y, target_x, target_y): def resize_keep_aspect(orig_x, orig_y, target_x, target_y): """ Calculates the dimensions of the rectangle obtained from - the rectangle orig_x * orig_y by scaling to fit + the rectangle orig_x * orig_y by scaling to fit target_x * target_y keeping the aspect ratio. """ orig_aspect = orig_x / orig_y @@ -419,7 +419,7 @@ class SelectionWidget(Gtk.ScrolledWindow): if w >= 1 and h >= 1 and self.pixbuf: subpixbuf = self.pixbuf.new_subpixbuf(region.x1, region.y1, w, h) size = resize_keep_aspect(w, h, *thumbnail_size) - return subpixbuf.scale_simple(size[0], size[1], + return subpixbuf.scale_simple(size[0], size[1], GdkPixbuf.InterpType.BILINEAR) else: return None @@ -476,12 +476,12 @@ class SelectionWidget(Gtk.ScrolledWindow): offset_y = (image_rect[1] - viewport_rect.height) / 2 else: offset_y = 0.0 - return (int(coords[0] * self.scale - offset_x), + return (int(coords[0] * self.scale - offset_x), int(coords[1] * self.scale - offset_y)) def _screen_to_image(self, coords): """ - Translates viewport coordinates to original (unscaled) image coordinates + Translates viewport coordinates to original (unscaled) image coordinates using the current scale and viewport size. """ viewport_rect = self.viewport.get_allocation() @@ -494,7 +494,7 @@ class SelectionWidget(Gtk.ScrolledWindow): offset_y = (image_rect[1] - viewport_rect.height) / 2 else: offset_y = 0.0 - return (int((coords[0] + offset_x) / self.scale), + return (int((coords[0] + offset_x) / self.scale), int((coords[1] + offset_y) / self.scale)) def _truncate_to_image_size(self, coords): @@ -557,7 +557,7 @@ class SelectionWidget(Gtk.ScrolledWindow): x1, y1, x2, y2 = self._rect_image_to_screen(self.selection) # transparent shading - self._draw_transparent_shading(cr, x1, y1, x2, y2, w, h, + self._draw_transparent_shading(cr, x1, y1, x2, y2, w, h, offset_x, offset_y) # selection frame @@ -571,7 +571,7 @@ class SelectionWidget(Gtk.ScrolledWindow): x1, y1, x2, y2 = self._rect_image_to_screen(region.coords()) self._draw_region_frame(cr, x1, y1, x2, y2) - def _draw_transparent_shading(self, cr, x1, y1, x2, y2, w, h, + def _draw_transparent_shading(self, cr, x1, y1, x2, y2, w, h, offset_x, offset_y): """ Draws the shading for a selection box. @@ -631,7 +631,7 @@ class SelectionWidget(Gtk.ScrolledWindow): Recalculates the sizes using the current scale and updates the buffers. """ - self.scaled_size = (int(self.original_image_size[0] * self.scale), + self.scaled_size = (int(self.original_image_size[0] * self.scale), int(self.original_image_size[1] * self.scale)) self.scaled_image = self.pixbuf.scale_simple(self.scaled_size[0], self.scaled_size[1], @@ -704,7 +704,7 @@ class SelectionWidget(Gtk.ScrolledWindow): self.emit("selection-cleared") elif self.grabber != INSIDE: # clicked on one of the grabbers - dx, dy = (event.x - self.start_point_screen[0], + dx, dy = (event.x - self.start_point_screen[0], event.y - self.start_point_screen[1]) self.grabber_to_draw = self._modify_selection(dx, dy) self.current.set_coords(*self.selection) @@ -744,7 +744,7 @@ class SelectionWidget(Gtk.ScrolledWindow): # selection or dragging (mouse button pressed) if self.grabber is not None and self.grabber != INSIDE: # dragging the grabber - dx, dy = (event.x - self.start_point_screen[0], + dx, dy = (event.x - self.start_point_screen[0], event.y - self.start_point_screen[1]) self.grabber_to_draw = self._modify_selection(dx, dy) elif self._can_select(): diff --git a/gramps/gui/widgets/shortlistcomboentry.py b/gramps/gui/widgets/shortlistcomboentry.py index 26141ff7d..ad1085ce9 100644 --- a/gramps/gui/widgets/shortlistcomboentry.py +++ b/gramps/gui/widgets/shortlistcomboentry.py @@ -69,14 +69,14 @@ class ShortlistComboEntry(ValidatedComboEntry): """A ComboboxEntry class with optional shortlist. """ __gtype_name__ = "ShortlistComboEntry" - + def __init__(self, items, shortlist=True, validator=None): if not items: raise ValueError - + data_type = items[0].__class__ gtype = _GTYPE.get(data_type, GObject.TYPE_PYOBJECT) - + # create the model and insert the items model = Gtk.ListStore(gtype, GObject.TYPE_BOOLEAN) maxlen = -1 @@ -84,7 +84,7 @@ class ShortlistComboEntry(ValidatedComboEntry): if len(str(item)) > maxlen: maxlen = len(str(item)) model.append((item, False)) - + width = -1 #default width if 1 < maxlen < 4: width = 4 @@ -95,20 +95,20 @@ class ShortlistComboEntry(ValidatedComboEntry): if shortlist: self._shortlist = [] self.connect("changed", self._on_combobox_changed) - + self.set_row_separator_func(self._is_row_separator, None) - + def _on_combobox_changed(self, combobox): if self._internal_change: return - + if self.get_active_iter(): model = self.get_model() # if first item on shortlist insert a separator row if not self._shortlist: model.prepend((None, True)) - + # remove the existing shortlist from the model iter = model.get_iter_first() for n in range(len(self._shortlist)): @@ -119,7 +119,7 @@ class ShortlistComboEntry(ValidatedComboEntry): self._shortlist.remove(self._active_data) self._shortlist.append(self._active_data) self._shortlist = self._shortlist[-5:] - + # prepend shortlist to model for data in self._shortlist: model.prepend((data, False)) diff --git a/gramps/gui/widgets/springseparator.py b/gramps/gui/widgets/springseparator.py index a28a27be9..c90e8c2d2 100644 --- a/gramps/gui/widgets/springseparator.py +++ b/gramps/gui/widgets/springseparator.py @@ -45,19 +45,19 @@ from gi.repository import Gtk #------------------------------------------------------------------------- class SpringSeparatorToolItem(Gtk.SeparatorToolItem): """Custom separator toolitem. - + Its only purpose is to push following tool items to the right end of the toolbar. - + """ __gtype_name__ = "SpringSeparatorToolItem" - + def __init__(self): GObject.GObject.__init__(self) - + self.set_draw(False) self.set_expand(True) - + #------------------------------------------------------------------------- # # SpringSeparatorAction class @@ -65,9 +65,9 @@ class SpringSeparatorToolItem(Gtk.SeparatorToolItem): #------------------------------------------------------------------------- class SpringSeparatorAction(Gtk.Action): """Custom Action to hold a SpringSeparatorToolItem.""" - + __gtype_name__ = "SpringSeparatorAction" - + def __init__(self, name, label, tooltip, stock_id): GObject.GObject.__init__(self, name=name, label=label, tooltip=tooltip, stock_id=stock_id) diff --git a/gramps/gui/widgets/statusbar.py b/gramps/gui/widgets/statusbar.py index 770acab69..df1632af4 100644 --- a/gramps/gui/widgets/statusbar.py +++ b/gramps/gui/widgets/statusbar.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -47,7 +47,7 @@ from . import WarnButton #------------------------------------------------------------------------- class Statusbar(Gtk.Box): """ - A status bar + A status bar """ def __init__(self): Gtk.Box.__init__(self) diff --git a/gramps/gui/widgets/styledtextbuffer.py b/gramps/gui/widgets/styledtextbuffer.py index 7218566be..316dfd2a9 100644 --- a/gramps/gui/widgets/styledtextbuffer.py +++ b/gramps/gui/widgets/styledtextbuffer.py @@ -114,7 +114,7 @@ class LinkTag(Gtk.TextTag): class GtkSpellState(object): """ A simple state machine kinda thingy. - + Trying to track Gtk.Spell activities on a buffer and re-apply formatting after Gtk.Spell replaces a misspelled word. """ @@ -126,20 +126,20 @@ class GtkSpellState(object): def __init__(self, textbuffer): if not isinstance(textbuffer, Gtk.TextBuffer): raise TypeError("Init parameter must be instance of Gtk.TextBuffer") - + textbuffer.connect('mark-set', self.on_buffer_mark_set) textbuffer.connect('delete-range', self.on_buffer_delete_range) textbuffer.connect('insert-text', self.on_buffer_insert_text) textbuffer.connect_after('insert-text', self.after_buffer_insert_text) - + self.reset_state() - + def reset_state(self): self.state = self.STATE_NONE self.start = 0 self.end = 0 self.tags = None - + def on_buffer_mark_set(self, textbuffer, iter, mark): mark_name = mark.get_name() if mark_name == 'gtkspell-click': @@ -156,7 +156,7 @@ class GtkSpellState(object): (end.get_offset() == self.end)): self.state = self.STATE_DELETED self.tags = start.get_tags() - + def on_buffer_insert_text(self, textbuffer, iter, text, length): if self.state == self.STATE_DELETED and iter.get_offset() == self.start: self.state = self.STATE_INSERTING @@ -167,13 +167,13 @@ class GtkSpellState(object): insert_start = textbuffer.get_iter_at_mark(mark) for tag in self.tags: textbuffer.apply_tag(tag, insert_start, iter) - + self.reset_state() def get_word_extents_from_mark(self, textbuffer, mark): """ Get the word extents as Gtk.Spell does. - + Used to get the beginning of the word, in which user right clicked. Formatting found at that position used after Gtk.Spell replaces misspelled words. @@ -187,26 +187,26 @@ class GtkSpellState(object): #end.forward_word_end() self.forward_word_end(end) return start.get_offset(), end.get_offset() - + def forward_word_end(self, iter): """ Gtk.Spell style Gtk.TextIter.forward_word_end. - + The parameter 'iter' is changing as side effect. """ if not iter.forward_word_end(): return False - + if iter.get_char() != "'": return True - + i = iter.copy() if i.forward_char(): if i.get_char().isalpha(): return iter.forward_word_end() - + return True - + def backward_word_start(self, iter): """ Gtk.Spell style Gtk.TextIter.backward_word_start. @@ -215,16 +215,16 @@ class GtkSpellState(object): """ if not iter.backward_word_start(): return False - + i = iter.copy() if i.backward_char(): if i.get_char() == "'": if i.backward_char(): if i.get_char().isalpha(): return iter.backward_word_start() - + return True - + #------------------------------------------------------------------------- # # StyledTextBuffer class @@ -233,20 +233,20 @@ class GtkSpellState(object): class StyledTextBuffer(UndoableBuffer): """ An extended TextBuffer for handling :class:`.StyledText` strings. - + StyledTextBuffer is an interface between GRAMPS' :class:`.StyledText` format - and Gtk.TextBuffer. To set and get the text use the :meth:`set_text` and + and Gtk.TextBuffer. To set and get the text use the :meth:`set_text` and :meth:`get_text` methods. - + To set a style to (a portion of) the text (e.g. from GUI) use the :meth:`apply_style` and :meth:`remove_style` methods. - + To receive information about the style of the text at the cursor position StyledTextBuffer provides two mechanism: message driven and polling. To receive notification of style change as cursor moves connect to the ``style-changed`` signal. To get the value of a certain style at the cursor use the :meth:`get_style_at_cursor` method. - + StyledTextBuffer has a regexp pattern matching mechanism too. To add a regexp pattern to match in the text use the :meth:`match_add` method. To check if there's a match at a certain position in the text use the @@ -254,12 +254,12 @@ class StyledTextBuffer(UndoableBuffer): :class:`.EditNote`. """ __gtype_name__ = 'StyledTextBuffer' - + __gsignals__ = { - 'style-changed': (GObject.SignalFlags.RUN_FIRST, + 'style-changed': (GObject.SignalFlags.RUN_FIRST, None, #return value (GObject.TYPE_PYOBJECT,)), # arguments - } + } def __init__(self): super(StyledTextBuffer, self).__init__() @@ -271,39 +271,39 @@ class StyledTextBuffer(UndoableBuffer): self.create_tag(str(StyledTextTagType.ITALIC), style=STYLE_ITALIC) self.create_tag(str(StyledTextTagType.UNDERLINE), underline=UNDERLINE_SINGLE) - + # internal format state attributes ## 1. are used to format inserted characters (self.after_insert_text) ## 2. are set each time the Insert marker is set (self.do_mark_set) ## 3. are set when a style is set (self._apply_style_to_selection) self.style_state = StyledTextTagType.STYLE_DEFAULT.copy() - + # internally used attribute self._insert = self.get_insert() - + # create a mark used for text formatting start, end = self.get_bounds() self.mark_insert = self.create_mark('insert-start', start, True) - + # pattern matching attributes self.patterns = [] self.matches = [] - + # hook up on some signals whose default handler cannot be overriden self.connect('insert-text', self.on_insert_text) self.connect_after('insert-text', self.after_insert_text) self.connect_after('delete-range', self.after_delete_range) - + self.linkcolor = 'blue' # init gtkspell "state machine" self.gtkspell_state = GtkSpellState(self) - + # Virtual methods def on_insert_text(self, textbuffer, iter, text, length): _LOG.debug("Will insert at %d length %d" % (iter.get_offset(), length)) - + # let's remember where we started inserting self.move_mark(self.mark_insert, iter) @@ -311,10 +311,10 @@ class StyledTextBuffer(UndoableBuffer): """Format inserted text.""" _LOG.debug("Have inserted at %d length %d (%s)" % (iter.get_offset(), length, text)) - + if not length: return - + # where did we start inserting insert_start = self.get_iter_at_mark(self.mark_insert) @@ -324,14 +324,14 @@ class StyledTextBuffer(UndoableBuffer): if value and (value != StyledTextTagType.STYLE_DEFAULT[style]): self.apply_tag(self._find_tag_by_name(style, value), insert_start, iter) - + def after_delete_range(self, textbuffer, start, end): _LOG.debug("Deleted from %d till %d" % (start.get_offset(), end.get_offset())) - + # move 'insert' marker to have the format attributes updated self.move_mark(self._insert, start) - + def do_changed(self, data=None): """Parse for patterns in the text.""" self.matches = [] @@ -355,16 +355,16 @@ class StyledTextBuffer(UndoableBuffer): """Update style state each time the cursor moves.""" _LOG.debug("Setting mark %s at %d" % (mark.get_name(), iter.get_offset())) - + if mark.get_name() != 'insert': return - + if not iter.starts_line(): iter.backward_char() - + tag_names = [tag.get_property('name') for tag in iter.get_tags()] changed_styles = {} - + for style in ALLOWED_STYLES: if StyledTextTagType.STYLE_TYPE[style] == bool: value = str(style) in tag_names @@ -374,21 +374,21 @@ class StyledTextBuffer(UndoableBuffer): if tname.startswith(str(style)): value = tname.split(' ', 1)[1] value = StyledTextTagType.STYLE_TYPE[style](value) - + if self.style_state[style] != value: changed_styles[style] = value - + self.style_state[style] = value - + if changed_styles: self.emit('style-changed', changed_styles) # Private - + ##def get_tag_value_at_insert(self, name): ##"""Get the value of the given tag at the insertion point.""" ##tags = self.get_iter_at_mark(self._insert).get_tags() - + ##if name in self.toggle_actions: ##for tag in tags: ##if tag.get_name() == name: @@ -426,12 +426,12 @@ class StyledTextBuffer(UndoableBuffer): selection = self._get_selection() if selection: self.remove_tag(tag, *selection) - + def _apply_style_to_selection(self, style, value): # FIXME can this be unified? if StyledTextTagType.STYLE_TYPE[style] == bool: start, end = self._get_selection() - + if value: self.apply_tag_by_name(str(style), start, end) else: @@ -482,16 +482,16 @@ class StyledTextBuffer(UndoableBuffer): start, end) removed_something = True return removed_something - + def _get_tag_from_range(self, start=None, end=None): """ Extract Gtk.TextTags from buffer. - + Return only the name of the TextTag from the specified range. If range is not given, tags extracted from the whole buffer. - + :note: TextTag names are always composed like: (%s %s) % (style, value) - + :param start: an offset pointing to the start of the range of text :param type: int :param end: an offset pointing to the end of the range of text @@ -503,7 +503,7 @@ class StyledTextBuffer(UndoableBuffer): start = 0 if end is None: end = self.get_char_count() - + tagdict = {} iter = self.get_iter_at_offset(start) for pos in range(start, end): @@ -522,7 +522,7 @@ class StyledTextBuffer(UndoableBuffer): def _find_tag_by_name(self, style, value): """ Fetch TextTag from buffer's tag table by it's name. - + If TextTag does not exist yet, it is created. """ if style not in StyledTextTagType.STYLE_TYPE: @@ -536,7 +536,7 @@ class StyledTextBuffer(UndoableBuffer): else: raise ValueError("Unknown style (%s) value type: %s" % (style, value.__class__)) - + tag = self.get_tag_table().lookup(tag_name) if not tag: @@ -553,17 +553,17 @@ class StyledTextBuffer(UndoableBuffer): def set_text(self, s_text): """ Set the content of the buffer with markup tags. - + .. note:: ``s_`` prefix means StyledText*, while ``g_`` prefix means Gtk.*. """ super(StyledTextBuffer, self).set_text(str(s_text)) #self.remove_all_tags(self.get_start_iter(), self.get_end_iter()) - + s_tags = s_text.get_tags() for s_tag in s_tags: if s_tag.name == _('Link'): - g_tag = LinkTag(self, s_tag.value, + g_tag = LinkTag(self, s_tag.value, foreground=self.linkcolor, underline=UNDERLINE_SINGLE) else: @@ -573,11 +573,11 @@ class StyledTextBuffer(UndoableBuffer): start_iter = self.get_iter_at_offset(start) end_iter = self.get_iter_at_offset(end) self.apply_tag(g_tag, start_iter, end_iter) - + def get_text(self, start=None, end=None, include_hidden_chars=True): """ Return the buffer text. - + .. note:: ``s_`` prefix means StyledText*, while ``g_`` prefix means Gtk.*. """ @@ -586,14 +586,14 @@ class StyledTextBuffer(UndoableBuffer): if end is None: end = self.get_end_iter() - txt = super(StyledTextBuffer, self).get_text(start, end, + txt = super(StyledTextBuffer, self).get_text(start, end, include_hidden_chars) txt = str(txt) - + # extract tags out of the buffer g_tags = self._get_tag_from_range() s_tags = [] - + for g_tagname, g_ranges in g_tags.items(): if g_tagname.startswith('link'): tag = self.get_tag_table().lookup(g_tagname) @@ -621,11 +621,11 @@ class StyledTextBuffer(UndoableBuffer): _LOG.debug("silently skipping Gtk.TextTag '%s'" % g_tagname) return StyledText(txt, s_tags) - + def apply_style(self, style, value): """ Apply a style with the given value to the selection. - + :param style: style type to apply :type style: :class:`.StyledTextTagStyle` int value :param value: value of the style type @@ -637,16 +637,16 @@ class StyledTextBuffer(UndoableBuffer): value.__class__)) self._apply_style_to_selection(style, value) - + def remove_style(self, style): """ Delete all occurences with any value of the given style. - + :param style: style type to apply :type style: :class:`.StyledTextTagStyle` int value """ self._remove_style_from_selection(style) - + def get_style_at_cursor(self, style): """ Get the actual value of the given style at the cursor position. @@ -657,7 +657,7 @@ class StyledTextBuffer(UndoableBuffer): :rtype: depends on the ``style`` type """ return self.style_state[style] - + def match_add(self, pattern, flavor): """Add a pattern to look for in the text.""" regex = re.compile(pattern) diff --git a/gramps/gui/widgets/styledtexteditor.py b/gramps/gui/widgets/styledtexteditor.py index f8854ebbc..91acd2183 100644 --- a/gramps/gui/widgets/styledtexteditor.py +++ b/gramps/gui/widgets/styledtexteditor.py @@ -77,8 +77,8 @@ if has_display(): FORMAT_TOOLBAR = ''' - - + + @@ -134,14 +134,14 @@ def find_parent_with_attr(self, attr="dbstate"): class StyledTextEditor(Gtk.TextView): """ StyledTextEditor is an enhanced Gtk.TextView to edit :class:`.StyledText`. - + StyledTextEditor is a gui object for :class:`.StyledTextBuffer`. It offers - :meth:`set_text` and :meth:`get_text` convenience methods to set and get the + :meth:`set_text` and :meth:`get_text` convenience methods to set and get the buffer's text. - + StyledTextEditor provides a formatting toolbar, which can be retrieved by the :meth:`get_toolbar` method. - + StyledTextEdit defines a new signal: 'match-changed', which is raised whenever the mouse cursor reaches or leaves a matched string in the text. The feature uses the regexp pattern mathing mechanism of @@ -149,7 +149,7 @@ class StyledTextEditor(Gtk.TextView): The signal's default handler highlights the URL strings. URL's can be followed from the editor's popup menu or by pressing the Left mouse button. - + :ivar last_match: previously matched string, used for generating the 'match-changed' signal. :type last_match: tuple or None @@ -164,16 +164,16 @@ class StyledTextEditor(Gtk.TextView): :type toolbar: Gtk.Toolbar :ivar url_match: stores the matched URL and other mathing parameters. :type url_match: tuple or None - + """ __gtype_name__ = 'StyledTextEditor' - + __gsignals__ = { - 'match-changed': (GObject.SignalFlags.RUN_FIRST, + 'match-changed': (GObject.SignalFlags.RUN_FIRST, None, #return value (GObject.TYPE_PYOBJECT,)), # arguments } - + def __init__(self): """Setup initial instance variable values.""" self.textbuffer = UndoableStyledBuffer() @@ -206,16 +206,16 @@ class StyledTextEditor(Gtk.TextView): self.selclick = False # virtual methods - + def do_match_changed(self, match): """ Default signal handler. - + URL highlighting. - + :param match: the new match parameters :type match: tuple or None - + .. warning:: Do not override the handler, but connect to the signal. """ window = self.get_window(Gtk.TextWindowType.TEXT) @@ -224,7 +224,7 @@ class StyledTextEditor(Gtk.TextView): if match and (match[MATCH_FLAVOR] in (GENURL, HTTP, MAIL)): start_offset = match[MATCH_START] end_offset = match[MATCH_END] - + start = self.textbuffer.get_iter_at_offset(start_offset) end = self.textbuffer.get_iter_at_offset(end_offset) @@ -237,15 +237,15 @@ class StyledTextEditor(Gtk.TextView): else: window.set_cursor(REGULAR_CURSOR) self.url_match = None - + def on_key_press_event(self, widget, event): """Signal handler. - + Handle formatting shortcuts. - + """ if ((Gdk.keyval_name(event.keyval) == 'Z') and - (event.get_state() & Gdk.ModifierType.CONTROL_MASK) and + (event.get_state() & Gdk.ModifierType.CONTROL_MASK) and (event.get_state() & Gdk.ModifierType.SHIFT_MASK)): self.redo() return True @@ -262,23 +262,23 @@ class StyledTextEditor(Gtk.TextView): action.activate() return True return False - + def on_insert_at_cursor(self, widget, string): """Signal handler. for debugging only.""" _LOG.debug("Textview insert '%s'" % string) - + def on_delete_from_cursor(self, widget, mode, count): """Signal handler. for debugging only.""" _LOG.debug("Textview delete type %d count %d" % (mode, count)) - + def on_paste_clipboard(self, widget): """Signal handler. for debugging only.""" _LOG.debug("Textview paste clipboard") - + def on_motion_notify_event(self, widget, event): """ Signal handler. - + As the mouse cursor moves the handler checks if there's a new regexp match at the new location. If match changes the 'match-changed' signal is raised. @@ -294,7 +294,7 @@ class StyledTextEditor(Gtk.TextView): self.match = (x, y, LINK, tag.data, tag) tooltip = self.make_tooltip_from_link(tag) break - + if self.match != self.last_match: self.emit('match-changed', self.match) @@ -327,16 +327,16 @@ class StyledTextEditor(Gtk.TextView): event.button == 1): bounds = self.textbuffer.get_selection_bounds() if bounds: - clip = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clip = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_PRIMARY) - clip.set_text(str(self.textbuffer.get_text(bounds[0], + clip.set_text(str(self.textbuffer.get_text(bounds[0], bounds[1], True)), -1) return False - + def on_button_press_event(self, widget, event): """ Signal handler. - + Handles the + Left click over a URL match. """ self.selclick=False @@ -344,7 +344,7 @@ class StyledTextEditor(Gtk.TextView): (event.button == 1) and (event.get_state() and Gdk.ModifierType.CONTROL_MASK) and (self.url_match)): - + flavor = self.url_match[MATCH_FLAVOR] url = self.url_match[MATCH_STRING] self._open_url_cb(None, url, flavor) @@ -357,9 +357,9 @@ class StyledTextEditor(Gtk.TextView): def on_populate_popup(self, widget, menu): """ Signal handler. - + Insert extra menuitems: - + 1. Insert spellcheck selector submenu for spell checking. 2. Insert extra menus depending on ULR match result. """ @@ -368,7 +368,7 @@ class StyledTextEditor(Gtk.TextView): spell_menu.set_submenu(self._create_spell_menu()) spell_menu.show_all() menu.prepend(spell_menu) - + search_menu = Gtk.MenuItem(label=_("Search selection on web")) search_menu.connect('activate', self.search_web) search_menu.show_all() @@ -378,7 +378,7 @@ class StyledTextEditor(Gtk.TextView): if self.url_match: flavor = self.url_match[MATCH_FLAVOR] url = self.url_match[MATCH_STRING] - + if flavor == MAIL: open_menu = Gtk.MenuItem(label=_('_Send Mail To...')) open_menu.set_use_underline(True) @@ -393,7 +393,7 @@ class StyledTextEditor(Gtk.TextView): if flavor == LINK: edit_menu = Gtk.MenuItem(label=_('_Edit Link')) edit_menu.set_use_underline(True) - edit_menu.connect('activate', self._edit_url_cb, + edit_menu.connect('activate', self._edit_url_cb, self.url_match[-1], # tag ) edit_menu.show() @@ -403,7 +403,7 @@ class StyledTextEditor(Gtk.TextView): copy_menu.show() menu.prepend(copy_menu) - + open_menu.connect('activate', self._open_url_cb, url, flavor) open_menu.show() menu.prepend(open_menu) @@ -414,9 +414,9 @@ class StyledTextEditor(Gtk.TextView): """ selection = self.textbuffer.get_selection_bounds() if len(selection) > 0: - display_url(config.get("behavior.web-search-url") % - {'text': - self.textbuffer.get_text(selection[0], + display_url(config.get("behavior.web-search-url") % + {'text': + self.textbuffer.get_text(selection[0], selection[1], True)}) def reset(self): @@ -428,7 +428,7 @@ class StyledTextEditor(Gtk.TextView): self.redo_action.set_sensitive(False) # private methods - + def _connect_signals(self): """Connect to several signals of the super class Gtk.TextView.""" self.connect('key-press-event', self.on_key_press_event) @@ -439,11 +439,11 @@ class StyledTextEditor(Gtk.TextView): self.connect('button-press-event', self.on_button_press_event) self.connect('button-release-event', self.on_button_release_event) self.connect('populate-popup', self.on_populate_popup) - + def _create_toolbar(self): """ Create a formatting toolbar. - + :returns: toolbar containing text formatting toolitems. :rtype: Gtk.Toolbar """ @@ -457,7 +457,7 @@ class StyledTextEditor(Gtk.TextView): (str(StyledTextTagType.UNDERLINE), 'format-text-underline', None, None, _('Underline'), self._on_toggle_action_activate), ] - + self.toggle_actions = [action[0] for action in format_toggle_actions] # ...then the normal actions, which have a ToolButton as proxy @@ -471,10 +471,10 @@ class StyledTextEditor(Gtk.TextView): ('clear', 'edit-clear', None, None, _('Clear Markup'), self._format_clear_cb), ] - + # ...last the custom actions, which have custom proxies default = StyledTextTagType.STYLE_DEFAULT[StyledTextTagType.FONTFACE] - fonts = SystemFonts() + fonts = SystemFonts() fontface_action = ValueAction(str(StyledTextTagType.FONTFACE), _("Font family"), default, @@ -498,7 +498,7 @@ class StyledTextEditor(Gtk.TextView): fontsize_action.connect('changed', self._on_valueaction_changed) spring = SpringSeparatorAction("spring", "", "", None) - + # action accelerators self.action_accels = { 'i': str(StyledTextTagType.ITALIC), @@ -523,21 +523,21 @@ class StyledTextEditor(Gtk.TextView): self.action_group.add_action(fontface_action) self.action_group.add_action(fontsize_action) self.action_group.add_action(spring) - + # define the toolbar and create the proxies via ensure_update() uimanager = Gtk.UIManager() uimanager.insert_action_group(self.action_group, 0) uimanager.add_ui_from_string(FORMAT_TOOLBAR) uimanager.ensure_update() - + # get the toolbar and set it's style - toolbar = uimanager.get_widget('/ToolBar') + toolbar = uimanager.get_widget('/ToolBar') toolbar.set_style(Gtk.ToolbarStyle.ICONS) self.undo_action.set_sensitive(False) self.redo_action.set_sensitive(False) return toolbar - + def _init_url_match(self): """Setup regexp matching for URL match.""" self.textbuffer.create_tag('hyperlink', @@ -551,14 +551,14 @@ class StyledTextEditor(Gtk.TextView): URLPATH + ")?/?", HTTP) self.textbuffer.match_add("(mailto:)?[a-z0-9][a-z0-9.-]*@[a-z0-9]" "[a-z0-9-]*(\\.[a-z0-9][a-z0-9-]*)+", MAIL) - + def _create_spell_menu(self): """ Create a menu with all the installed spellchecks. - + It is called each time the popup menu is opened. Each spellcheck forms a radio menu item, and the selected spellcheck is set as active. - + :returns: menu containing all the installed spellchecks. :rtype: Gtk.Menu """ @@ -571,18 +571,18 @@ class StyledTextEditor(Gtk.TextView): menuitem.set_active(lang == active_spellcheck) menuitem.connect('activate', self._spell_change_cb, lang) menu.append(menuitem) - + if group is None: group = menuitem - + return menu # Callback functions - + def _on_toggle_action_activate(self, action): """ Toggle a style. - + Toggle styles are e.g. 'bold', 'italic', 'underline'. """ if self._internal_style_change: @@ -601,13 +601,13 @@ class StyledTextEditor(Gtk.TextView): selection_bounds = self.textbuffer.get_selection_bounds() if selection_bounds: # Paste text to clipboards - text = str(self.textbuffer.get_text(selection_bounds[0], + text = str(self.textbuffer.get_text(selection_bounds[0], selection_bounds[1], True)) - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_CLIPBOARD) clipboard.set_text(text, -1) - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_PRIMARY) clipboard.set_text(text, -1) uri_dialog(self, None, self.setlink_callback) @@ -619,9 +619,9 @@ class StyledTextEditor(Gtk.TextView): if uri: _LOG.debug("applying style 'link' with value '%s'" % uri) if not tag: - tag = LinkTag(self.textbuffer, + tag = LinkTag(self.textbuffer, data=uri, - underline=Pango.Underline.SINGLE, + underline=Pango.Underline.SINGLE, foreground=self.linkcolor) selection_bounds = self.textbuffer.get_selection_bounds() self.textbuffer.apply_tag(tag, @@ -655,7 +655,7 @@ class StyledTextEditor(Gtk.TextView): int(rgba.green * 255), int(rgba.blue * 255)) color_dialog.destroy() - + if response == Gtk.ResponseType.OK: _LOG.debug("applying style '%d' with value '%s'" % (style, str(value))) @@ -665,7 +665,7 @@ class StyledTextEditor(Gtk.TextView): """Apply a format set by a ValueAction type of action.""" if self._internal_style_change: return - + style = int(action.get_name()) value = action.get_value() @@ -681,7 +681,7 @@ class StyledTextEditor(Gtk.TextView): def _format_clear_cb(self, action): """ Remove all formats from the selection or from all. - + Remove only our own tags without touching other ones (e.g. Gtk.Spell), thus remove_all_tags() can not be used. """ @@ -691,7 +691,7 @@ class StyledTextEditor(Gtk.TextView): self.textbuffer.remove_style(style) start, end = self.textbuffer.get_bounds() - tags = self.textbuffer._get_tag_from_range(start.get_offset(), + tags = self.textbuffer._get_tag_from_range(start.get_offset(), end.get_offset()) for tag_name, tag_data in tags.items(): if tag_name.startswith("link"): @@ -713,14 +713,14 @@ class StyledTextEditor(Gtk.TextView): self._internal_style_change = True action.set_active(style_value) self._internal_style_change = False - + if ((style == StyledTextTagType.FONTFACE) or (style == StyledTextTagType.FONTSIZE)): action = self.action_group.get_action(str(style)) self._internal_style_change = True action.set_value(style_value) self._internal_style_change = False - + def _spell_change_cb(self, menuitem, spellcheck): """Set spell checker spellcheck according to user selection.""" self.spellcheck.set_active_spellcheck(spellcheck) @@ -729,7 +729,7 @@ class StyledTextEditor(Gtk.TextView): """Open the URL in a browser.""" if not url: return - + if flavor == HTTP: url = 'http:' + url elif flavor == MAIL: @@ -747,9 +747,9 @@ class StyledTextEditor(Gtk.TextView): # Edit the object: obj_class, prop, value = url[9:].split("/") from ..editors import EditObject - EditObject(win_obj.dbstate, - win_obj.uistate, - win_obj.track, + EditObject(win_obj.dbstate, + win_obj.uistate, + win_obj.track, obj_class, prop, value) return else: @@ -760,14 +760,14 @@ class StyledTextEditor(Gtk.TextView): display_url(url, obj.uistate) else: display_url(url) - + def _copy_url_cb(self, menuitem, url, flavor): """Copy url to both useful selections.""" - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_CLIPBOARD) clipboard.set_text(url, -1) - - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_PRIMARY) clipboard.set_text(url, -1) @@ -780,21 +780,21 @@ class StyledTextEditor(Gtk.TextView): bounds = self.textbuffer.get_selection_bounds() if bounds: text = str(self.textbuffer.get_text(bounds[0], bounds[1], True)) - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_CLIPBOARD) clipboard.set_text(text, -1) - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_PRIMARY) clipboard.set_text(text, -1) - uri_dialog(self, link_tag.data, + uri_dialog(self, link_tag.data, lambda uri: self.setlink_callback(uri, link_tag)) - + # public methods - + def set_text(self, text): """ Set the text of the text buffer of the editor. - + :param text: formatted text to edit in the view. :type text: :class:`.StyledText` """ @@ -804,17 +804,17 @@ class StyledTextEditor(Gtk.TextView): def get_text(self): """ Get the text of the text buffer of the editor. - + :returns: the formatted text from the editor. :rtype: :class:`.StyledText` """ start, end = self.textbuffer.get_bounds() return self.textbuffer.get_text(start, end, True) - + def get_toolbar(self): """ Get the formatting toolbar of the editor. - + :returns: toolbar widget to use as formatting GUI. :rtype: Gtk.Toolbar """ @@ -837,7 +837,7 @@ def uri_dialog(self, uri, callback): # make a default link uri = "http://" # Check in order for an open page: - for object_class in ["Person", "Place", "Event", "Family", + for object_class in ["Person", "Place", "Event", "Family", "Repository", "Source", "Media"]: handle = obj.uistate.get_active(object_class) if handle: diff --git a/gramps/gui/widgets/toolcomboentry.py b/gramps/gui/widgets/toolcomboentry.py index 17d6e4b2c..a881866cf 100644 --- a/gramps/gui/widgets/toolcomboentry.py +++ b/gramps/gui/widgets/toolcomboentry.py @@ -54,22 +54,22 @@ from .shortlistcomboentry import ShortlistComboEntry class ToolComboEntry(ValueToolItem): """Tool bar item containing a ShortlistComboEntry widget.""" __gtype_name__ = "ToolComboEntry" - + def _create_widget(self, items, editable, shortlist=True, validator=None): self.set_border_width(2) self.set_homogeneous(False) self.set_expand(False) - + combo = ShortlistComboEntry(items, shortlist, validator) combo.set_focus_on_click(False) combo.set_entry_editable(editable) combo.show() self.add(combo) - + combo.connect('changed', self._on_widget_changed) def set_value(self, value): self.get_child().set_active_data(value) - + def get_value(self): return self.get_child().get_active_data() diff --git a/gramps/gui/widgets/undoablebuffer.py b/gramps/gui/widgets/undoablebuffer.py index ed0cb671b..c93eff715 100644 --- a/gramps/gui/widgets/undoablebuffer.py +++ b/gramps/gui/widgets/undoablebuffer.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -20,8 +20,8 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -""" -gtk textbuffer with undo functionality +""" +gtk textbuffer with undo functionality """ __all__ = ["UndoableBuffer"] @@ -34,8 +34,8 @@ from gi.repository import Gtk class Stack(list): """ - Very simple stack implementation that cannot grow beyond an at init - determined size. + Very simple stack implementation that cannot grow beyond an at init + determined size. Inherits from list. Only append checks if this is really the case! """ @@ -87,10 +87,10 @@ class UndoableBuffer(Gtk.TextBuffer): at least as far as undo is concerned""" insertclass = UndoableInsert deleteclass = UndoableDelete - + #how many undo's are remembered undo_stack_size = 700 - + def __init__(self): """ we'll need empty stacks for undo/redo and some state keeping @@ -157,7 +157,7 @@ class UndoableBuffer(Gtk.TextBuffer): else: self.undo_stack.append(prev_insert) self.undo_stack.append(undo_action) - + def on_delete_range_undoable(self, text_buffer, start_iter, end_iter): def can_be_merged(prev, cur): """ @@ -213,16 +213,16 @@ class UndoableBuffer(Gtk.TextBuffer): def begin_not_undoable_action(self): """don't record the next actions - + toggles self.not_undoable_action""" - self.not_undoable_action = True + self.not_undoable_action = True def end_not_undoable_action(self): """record next actions - + toggles self.not_undoable_action""" self.not_undoable_action = False - + def reset(self): """ Resets buffer to initial state. @@ -306,7 +306,7 @@ class UndoableBuffer(Gtk.TextBuffer): def _handle_redo(self, redo_action): raise NotImplementedError -## for test, run script as +## for test, run script as ## PYTHONPATH=$PYTHONPATH:~/gramps/trunk/src/ python gui/widgets/undoablebuffer.py if __name__ == '__main__': test = Stack(5) @@ -314,7 +314,7 @@ if __name__ == '__main__': print('WRONG: test is empty') else: print('CORRECT: test is empty') - + test.append(0);test.append(1);test.append(2);test.append(3);test.append(4); print('5 inserts', test) test.append(5);test.append(6);test.append(7);test.append(8);test.append(9); diff --git a/gramps/gui/widgets/undoableentry.py b/gramps/gui/widgets/undoableentry.py index c124e9253..dec21ff4c 100644 --- a/gramps/gui/widgets/undoableentry.py +++ b/gramps/gui/widgets/undoableentry.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -92,7 +92,7 @@ class UndoableEntry(Gtk.Entry): - Undo and Redo on CTRL-Z/CTRL-SHIFT-Z """ __gtype_name__ = 'UndoableEntry' - + insertclass = UndoableInsertEntry deleteclass = UndoableDeleteEntry @@ -121,10 +121,10 @@ class UndoableEntry(Gtk.Entry): def _on_key_press_event(self, widget, event): """Signal handler. Handle formatting undo/redo key press. - + """ if ((Gdk.keyval_name(event.keyval) == 'Z') and - (event.get_state() & Gdk.ModifierType.CONTROL_MASK) and + (event.get_state() & Gdk.ModifierType.CONTROL_MASK) and (event.get_state() & Gdk.ModifierType.SHIFT_MASK)): self.redo() return True @@ -165,7 +165,7 @@ class UndoableEntry(Gtk.Entry): self.__empty_redo_stack() if self.not_undoable_action: return - undo_action = self.insertclass(text, length, editable.get_position(), + undo_action = self.insertclass(text, length, editable.get_position(), editable) try: prev_insert = self.undo_stack.pop() @@ -239,16 +239,16 @@ class UndoableEntry(Gtk.Entry): def begin_not_undoable_action(self): """don't record the next actions - + toggles self.not_undoable_action""" - self.not_undoable_action = True + self.not_undoable_action = True def end_not_undoable_action(self): """record next actions - + toggles self.not_undoable_action""" self.not_undoable_action = False - + def reset(self): """ Resets buffer to initial state. diff --git a/gramps/gui/widgets/undoablestyledbuffer.py b/gramps/gui/widgets/undoablestyledbuffer.py index f1054fb36..7de415870 100644 --- a/gramps/gui/widgets/undoablestyledbuffer.py +++ b/gramps/gui/widgets/undoablestyledbuffer.py @@ -11,7 +11,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -21,8 +21,8 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -""" -gtk textbuffer with undo functionality +""" +gtk textbuffer with undo functionality """ __all__ = ["UndoableStyledBuffer"] @@ -40,7 +40,7 @@ class UndoableInsertStyled(UndoableInsert): def __init__(self, text_iter, text, length, text_buffer): #we obtain the buffer before the text has been inserted UndoableInsert.__init__(self, text_iter, text, length, text_buffer) - self.tags = text_buffer.get_text(text_buffer.get_start_iter(), + self.tags = text_buffer.get_text(text_buffer.get_start_iter(), text_buffer.get_end_iter(), True).get_tags() self.tagsafter = None @@ -48,16 +48,16 @@ class UndoableDeleteStyled(UndoableDelete): def __init__(self, text_buffer, start_iter, end_iter): #we obtain the buffer before the text has been deleted UndoableDelete.__init__(self, text_buffer, start_iter, end_iter) - self.tags = text_buffer.get_text(text_buffer.get_start_iter(), + self.tags = text_buffer.get_text(text_buffer.get_start_iter(), text_buffer.get_end_iter(), True).get_tags() class UndoableApplyStyle(): """a style has been applied to our textbuffer""" def __init__(self, text_buffer, tag, start, end): self.offset = text_buffer.get_iter_at_mark(text_buffer.get_insert()).get_offset() - + self.mergeable = False - self.tags = text_buffer.get_text(text_buffer.get_start_iter(), + self.tags = text_buffer.get_text(text_buffer.get_start_iter(), text_buffer.get_end_iter(), True).get_tags() # self.tags_after = None @@ -86,11 +86,11 @@ class UndoableStyledBuffer(StyledTextBuffer): Assures that not_undoable_action is False during the context. Usage example (see gramps/gui/widgets/styledtexteditor.py):: - + with self.buffer.undo_disabled(): ... # heavy stuff like spell checking """ - oldflag = self.not_undoable_action + oldflag = self.not_undoable_action self.not_undoable_action = True try: yield @@ -106,7 +106,7 @@ class UndoableStyledBuffer(StyledTextBuffer): return if end.get_offset() - start.get_offset() == 1: #only store this 1 character tag if in a different place - if self.undo_stack and isinstance(self.undo_stack[-1], + if self.undo_stack and isinstance(self.undo_stack[-1], UndoableInsertStyled) and self.undo_stack[-1].offset + \ self.undo_stack[-1].length == end.get_offset(): return @@ -119,7 +119,7 @@ class UndoableStyledBuffer(StyledTextBuffer): if not self.undo_stack or not isinstance(self.undo_stack[-1], UndoableApplyStyle): return - self.undo_stack[-1].set_after(buffer.get_text(buffer.get_start_iter(), + self.undo_stack[-1].set_after(buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter(), True).get_tags(), buffer.get_iter_at_mark(buffer.get_insert()).get_offset()) @@ -130,7 +130,7 @@ class UndoableStyledBuffer(StyledTextBuffer): ) self.delete(start, stop) #the text is correct again, now we create correct styled text - s_text = StyledText(Gtk.TextBuffer.get_text(self, + s_text = StyledText(Gtk.TextBuffer.get_text(self, self.get_start_iter(), self.get_end_iter(), True), undo_action.tags) self.set_text(s_text) self.place_cursor(self.get_iter_at_offset(undo_action.offset)) @@ -139,7 +139,7 @@ class UndoableStyledBuffer(StyledTextBuffer): start = self.get_iter_at_offset(undo_action.start) self.insert(start, undo_action.text) #the text is correct again, now we create correct styled text - s_text = StyledText(Gtk.TextBuffer.get_text(self, + s_text = StyledText(Gtk.TextBuffer.get_text(self, self.get_start_iter(), self.get_end_iter(), True), undo_action.tags) self.set_text(s_text) if undo_action.delete_key_used: @@ -148,7 +148,7 @@ class UndoableStyledBuffer(StyledTextBuffer): self.place_cursor(self.get_iter_at_offset(undo_action.end)) def _redo_insert(self, redo_action): - s_text = StyledText(Gtk.TextBuffer.get_text(self, + s_text = StyledText(Gtk.TextBuffer.get_text(self, self.get_start_iter(), self.get_end_iter(), True), redo_action.tags) self.set_text(s_text) start = self.get_iter_at_offset(redo_action.offset) @@ -163,22 +163,22 @@ class UndoableStyledBuffer(StyledTextBuffer): stop = self.get_iter_at_offset(redo_action.end) self.delete(start, stop) #the text is correct again, now we create correct styled text - #s_text = StyledText(Gtk.TextBuffer.get_text(self, + #s_text = StyledText(Gtk.TextBuffer.get_text(self, # self.get_start_iter(), self.get_end_iter(), True), redo_action.tags) #self.set_text(s_text) self.place_cursor(self.get_iter_at_offset(redo_action.start)) - + def _handle_undo(self, undo_action): """ undo of apply of style """ - s_text = StyledText(Gtk.TextBuffer.get_text(self, + s_text = StyledText(Gtk.TextBuffer.get_text(self, self.get_start_iter(), self.get_end_iter(), True), undo_action.tags) self.set_text(s_text) self.place_cursor(self.get_iter_at_offset(undo_action.offset)) def _handle_redo(self, redo_action): """ redo of apply of style """ - s_text = StyledText(Gtk.TextBuffer.get_text(self, - self.get_start_iter(), self.get_end_iter(), True), + s_text = StyledText(Gtk.TextBuffer.get_text(self, + self.get_start_iter(), self.get_end_iter(), True), redo_action.tags_after) self.set_text(s_text) self.place_cursor(self.get_iter_at_offset(redo_action.offset_after)) diff --git a/gramps/gui/widgets/validatedcomboentry.py b/gramps/gui/widgets/validatedcomboentry.py index 175615b87..9a1a5c56c 100644 --- a/gramps/gui/widgets/validatedcomboentry.py +++ b/gramps/gui/widgets/validatedcomboentry.py @@ -47,24 +47,24 @@ from gi.repository import Gtk class ValidatedComboEntry(Gtk.ComboBox): """ A ComboBoxEntry widget with validation. - + ValidatedComboEntry may have data type other then string, and is set with the ``datatype`` contructor parameter. - + Its behaviour is different from Gtk.ComboBoxEntry in the way how the entry part of the widget is handled. While Gtk.ComboBoxEntry - emits the 'changed' signal immediatelly the text in the entry is + emits the 'changed' signal immediatelly the text in the entry is changed, ValidatedComboEntry emits the signal only after the text is activated (enter is pressed, the focus is moved out) and validated. - + Validation function is an optional feature and activated only if a validator function is given at instantiation. - + The entry can be set as editable or not editable using the :meth:`set_entry_editable` method. """ __gtype_name__ = "ValidatedComboEntry" - + def __init__(self, datatype, model=None, column=-1, validator=None, width=-1): #GObject.GObject.__init__(self, model) Gtk.ComboBox.__init__(self, model=model) @@ -81,10 +81,10 @@ class ValidatedComboEntry(Gtk.ComboBox): # self.add(self._entry) self._entry.show() - + self._text_renderer = Gtk.CellRendererText() self.pack_start(self._text_renderer, False) - + self._data_type = datatype self._data_column = -1 self.set_data_column(column) @@ -92,60 +92,60 @@ class ValidatedComboEntry(Gtk.ComboBox): self._active_text = '' self._active_data = None self.set_active(-1) - + self._validator = validator - + self._entry.connect('activate', self._on_entry_activate) self._entry.connect('focus-in-event', self._on_entry_focus_in_event) self._entry.connect('focus-out-event', self._on_entry_focus_out_event) self._entry.connect('key-press-event', self._on_entry_key_press_event) self.connect('changed', self._on_changed) self._internal_change = False - + self._has_frame_changed() self.connect('notify', self._on_notify) # Virtual overriden methods - + def do_mnemonic_activate(self, group_cycling): self._entry.grab_focus() return True - + def do_grab_focus(self): self._entry.grab_focus() - + # Signal handlers - + def _on_entry_activate(self, entry): """ Signal handler. - + Called when the entry is activated. """ self._entry_changed(entry) - + def _on_entry_focus_in_event(self, widget, event): """ Signal handler. - + Called when the focus enters the entry, and is used for saving the entry's text for later comparison. """ self._text_on_focus_in = self._entry.get_text() - + def _on_entry_focus_out_event(self, widget, event): """ Signal handler. - + Called when the focus leaves the entry. """ if (self._entry.get_text() != self._text_on_focus_in): self._entry_changed(widget) - + def _on_entry_key_press_event(self, entry, event): """ Signal handler. - + Its purpose is to handle escape button. """ # FIXME Escape never reaches here, the dialog eats it, I assume. @@ -159,12 +159,12 @@ class ValidatedComboEntry(Gtk.ComboBox): def _on_changed(self, combobox): """ Signal handler. - + Called when the active row is changed in the combo box. """ if self._internal_change: return - + iter = self.get_active_iter() if iter: model = self.get_model() @@ -175,30 +175,30 @@ class ValidatedComboEntry(Gtk.ComboBox): def _on_notify(self, object, gparamspec): """ Signal handler. - + Called whenever a property of the object is changed. """ if gparamspec and gparamspec.name == 'has-frame': self._has_frame_changed() - + # Private methods - + def _entry_changed(self, entry): new_text = entry.get_text() - + try: new_data = self._data_type(new_text) - + if (self._validator is not None) and not self._validator(new_data): raise ValueError except ValueError: entry.set_text(self._active_text) entry.set_position(-1) return - + self._active_text = new_text self._active_data = new_data - + self._internal_change = True new_iter = self._is_in_model(new_data) if new_iter is None: @@ -210,18 +210,18 @@ class ValidatedComboEntry(Gtk.ComboBox): def _has_frame_changed(self): has_frame = self.get_property('has-frame') self._entry.set_has_frame(has_frame) - + def _is_in_model(self, data): """ Check if given data is in the model or not. - + :param data: data value to check :type data: depends on the actual data type of the object :returns: position of 'data' in the model :rtype: Gtk.TreeIter or None """ model = self.get_model() - + iter = model.get_iter_first() while iter: if model.get_value(iter, self._data_column) == data: @@ -231,25 +231,25 @@ class ValidatedComboEntry(Gtk.ComboBox): return iter # Public methods - + def set_data_column(self, data_column): if data_column < 0: return - + model = self.get_model() if model is None: return - + if data_column > model.get_n_columns(): return - + if self._data_column == -1: self._data_column = data_column self.add_attribute(self._text_renderer, "text", data_column) - + def get_data_column(self): return self._data_column - + def set_active_data(self, data): # set it via entry so that it will be also validated if self._entry: diff --git a/gramps/gui/widgets/validatedmaskedentry.py b/gramps/gui/widgets/validatedmaskedentry.py index 0099601ea..5f2b45af0 100644 --- a/gramps/gui/widgets/validatedmaskedentry.py +++ b/gramps/gui/widgets/validatedmaskedentry.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -69,14 +69,14 @@ class FadeOut(GObject.GObject): Call my methods :meth:`start` and :meth:`stop` to control the fading. """ __gsignals__ = { - 'done': (GObject.SignalFlags.RUN_FIRST, - None, - ()), - 'color-changed': (GObject.SignalFlags.RUN_FIRST, - None, - (Gdk.Color, )), + 'done': (GObject.SignalFlags.RUN_FIRST, + None, + ()), + 'color-changed': (GObject.SignalFlags.RUN_FIRST, + None, + (Gdk.Color, )), } - + # How long time it'll take before we start (in ms) COMPLAIN_DELAY = 500 @@ -107,8 +107,8 @@ class FadeOut(GObject.GObject): rs += rinc gs += ginc bs += binc - col = Gdk.color_parse("#%02X%02X%02X" % (int(rs) >> 8, - int(gs) >> 8, + col = Gdk.color_parse("#%02X%02X%02X" % (int(rs) >> 8, + int(gs) >> 8, int(bs) >> 8)) self.emit('color-changed', col) yield True @@ -125,7 +125,7 @@ class FadeOut(GObject.GObject): return ##_LOG.debug('_start_merging: Starting') - generator = self._merge_colors(self._start_color, + generator = self._merge_colors(self._start_color, Gdk.color_parse(self.ERROR_COLOR)) self._background_timeout_id = ( GLib.timeout_add(FadeOut.MERGE_COLORS_DELAY, generator.__next__)) @@ -134,7 +134,7 @@ class FadeOut(GObject.GObject): def start(self, color): """ Schedules a start of the countdown. - + :param color: initial background color :returns: True if we could start, False if was already in progress """ @@ -170,17 +170,17 @@ class FadeOut(GObject.GObject): (DIRECTION_LEFT, DIRECTION_RIGHT) = (1, -1) -(INPUT_ASCII_LETTER, - INPUT_ALPHA, - INPUT_ALPHANUMERIC, +(INPUT_ASCII_LETTER, + INPUT_ALPHA, + INPUT_ALPHANUMERIC, INPUT_DIGIT) = list(range(4)) INPUT_FORMATS = { - '0': INPUT_DIGIT, - 'L': INPUT_ASCII_LETTER, - 'A': INPUT_ALPHANUMERIC, - 'a': INPUT_ALPHANUMERIC, - '&': INPUT_ALPHA, + '0': INPUT_DIGIT, + 'L': INPUT_ASCII_LETTER, + 'A': INPUT_ALPHANUMERIC, + 'a': INPUT_ALPHANUMERIC, + '&': INPUT_ALPHA, } # Todo list: Other useful Masks @@ -189,13 +189,13 @@ INPUT_FORMATS = { # C - Alpha, optional INPUT_CHAR_MAP = { - INPUT_ASCII_LETTER: lambda text: text in string.ascii_letters, - INPUT_ALPHA: str.isalpha, - INPUT_ALPHANUMERIC: str.isalnum, - INPUT_DIGIT: str.isdigit, + INPUT_ASCII_LETTER: lambda text: text in string.ascii_letters, + INPUT_ALPHA: str.isalpha, + INPUT_ALPHANUMERIC: str.isalnum, + INPUT_DIGIT: str.isdigit, } -(COL_TEXT, +(COL_TEXT, COL_OBJECT) = list(range(2)) class MaskedEntry(UndoableEntry): @@ -207,7 +207,7 @@ class MaskedEntry(UndoableEntry): - Mask, force the input to meet certain requirements - IconEntry, allows you to have an icon inside the entry - convenience functions for completion - + .. note:: Gramps does not use the mask feature at the moment, so that code path is not tested """ @@ -228,7 +228,7 @@ class MaskedEntry(UndoableEntry): self.connect('focus-out-event', self._on_focus_out_event) self.connect('move-cursor', self._on_move_cursor) self.connect('button-press-event', self._on_button_press_event) - self.connect('notify::cursor-position', + self.connect('notify::cursor-position', self._on_notify_cursor_position) self._completion = None @@ -279,7 +279,7 @@ class MaskedEntry(UndoableEntry): def set_mask(self, mask): """ Set the mask of the Entry. - + Supported format characters are: - '0' digit @@ -288,7 +288,7 @@ class MaskedEntry(UndoableEntry): - 'a' alphanumeric, honors the locale - 'A' alphanumeric, honors the locale - This is similar to MaskedTextBox: + This is similar to MaskedTextBox: http://msdn2.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask(VS.80).aspx Example mask for a ISO-8601 date @@ -438,7 +438,7 @@ class MaskedEntry(UndoableEntry): start, end = self._mask_fields[field] return end - start - def _shift_text(self, start, end, direction=DIRECTION_LEFT, + def _shift_text(self, start, end, direction=DIRECTION_LEFT, positions=1): """ Shift the text, to the right or left, n positions. Note that this @@ -467,11 +467,11 @@ class MaskedEntry(UndoableEntry): # Non-static char shoud be here. Get the next one (depending # on the direction, and the number of positions to skip.) # - # When shifting left, the next char will be on the right, + # When shifting left, the next char will be on the right, # so, it will be appended, to the new text. # Otherwise, when shifting right, the char will be # prepended. - next_pos = self._get_next_non_static_char_pos(i, direction, + next_pos = self._get_next_non_static_char_pos(i, direction, positions-1) # If its outside the bounds of the region, ignore it. @@ -499,7 +499,7 @@ class MaskedEntry(UndoableEntry): return new_text - def _get_next_non_static_char_pos(self, pos, direction=DIRECTION_LEFT, + def _get_next_non_static_char_pos(self, pos, direction=DIRECTION_LEFT, skip=0): """ Get next non-static char position, skiping some chars, if necessary. @@ -590,7 +590,7 @@ class MaskedEntry(UndoableEntry): def _get_completion(self): # Check so we have completion enabled, not this does not - # depend on the property, the user can manually override it, + # depend on the property, the user can manually override it, # as long as there is a completion object set completion = self.get_completion() if completion: @@ -609,7 +609,7 @@ class MaskedEntry(UndoableEntry): #completion.set_model(Gtk.ListStore(str, object)) completion.set_model(Gtk.ListStore(GObject.TYPE_STRING)) completion.set_text_column(0) - #completion.connect("match-selected", + #completion.connect("match-selected", #self._on_completion__match_selected) self._completion = Gtk.Entry.get_completion(self) @@ -619,7 +619,7 @@ class MaskedEntry(UndoableEntry): def set_completion_mode(self, popup=None, inline=None): """ Set the way how completion is presented. - + :param popup: enable completion in popup window :type popup: boolean :param inline: enable inline completion @@ -630,7 +630,7 @@ class MaskedEntry(UndoableEntry): completion.set_popup_completion(popup) if inline is not None: completion.set_inline_completion(inline) - + def _completion_exact_match_func(self, completion, key, iter): model = completion.get_model() if not len(model): @@ -682,7 +682,7 @@ class MaskedEntry(UndoableEntry): :param new: The char that wants to be inserted. :param pos: The position where it wants to be inserted. - :returns: Returns None if it can be inserted. If it cannot be, + :returns: Returns None if it can be inserted. If it cannot be, return the next position where it can be successfuly inserted. """ @@ -716,7 +716,7 @@ class MaskedEntry(UndoableEntry): return None -# When inserting new text, supose, the entry, at some time is like this, +# When inserting new text, supose, the entry, at some time is like this, # ahd the user presses '0', for instance: # -------------------------------- # | ( 1 2 ) 3 4 5 - 6 7 8 9 | @@ -878,7 +878,7 @@ class MaskedEntry(UndoableEntry): # Shift Left new_text = (text[:start] + - self._shift_text(start, _end, DIRECTION_LEFT, + self._shift_text(start, _end, DIRECTION_LEFT, end-start) + text[_end:]) @@ -1022,7 +1022,7 @@ class MaskedEntry(UndoableEntry): rgba = Gdk.RGBA() Gdk.RGBA.parse(rgba, 'rgb(%f,%f,%f)'%(red, green, blue)) self.override_background_color(Gtk.StateFlags.NORMAL | - Gtk.StateFlags.ACTIVE | Gtk.StateFlags.SELECTED | + Gtk.StateFlags.ACTIVE | Gtk.StateFlags.SELECTED | Gtk.StateFlags.FOCUSED, rgba) #GTK 3: workaround, background not changing in themes, use symbolic self.override_symbolic_color('bg_color', rgba) @@ -1039,7 +1039,7 @@ class MaskedEntry(UndoableEntry): self.override_font(font_description) else: self.override_background_color(Gtk.StateFlags.NORMAL | - Gtk.StateFlags.ACTIVE | Gtk.StateFlags.SELECTED | + Gtk.StateFlags.ACTIVE | Gtk.StateFlags.SELECTED | Gtk.StateFlags.FOCUSED, None) # Setting the following to None causes an error (bug #6353). #self.override_symbolic_color('bg_color', None) @@ -1060,7 +1060,7 @@ class MaskedEntry(UndoableEntry): return bcol # Gtk.EntryCompletion convenience function - + def prefill(self, itemdata, sort=False): if not isinstance(itemdata, (list, tuple)): raise TypeError("'data' parameter must be a list or tuple of item " @@ -1104,32 +1104,32 @@ class ValidatableMaskedEntry(MaskedEntry): __gtype_name__ = 'ValidatableMaskedEntry' __gsignals__ = { - 'content-changed': (GObject.SignalFlags.RUN_FIRST, - None, - ()), - 'validation-changed': (GObject.SignalFlags.RUN_FIRST, - None, - (GObject.TYPE_BOOLEAN, )), - 'validate': (GObject.SignalFlags.RUN_LAST, - GObject.TYPE_PYOBJECT, - (GObject.TYPE_PYOBJECT, )), - 'changed': 'override', + 'content-changed': (GObject.SignalFlags.RUN_FIRST, + None, + ()), + 'validation-changed': (GObject.SignalFlags.RUN_FIRST, + None, + (GObject.TYPE_BOOLEAN, )), + 'validate': (GObject.SignalFlags.RUN_LAST, + GObject.TYPE_PYOBJECT, + (GObject.TYPE_PYOBJECT, )), + 'changed': 'override', } __gproperties__ = { - 'data-type': (GObject.TYPE_PYOBJECT, - 'Data Type of the widget', - 'Type object', - GObject.PARAM_READWRITE), - 'mandatory': (GObject.TYPE_BOOLEAN, - 'Mandatory', - 'Mandatory', - False, - GObject.PARAM_READWRITE), + 'data-type': (GObject.TYPE_PYOBJECT, + 'Data Type of the widget', + 'Type object', + GObject.PARAM_READWRITE), + 'mandatory': (GObject.TYPE_BOOLEAN, + 'Mandatory', + 'Mandatory', + False, + GObject.PARAM_READWRITE), } - + # FIXME put the data type support back - #allowed_data_types = (basestring, datetime.date, datetime.time, + #allowed_data_types = (basestring, datetime.date, datetime.time, #datetime.datetime, object) + number def __init__(self, data_type=None, err_color = "#ffd5d5", error_icon=ERROR_ICON): @@ -1139,12 +1139,12 @@ class ValidatableMaskedEntry(MaskedEntry): self._block_changed = False MaskedEntry.__init__(self) - + self._valid = True self._def_error_msg = None self._fade = FadeOut(self, err_color) self._fade.connect('color-changed', self._on_fadeout__color_changed) - + # FIXME put data type support back #self.set_property('data-type', data_type) @@ -1159,7 +1159,7 @@ class ValidatableMaskedEntry(MaskedEntry): def do_get_property(self, prop): """Return the gproperty's value.""" - + if prop.name == 'data-type': return self.data_type elif prop.name == 'mandatory': @@ -1169,18 +1169,18 @@ class ValidatableMaskedEntry(MaskedEntry): def do_set_property(self, prop, value): """Set the property of writable properties.""" - + if prop.name == 'data-type': if value is None: self.data_type = value return - + # FIXME put the data type support back #if not issubclass(value, self.allowed_data_types): #raise TypeError( #"%s only accept %s types, not %r" - #% (self, - #' or '.join([t.__name__ for t in self.allowed_data_types]), + #% (self, + #' or '.join([t.__name__ for t in self.allowed_data_types]), #value)) self.data_type = value elif prop.name == 'mandatory': @@ -1193,19 +1193,19 @@ class ValidatableMaskedEntry(MaskedEntry): def set_default_error_msg(self, text): """ Set default message for validation error. - + Default error message for an instance is useful when completion is used, because this case custom validation is not called. - + :param text: can contain one and only one '%s', where the actual value of the Entry will be inserted. :type text: str """ if not isinstance(text, str): raise TypeError("text must be a string") - + self._def_error_msg = text - + def is_valid(self): """ :returns: True if the widget is in validated state @@ -1283,14 +1283,14 @@ class ValidatableMaskedEntry(MaskedEntry): generic_text = _("'%s' is not a valid value " "for this field") % self.get_text() - + # If there is no error text, let's try with the default or # fall back to a generic one if not text: text = self._def_error_msg if not text: text = generic_text - + try: text.index('%s') text = text % self.get_text() @@ -1385,13 +1385,13 @@ class ValidatableMaskedEntry(MaskedEntry): def main(args): from gramps.gen.datehandler import parser - + def on_validate(widget, text): myDate = parser.parse(text) if not myDate.is_regular(): # used on AgeOnDateGramplet return ValidationError(_("'%s' is not a valid date value")) - + win = Gtk.Window() win.set_title('ValidatableMaskedEntry test window') win.set_position(Gtk.WindowPosition.CENTER) @@ -1401,10 +1401,10 @@ def main(args): vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) win.add(vbox) - + label = Gtk.Label(label='Pre-filled entry validated against the given list:') vbox.pack_start(label, True, True, 0) - + widget1 = ValidatableMaskedEntry(str) widget1.set_completion_mode(inline=True, popup=False) widget1.set_default_error_msg("'%s' is not a default Event") @@ -1412,17 +1412,17 @@ def main(args): widget1.prefill(('Birth', 'Death', 'Conseption')) #widget1.set_exact_completion(True) vbox.pack_start(widget1, True, False, 0) - + label = Gtk.Label(label='Mandatory masked entry validated against user function:') vbox.pack_start(label, True, True, 0) - + #widget2 = ValidatableMaskedEntry(str, "#e0e0e0", error_icon=None) widget2 = ValidatableMaskedEntry() widget2.set_mask('00/00/0000') widget2.connect('validate', on_validate) widget2.mandatory = True vbox.pack_start(widget2, True, False, 0) - + win.show_all() Gtk.main() diff --git a/gramps/gui/widgets/valueaction.py b/gramps/gui/widgets/valueaction.py index 98b836e37..8b1dcd96d 100644 --- a/gramps/gui/widgets/valueaction.py +++ b/gramps/gui/widgets/valueaction.py @@ -53,21 +53,21 @@ from .valuetoolitem import ValueToolItem class ValueAction(Gtk.Action): """ Value action class. - + (A ValueAction with menu item doesn't make any sense.) """ __gtype_name__ = "ValueAction" - + __gsignals__ = { - 'changed': (GObject.SignalFlags.RUN_FIRST, + 'changed': (GObject.SignalFlags.RUN_FIRST, None, #return value ()), # arguments - } + } def __init__(self, name, tooltip, default, itemtype, *args): """ Create a new ValueAction instance. - + :param name: the name of the action :type name: str :param tooltip: tooltip string @@ -78,53 +78,53 @@ class ValueAction(Gtk.Action): :type default: set by itemtype :param itemtype: default tool item class :type itemtype: :class:`.ValueToolItem` subclass - :param args: arguments to be passed to the default toolitem class + :param args: arguments to be passed to the default toolitem class at creation. see: :meth:`do_create_tool_item` :type args: list """ GObject.GObject.__init__(self, name=name, label='', tooltip=tooltip, stock_id=None) - + self._value = default self._data_type = type(default) - + # have to be remembered, because we can't access # GtkAction->toolbar_item_type later. self._default_toolitem_type = itemtype -##TODO GTK3: following is deprecated, must be replaced by +##TODO GTK3: following is deprecated, must be replaced by ## itemtype.set_related_action(ValueAction) in calling class? ## self.set_tool_item_type(itemtype) self._args_for_toolitem = args - + self._handlers = {} - + def do_changed(self): """ Default signal handler for 'changed' signal. - + Synchronize all the proxies with the active value. """ for proxy in self.get_proxies(): proxy.handler_block(self._handlers[proxy]) proxy.set_value(self._value) proxy.handler_unblock(self._handlers[proxy]) - + def do_create_tool_item(self): """ Create a 'default' toolbar item widget. - + Override the default method, to be able to pass the required parameters to the proxy's constructor. - + This method is called from Gtk.UIManager.ensure_update(), when a 'toolitem' is found in the UI definition with a name refering to a ValueAction. Thus, to use the action via the UIManager a 'default' toolitem type has to be set with the Gtk.Action.set_tool_item_type() method, before invoking the Gtk.UIManager.ensure_update() method. - + Widgets other than the default type has to be created and added - manually with the Gtk.Action.connect_proxy() method. - + manually with the Gtk.Action.connect_proxy() method. + :returns: a toolbar item connected to the action. :rtype: :class:`.ValueToolItem` subclass """ @@ -138,17 +138,17 @@ class ValueAction(Gtk.Action): value = proxy.get_value() if value is not None: self.set_value(value) - + def connect_proxy(self, proxy): """ Connect a widget to an action object as a proxy. - + :param proxy: widget to be connected :type proxy: :class:`.ValueToolItem` subclass """ if not isinstance(proxy, ValueToolItem): raise TypeError - + # do this before connecting, so that we don't call the handler proxy.set_value(self._value) self._handlers[proxy] = proxy.connect('changed', self._on_proxy_changed) @@ -160,10 +160,10 @@ class ValueAction(Gtk.Action): """Set value to action.""" if not isinstance(value, self._data_type): raise TypeError - + self._value = value self.emit('changed') - + def get_value(self): """Get the value from the action.""" return self._value diff --git a/gramps/gui/widgets/valuetoolitem.py b/gramps/gui/widgets/valuetoolitem.py index 935c13b70..955bbbdea 100644 --- a/gramps/gui/widgets/valuetoolitem.py +++ b/gramps/gui/widgets/valuetoolitem.py @@ -46,47 +46,47 @@ from gi.repository import Gtk #------------------------------------------------------------------------- class ValueToolItem(Gtk.ToolItem): """ValueToolItem is an abstract toolbar proxy for ValueAction. - + For each kind of widget a separete tool item proxy has to be subclassed from this ValueToolItem. - + """ __gtype_name__ = "ValueToolItem" - + __gsignals__ = { - 'changed': (GObject.SignalFlags.RUN_FIRST, + 'changed': (GObject.SignalFlags.RUN_FIRST, None, #return value ()), # arguments - } + } def __init__(self, data_type, args): GObject.GObject.__init__(self) - + self._data_type = data_type - + self._create_widget(*args) - + def _on_widget_changed(self, widget): self.emit('changed') def _create_widget(self, args): """Create the apropriate widget for the actual proxy.""" raise NotImplementedError - + def set_value(self, value): """Set new value for the proxied widget. - + The method is responsible converting the data type between action and widget. - + """ raise NotImplementedError - + def get_value(self): """Get value from the proxied widget. - + The method is responsible converting the data type between action and widget. - + """ raise NotImplementedError diff --git a/gramps/guiQML/__init__.py b/gramps/guiQML/__init__.py index 4dc330886..6bd7f9e37 100644 --- a/gramps/guiQML/__init__.py +++ b/gramps/guiQML/__init__.py @@ -22,6 +22,6 @@ Package init for the guiQML package. """ -# DO NOT IMPORT METHODS/CLASSES FROM src/guiQML HERE ! Only __all__ +# DO NOT IMPORT METHODS/CLASSES FROM src/guiQML HERE ! Only __all__ __all__ = [ ] diff --git a/gramps/guiQML/grampsqml.py b/gramps/guiQML/grampsqml.py index e366f6aef..8781be600 100644 --- a/gramps/guiQML/grampsqml.py +++ b/gramps/guiQML/grampsqml.py @@ -89,7 +89,7 @@ class GrampsQML(object): else: # open without fam tree loaded self.vm.post_init_interface() - + #start the QT loop self.app.exec_() @@ -104,14 +104,14 @@ def startqml(errors, argparser): First action inside the gtk loop """ from guiQML.questiondialog import ErrorDialog, run_dialog_standalone - + #handle first existing errors in GUI fashion if errors: run_dialog_standalone(ErrorDialog,errors[0], errors[1]) sys.exit() if argparser.errors: - run_dialog_standalone(ErrorDialog, argparser.errors[0], + run_dialog_standalone(ErrorDialog, argparser.errors[0], argparser.errors[1]) sys.exit() diff --git a/gramps/guiQML/questiondialog.py b/gramps/guiQML/questiondialog.py index b62cd0121..5dcf24d75 100644 --- a/gramps/guiQML/questiondialog.py +++ b/gramps/guiQML/questiondialog.py @@ -58,7 +58,7 @@ class ErrorDialog(QDialog): def run_dialog_standalone(dlgclass, *args, **keywords): app = QApplication(sys.argv) - QObject.connect(app, SIGNAL('lastWindowClosed()'), app, SLOT('quit()')) - + QObject.connect(app, SIGNAL('lastWindowClosed()'), app, SLOT('quit()')) + win = dlgclass(*args, **keywords) app.exec_() diff --git a/gramps/guiQML/viewmanager.py b/gramps/guiQML/viewmanager.py index 735c3113a..34a19688e 100644 --- a/gramps/guiQML/viewmanager.py +++ b/gramps/guiQML/viewmanager.py @@ -73,7 +73,7 @@ from guiQML.questiondialog import ErrorDialog #------------------------------------------------------------------------- class ViewManager(CLIManager): - """ + """ Manages main widget by holding what state it is in. """ def __init__(self, dbstate, user = None): @@ -146,7 +146,7 @@ class ViewManager(CLIManager): """ if not self.__centralview: from guiQML.views.centralview import CentralView - self.__centralview = CentralView(self.dbstate, self.engine, + self.__centralview = CentralView(self.dbstate, self.engine, self.open_view) self.__centralview.show(self.mainview, self.mainwindow) diff --git a/gramps/guiQML/views/__init__.py b/gramps/guiQML/views/__init__.py index 008f9bc41..a595ea2c8 100644 --- a/gramps/guiQML/views/__init__.py +++ b/gramps/guiQML/views/__init__.py @@ -22,6 +22,6 @@ Package init for different views in guiQML. """ -# DO NOT IMPORT METHODS/CLASSES FROM src/guiQML HERE ! Only __all__ +# DO NOT IMPORT METHODS/CLASSES FROM src/guiQML HERE ! Only __all__ __all__ = [ ] diff --git a/gramps/guiQML/views/centralview.py b/gramps/guiQML/views/centralview.py index 8b45fd044..1eca1438f 100644 --- a/gramps/guiQML/views/centralview.py +++ b/gramps/guiQML/views/centralview.py @@ -79,28 +79,28 @@ class DetailView(QtCore.QObject): def _name(self): return self.__name - + changed = QtCore.Signal() - #make Model.Column.property available in QML + #make Model.Column.property available in QML name = QtCore.Property(str, _name, notify=changed) - + class DetViewSumModel(QtCore.QAbstractListModel): """ A simple ListModel for the different detailed views """ COLUMNS = ('name', ) - + def __init__(self, detviews): QtCore.QAbstractListModel.__init__(self) self._detviews = detviews self.setRoleNames(dict(enumerate(DetViewSumModel.COLUMNS))) - + def rowCount(self, parent=QtCore.QModelIndex()): return len(self._detviews) - + def data(self, index, role): - print('role', role, DetViewSumModel.COLUMNS.index('name')) + print('role', role, DetViewSumModel.COLUMNS.index('name')) if index.isValid() and role == DetViewSumModel.COLUMNS.index('name'): return self._detviews[index.row()] return None @@ -112,7 +112,7 @@ class DetViewSumModel(QtCore.QAbstractListModel): #------------------------------------------------------------------------- class CentralView(QtCore.QObject): - """ + """ Manages family tree list widget """ def __init__(self, dbstate, engine, viewshow): @@ -139,7 +139,7 @@ class CentralView(QtCore.QObject): self.centralviewcontext = QtDeclarative.QDeclarativeContext(parentcontext) #Create ListModel to use detviews = DetViewSumModel([DetailView('People')]) - + #register them in the context self.centralviewcontext.setContextProperty('Const', self.const) self.centralviewcontext.setContextProperty('CentralView', self) @@ -162,7 +162,7 @@ class CentralView(QtCore.QObject): mainwindow.setCentralWidget(graphicsview) mainwindow.show() - @QtCore.Slot(QtCore.QObject) + @QtCore.Slot(QtCore.QObject) def detviewSelected(self, detview): """ We load the selected family tree diff --git a/gramps/guiQML/views/dbman.py b/gramps/guiQML/views/dbman.py index 3f77a990f..4dacc4420 100644 --- a/gramps/guiQML/views/dbman.py +++ b/gramps/guiQML/views/dbman.py @@ -112,20 +112,20 @@ class FamTreeListModel(QtCore.QAbstractListModel): A simple ListModel """ COLUMNS = ('name', 'path', 'last_access', 'use_icon', 'icon') - + def __init__(self, famtrees): QtCore.QAbstractListModel.__init__(self) self._famtrees = famtrees self.setRoleNames(dict(enumerate(FamTreeListModel.COLUMNS))) - + def rowCount(self, parent=QtCore.QModelIndex()): return len(self._famtrees) - + def data(self, index, role): if index.isValid() and role == FamTreeListModel.COLUMNS.index('name'): return self._famtrees[index.row()] return None - + def append_famtree(self, famtree): """ Append a FamTreeWrapper to the family tree litsmodel @@ -141,7 +141,7 @@ class FamTreeListModel(QtCore.QAbstractListModel): #------------------------------------------------------------------------- class DbManager(CLIDbManager, QtCore.QObject): - """ + """ Manages family tree list widget """ def __init__(self, dbstate, engine, onselectcallback): @@ -172,7 +172,7 @@ class DbManager(CLIDbManager, QtCore.QObject): #Create ListModel to use famtreesQT = [FamTreeWrapper(obj, self) for obj in self.current_names] self.famtrees = FamTreeListModel(famtreesQT) - + #register them in the context self.famtreecontext.setContextProperty('Const', self.const) self.famtreecontext.setContextProperty('DbManager', self) @@ -218,7 +218,7 @@ class DbManager(CLIDbManager, QtCore.QObject): new_path, title = self.create_new_db_cli(None) path_name = os.path.join(new_path, NAME_FILE) (tval, last) = time_val(new_path) - self.famtrees.append_famtree(FamTreeWrapper([title, new_path, path_name, + self.famtrees.append_famtree(FamTreeWrapper([title, new_path, path_name, last, tval, False, ''])) self.__busy = False diff --git a/gramps/guiQML/views/personview.py b/gramps/guiQML/views/personview.py index b882f46b8..d0101d8f0 100644 --- a/gramps/guiQML/views/personview.py +++ b/gramps/guiQML/views/personview.py @@ -82,20 +82,20 @@ class QMLPerson(QtCore.QObject): def _name(self): return name_displayer.display(self.__db.get_person_from_handle(self.__handle)) - + #dummy signal for things that change must not be tracked dummychanged = QtCore.Signal() - #make Model.Column.property available in QML + #make Model.Column.property available in QML name = QtCore.Property(str, _name, notify=dummychanged) - + class QMLPersonListModel(QtCore.QAbstractListModel): """ A simple ListModel for the People in the database """ ROLE_NAME_COL = 0 COLUMNS = ((ROLE_NAME_COL, 'name'), ) - + def __init__(self, db): QtCore.QAbstractListModel.__init__(self) self.__db = db @@ -107,12 +107,12 @@ class QMLPersonListModel(QtCore.QAbstractListModel): allkeys = self.sort_keys() ident = True dlist = allkeys - self.node_map.set_path_map(dlist, allkeys, identical=ident, + self.node_map.set_path_map(dlist, allkeys, identical=ident, reverse=self._reverse) - + #every column has a role from 0 to nrcol-1, and name as in COLUMNS self.setRoleNames(dict(QMLPersonListModel.COLUMNS)) - #we create an array with all the QMLPerson that we need so + #we create an array with all the QMLPerson that we need so #that we can match a rowindex with correct QMLPerson self._qmlpersons = [] for _, handle in self.node_map.full_srtkey_hndl_map(): @@ -120,15 +120,15 @@ class QMLPersonListModel(QtCore.QAbstractListModel): def sort_keys(self): """ - Return the (sort_key, handle) list of all data that can maximally - be shown. - This list is sorted ascending, via localized string sort. - conv_unicode_tosrtkey which uses strxfrm, which is apparently - broken in Win ?? --> they should fix base lib, we need strxfrm, fix it + Return the (sort_key, handle) list of all data that can maximally + be shown. + This list is sorted ascending, via localized string sort. + conv_unicode_tosrtkey which uses strxfrm, which is apparently + broken in Win ?? --> they should fix base lib, we need strxfrm, fix it in the Utils module. """ # use cursor as a context manager - with self.gen_cursor() as cursor: + with self.gen_cursor() as cursor: #loop over database and store the sort field, and the handle return sorted((list(map(conv_unicode_tosrtkey, self.sort_func(data))), key) for key, data in cursor) @@ -140,7 +140,7 @@ class QMLPersonListModel(QtCore.QAbstractListModel): def rowCount(self, parent=QtCore.QModelIndex()): return self.__db.get_number_of_people() - + def data(self, index, role): """ Obtain QMLPerson to show. Role is a number that corresponds to a column, @@ -157,7 +157,7 @@ class QMLPersonListModel(QtCore.QAbstractListModel): #------------------------------------------------------------------------- class QMLPersonList(QtCore.QObject): - """ + """ Manages family tree list widget """ def __init__(self, dbstate, engine): @@ -182,7 +182,7 @@ class QMLPersonList(QtCore.QObject): self.qmlpersonlistcontext = QtDeclarative.QDeclarativeContext(parentcontext) #Create ListModel to use personlistmodel = QMLPersonListModel(self.dbstate.db) - + #register them in the context self.qmlpersonlistcontext.setContextProperty('Const', self.const) self.qmlpersonlistcontext.setContextProperty('QMLPersonList', self) @@ -205,7 +205,7 @@ class QMLPersonList(QtCore.QObject): mainwindow.setCentralWidget(graphicsview) mainwindow.show() - @QtCore.Slot(QtCore.QObject) + @QtCore.Slot(QtCore.QObject) def detailsSelected(self, qmlperson): """ We load the selected family tree diff --git a/gramps/plugins/database/bsddb_support/bsddbtxn.py b/gramps/plugins/database/bsddb_support/bsddbtxn.py index 3d65379fd..c89ed1296 100644 --- a/gramps/plugins/database/bsddb_support/bsddbtxn.py +++ b/gramps/plugins/database/bsddb_support/bsddbtxn.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -81,7 +81,7 @@ class BSDDBTxn(object): if self.txn: self.commit() return True - + # Methods implementing txn_ methods in DBEnv def begin(self, *args, **kwargs): @@ -183,7 +183,7 @@ class BSDDBTxn(object): self.db.delete(key, txn or self.txn, **kwargs) # test code -if __name__ == "__main__": +if __name__ == "__main__": print("1") from bsddb3 import db, dbshelve print("2") diff --git a/gramps/plugins/database/bsddb_support/cursor.py b/gramps/plugins/database/bsddb_support/cursor.py index 9ee917b50..5161fefed 100644 --- a/gramps/plugins/database/bsddb_support/cursor.py +++ b/gramps/plugins/database/bsddb_support/cursor.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -47,16 +47,16 @@ except: class BsddbBaseCursor(object): """ Provide a basic iterator that allows the user to cycle through - the elements in a particular map. - - A cursor should never be directly instantiated. Instead, in should be + the elements in a particular map. + + A cursor should never be directly instantiated. Instead, in should be created by the database class. A cursor should only be used for a single pass through the database. If multiple passes are needed, multiple cursors should be used. """ - + def __init__(self, txn=None, update=False, commit=False): """ Instantiate the object. Note, this method should be overridden in @@ -87,12 +87,12 @@ class BsddbBaseCursor(object): if self.txn and self.commit: self.txn.commit() return exc_type is None - + def __iter__(self): """ Iterator """ - + data = self.first() _n = self.next # Saved attribute lookup in the loop while data: diff --git a/gramps/plugins/database/bsddb_support/read.py b/gramps/plugins/database/bsddb_support/read.py index 07b712e4f..9d01d77d1 100644 --- a/gramps/plugins/database/bsddb_support/read.py +++ b/gramps/plugins/database/bsddb_support/read.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -44,7 +44,7 @@ except: DBAccessError = 0 DBPageNotFoundError = 0 DBInvalidArgError = 0 - + import re import logging @@ -64,7 +64,7 @@ from gramps.gen.lib.repo import Repository from gramps.gen.lib.note import Note from gramps.gen.lib.tag import Tag from gramps.gen.lib.genderstats import GenderStats -from gramps.gen.lib.researcher import Researcher +from gramps.gen.lib.researcher import Researcher from gramps.gen.lib.nameorigintype import NameOriginType from gramps.gen.utils.callback import Callback @@ -87,18 +87,18 @@ LOG = logging.getLogger(".citation") # #------------------------------------------------------------------------- -_SIGBASE = ('person', 'family', 'source', 'citation', +_SIGBASE = ('person', 'family', 'source', 'citation', 'event', 'media', 'place', 'repository', 'reference', 'note', 'tag') -DBERRS = (db.DBRunRecoveryError, db.DBAccessError, +DBERRS = (db.DBRunRecoveryError, db.DBAccessError, db.DBPageNotFoundError, db.DBInvalidArgError) #------------------------------------------------------------------------- # # Helper functions # -#------------------------------------------------------------------------- +#------------------------------------------------------------------------- def find_byte_surname(key, data): """ Creating a surname from raw data of a person, to use for sort and index @@ -136,13 +136,13 @@ def __index_surname(surn_list): else: surn = "" return surn - + #------------------------------------------------------------------------- # # class DbBookmarks # -#------------------------------------------------------------------------- +#------------------------------------------------------------------------- class DbBookmarks(object): def __init__(self, default=[]): self.bookmarks = list(default) # want a copy (not an alias) @@ -225,9 +225,9 @@ class DbBsddbRead(DbReadBase, Callback): Read class for the Gramps databases. Implements methods necessary to read the various object classes. Currently, there are nine (9) classes: - :py:class:`.Person`, :py:class:`.Family`, :py:class:`.Event`, - :py:class:`.Place`, :py:class:`.Source`, - :py:class:`Citation <.lib.citation.Citation>`, :py:class:`.MediaObject`, + :py:class:`.Person`, :py:class:`.Family`, :py:class:`.Event`, + :py:class:`.Place`, :py:class:`.Source`, + :py:class:`Citation <.lib.citation.Citation>`, :py:class:`.MediaObject`, :py:class:`.Repository` and :py:class:`.Note` For each object class, there are methods to retrieve data in various ways. @@ -236,7 +236,7 @@ class DbBsddbRead(DbReadBase, Callback): specified. .. method:: get__from_handle() - + returns an object given its handle .. method:: get__from_gramps_id() @@ -286,13 +286,13 @@ class DbBsddbRead(DbReadBase, Callback): def __init__(self): """ - Create a new DbBsddbRead instance. + Create a new DbBsddbRead instance. """ DbReadBase.__init__(self) Callback.__init__(self) self._tables['Person'].update( { - "handle_func": self.get_person_from_handle, + "handle_func": self.get_person_from_handle, "gramps_id_func": self.get_person_from_gramps_id, "class_func": Person, "cursor_func": self.get_person_cursor, @@ -300,7 +300,7 @@ class DbBsddbRead(DbReadBase, Callback): }) self._tables['Family'].update( { - "handle_func": self.get_family_from_handle, + "handle_func": self.get_family_from_handle, "gramps_id_func": self.get_family_from_gramps_id, "class_func": Family, "cursor_func": self.get_family_cursor, @@ -308,7 +308,7 @@ class DbBsddbRead(DbReadBase, Callback): }) self._tables['Source'].update( { - "handle_func": self.get_source_from_handle, + "handle_func": self.get_source_from_handle, "gramps_id_func": self.get_source_from_gramps_id, "class_func": Source, "cursor_func": self.get_source_cursor, @@ -316,7 +316,7 @@ class DbBsddbRead(DbReadBase, Callback): }) self._tables['Citation'].update( { - "handle_func": self.get_citation_from_handle, + "handle_func": self.get_citation_from_handle, "gramps_id_func": self.get_citation_from_gramps_id, "class_func": Citation, "cursor_func": self.get_citation_cursor, @@ -324,7 +324,7 @@ class DbBsddbRead(DbReadBase, Callback): }) self._tables['Event'].update( { - "handle_func": self.get_event_from_handle, + "handle_func": self.get_event_from_handle, "gramps_id_func": self.get_event_from_gramps_id, "class_func": Event, "cursor_func": self.get_event_cursor, @@ -332,7 +332,7 @@ class DbBsddbRead(DbReadBase, Callback): }) self._tables['Media'].update( { - "handle_func": self.get_object_from_handle, + "handle_func": self.get_object_from_handle, "gramps_id_func": self.get_object_from_gramps_id, "class_func": MediaObject, "cursor_func": self.get_media_cursor, @@ -340,7 +340,7 @@ class DbBsddbRead(DbReadBase, Callback): }) self._tables['Place'].update( { - "handle_func": self.get_place_from_handle, + "handle_func": self.get_place_from_handle, "gramps_id_func": self.get_place_from_gramps_id, "class_func": Place, "cursor_func": self.get_place_cursor, @@ -348,7 +348,7 @@ class DbBsddbRead(DbReadBase, Callback): }) self._tables['Repository'].update( { - "handle_func": self.get_repository_from_handle, + "handle_func": self.get_repository_from_handle, "gramps_id_func": self.get_repository_from_gramps_id, "class_func": Repository, "cursor_func": self.get_repository_cursor, @@ -356,7 +356,7 @@ class DbBsddbRead(DbReadBase, Callback): }) self._tables['Note'].update( { - "handle_func": self.get_note_from_handle, + "handle_func": self.get_note_from_handle, "gramps_id_func": self.get_note_from_gramps_id, "class_func": Note, "cursor_func": self.get_note_cursor, @@ -364,7 +364,7 @@ class DbBsddbRead(DbReadBase, Callback): }) self._tables['Tag'].update( { - "handle_func": self.get_tag_from_handle, + "handle_func": self.get_tag_from_handle, "gramps_id_func": None, "class_func": Tag, "cursor_func": self.get_tag_cursor, @@ -534,8 +534,8 @@ class DbBsddbRead(DbReadBase, Callback): def close(self): """ - Close the specified database. - + Close the specified database. + The method needs to be overridden in the derived class. """ #remove circular dependance @@ -594,10 +594,10 @@ class DbBsddbRead(DbReadBase, Callback): bindex = index.encode('utf-8') map_index += 1 return (map_index, index) - + def find_next_person_gramps_id(self): """ - Return the next available Gramps ID for a Person object based off the + Return the next available Gramps ID for a Person object based off the person ID prefix. """ self.pmap_index, gid = self.__find_next_gramps_id(self.person_prefix, @@ -606,7 +606,7 @@ class DbBsddbRead(DbReadBase, Callback): def find_next_place_gramps_id(self): """ - Return the next available Gramps ID for a Place object based off the + Return the next available Gramps ID for a Place object based off the place ID prefix. """ self.lmap_index, gid = self.__find_next_gramps_id(self.place_prefix, @@ -615,7 +615,7 @@ class DbBsddbRead(DbReadBase, Callback): def find_next_event_gramps_id(self): """ - Return the next available Gramps ID for a Event object based off the + Return the next available Gramps ID for a Event object based off the event ID prefix. """ self.emap_index, gid = self.__find_next_gramps_id(self.event_prefix, @@ -633,7 +633,7 @@ class DbBsddbRead(DbReadBase, Callback): def find_next_source_gramps_id(self): """ - Return the next available Gramps ID for a Source object based off the + Return the next available Gramps ID for a Source object based off the source ID prefix. """ self.smap_index, gid = self.__find_next_gramps_id(self.source_prefix, @@ -642,7 +642,7 @@ class DbBsddbRead(DbReadBase, Callback): def find_next_citation_gramps_id(self): """ - Return the next available Gramps ID for a Source object based off the + Return the next available Gramps ID for a Source object based off the source ID prefix. """ self.cmap_index, gid = self.__find_next_gramps_id(self.citation_prefix, @@ -651,7 +651,7 @@ class DbBsddbRead(DbReadBase, Callback): def find_next_family_gramps_id(self): """ - Return the next available Gramps ID for a Family object based off the + Return the next available Gramps ID for a Family object based off the family ID prefix. """ self.fmap_index, gid = self.__find_next_gramps_id(self.family_prefix, @@ -660,7 +660,7 @@ class DbBsddbRead(DbReadBase, Callback): def find_next_repository_gramps_id(self): """ - Return the next available Gramps ID for a Respository object based + Return the next available Gramps ID for a Respository object based off the repository ID prefix. """ self.rmap_index, gid = self.__find_next_gramps_id(self.repository_prefix, @@ -669,7 +669,7 @@ class DbBsddbRead(DbReadBase, Callback): def find_next_note_gramps_id(self): """ - Return the next available Gramps ID for a Note object based off the + Return the next available Gramps ID for a Note object based off the note ID prefix. """ self.nmap_index, gid = self.__find_next_gramps_id(self.note_prefix, @@ -718,7 +718,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_person_from_handle(self, handle): """ Find a Person in the database from the passed handle. - + If no such Person exists, None is returned. """ return self.get_from_handle(handle, Person, self.person_map) @@ -726,7 +726,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_source_from_handle(self, handle): """ Find a Source in the database from the passed handle. - + If no such Source exists, None is returned. """ return self.get_from_handle(handle, Source, self.source_map) @@ -734,7 +734,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_citation_from_handle(self, handle): """ Find a Citation in the database from the passed handle. - + If no such Citation exists, None is returned. """ return self.get_from_handle(handle, Citation, self.citation_map) @@ -742,7 +742,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_object_from_handle(self, handle): """ Find an Object in the database from the passed handle. - + If no such Object exists, None is returned. """ return self.get_from_handle(handle, MediaObject, self.media_map) @@ -750,7 +750,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_place_from_handle(self, handle): """ Find a Place in the database from the passed handle. - + If no such Place exists, None is returned. """ return self.get_from_handle(handle, Place, self.place_map) @@ -758,7 +758,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_event_from_handle(self, handle): """ Find a Event in the database from the passed handle. - + If no such Event exists, None is returned. """ return self.get_from_handle(handle, Event, self.event_map) @@ -766,7 +766,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_family_from_handle(self, handle): """ Find a Family in the database from the passed handle. - + If no such Family exists, None is returned. """ return self.get_from_handle(handle, Family, self.family_map) @@ -774,7 +774,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_repository_from_handle(self, handle): """ Find a Repository in the database from the passed handle. - + If no such Repository exists, None is returned. """ return self.get_from_handle(handle, Repository, self.repository_map) @@ -782,7 +782,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_note_from_handle(self, handle): """ Find a Note in the database from the passed handle. - + If no such Note exists, None is returned. """ return self.get_from_handle(handle, Note, self.note_map) @@ -790,14 +790,14 @@ class DbBsddbRead(DbReadBase, Callback): def get_tag_from_handle(self, handle): """ Find a Tag in the database from the passed handle. - + If no such Tag exists, None is returned. """ return self.get_from_handle(handle, Tag, self.tag_map) def __get_obj_from_gramps_id(self, val, tbl, class_, prim_tbl): - if isinstance(tbl, dict): - return None ## trying to get object too early + if isinstance(tbl, dict): + return None ## trying to get object too early if isinstance(val, str): val = val.encode('utf-8') try: @@ -823,7 +823,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_person_from_gramps_id(self, val): """ Find a Person in the database from the passed Gramps ID. - + If no such Person exists, None is returned. """ return self.__get_obj_from_gramps_id(val, self.id_trans, Person, @@ -832,16 +832,16 @@ class DbBsddbRead(DbReadBase, Callback): def get_family_from_gramps_id(self, val): """ Find a Family in the database from the passed Gramps ID. - + If no such Family exists, None is return. """ return self.__get_obj_from_gramps_id(val, self.fid_trans, Family, self.family_map) - + def get_event_from_gramps_id(self, val): """ Find an Event in the database from the passed Gramps ID. - + If no such Family exists, None is returned. """ return self.__get_obj_from_gramps_id(val, self.eid_trans, Event, @@ -850,7 +850,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_place_from_gramps_id(self, val): """ Find a Place in the database from the passed Gramps ID. - + If no such Place exists, None is returned. """ return self.__get_obj_from_gramps_id(val, self.pid_trans, Place, @@ -859,7 +859,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_source_from_gramps_id(self, val): """ Find a Source in the database from the passed Gramps ID. - + If no such Source exists, None is returned. """ return self.__get_obj_from_gramps_id(val, self.sid_trans, Source, @@ -868,7 +868,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_citation_from_gramps_id(self, val): """ Find a Citation in the database from the passed Gramps ID. - + If no such Citation exists, None is returned. """ return self.__get_obj_from_gramps_id(val, self.cid_trans, Citation, @@ -877,7 +877,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_object_from_gramps_id(self, val): """ Find a MediaObject in the database from the passed Gramps ID. - + If no such MediaObject exists, None is returned. """ return self.__get_obj_from_gramps_id(val, self.oid_trans, MediaObject, @@ -886,7 +886,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_repository_from_gramps_id(self, val): """ Find a Repository in the database from the passed Gramps ID. - + If no such Repository exists, None is returned. """ return self.__get_obj_from_gramps_id(val, self.rid_trans, Repository, @@ -895,7 +895,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_note_from_gramps_id(self, val): """ Find a Note in the database from the passed Gramps ID. - + If no such Note exists, None is returned. """ return self.__get_obj_from_gramps_id(val, self.nid_trans, Note, @@ -904,12 +904,12 @@ class DbBsddbRead(DbReadBase, Callback): def get_tag_from_name(self, val): """ Find a Tag in the database from the passed Tag name. - + If no such Tag exists, None is returned. """ return self.__get_obj_from_gramps_id(val, self.tag_trans, Tag, self.tag_map) - + def get_name_group_mapping(self, surname): """ Return the default grouping name for a surname. @@ -1018,20 +1018,20 @@ class DbBsddbRead(DbReadBase, Callback): def all_handles(self, table): """ return all the keys of a database table - .. warning:: For speed the keys are directly returned, so on python3 + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ return table.keys(txn=self.txn) - + def get_person_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Person in - the database. - + the database. + If sort_handles is True, the list is sorted by surnames. - - .. warning:: For speed the keys are directly returned, so on python3 + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ @@ -1045,11 +1045,11 @@ class DbBsddbRead(DbReadBase, Callback): def get_place_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Place in - the database. - + the database. + If sort_handles is True, the list is sorted by Place title. - - .. warning:: For speed the keys are directly returned, so on python3 + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ @@ -1065,10 +1065,10 @@ class DbBsddbRead(DbReadBase, Callback): """ Return a list of database handles, one handle for each Source in the database. - + If sort_handles is True, the list is sorted by Source title. - - .. warning:: For speed the keys are directly returned, so on python3 + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ @@ -1078,15 +1078,15 @@ class DbBsddbRead(DbReadBase, Callback): handle_list.sort(key=self.__sortbysource_key) return handle_list return [] - + def get_citation_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each Citation in the database. - + If sort_handles is True, the list is sorted by Citation Volume/Page. - - .. warning:: For speed the keys are directly returned, so on python3 + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ @@ -1096,15 +1096,15 @@ class DbBsddbRead(DbReadBase, Callback): handle_list.sort(key=self.__sortbycitation_key) return handle_list return [] - + def get_media_object_handles(self, sort_handles=False): """ Return a list of database handles, one handle for each MediaObject in - the database. - + the database. + If sort_handles is True, the list is sorted by title. - - .. warning:: For speed the keys are directly returned, so on python3 + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ @@ -1114,52 +1114,52 @@ class DbBsddbRead(DbReadBase, Callback): handle_list.sort(key=self.__sortbymedia_key) return handle_list return [] - + def get_event_handles(self): """ - Return a list of database handles, one handle for each Event in the - database. - - .. warning:: For speed the keys are directly returned, so on python3 + Return a list of database handles, one handle for each Event in the + database. + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ if self.db_is_open: return self.all_handles(self.event_map) return [] - + def get_family_handles(self): """ Return a list of database handles, one handle for each Family in the database. - - .. warning:: For speed the keys are directly returned, so on python3 + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ if self.db_is_open: return self.all_handles(self.family_map) return [] - + def get_repository_handles(self): """ Return a list of database handles, one handle for each Repository in the database. - - .. warning:: For speed the keys are directly returned, so on python3 + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ if self.db_is_open: return self.all_handles(self.repository_map) return [] - + def get_note_handles(self): """ - Return a list of database handles, one handle for each Note in the + Return a list of database handles, one handle for each Note in the database. - - .. warning:: For speed the keys are directly returned, so on python3 + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ @@ -1171,10 +1171,10 @@ class DbBsddbRead(DbReadBase, Callback): """ Return a list of database handles, one handle for each Tag in the database. - + If sort_handles is True, the list is sorted by Tag name. - - .. warning:: For speed the keys are directly returned, so on python3 + + .. warning:: For speed the keys are directly returned, so on python3 bytestrings are returned! Use constfunc.py handle2internal on this result! """ @@ -1208,7 +1208,7 @@ class DbBsddbRead(DbReadBase, Callback): iter_note_handles = _f(get_note_cursor) iter_tag_handles = _f(get_tag_cursor) del _f - + def _f(curs_, obj_): """ Closure that returns an iterator over objects in the database. @@ -1222,7 +1222,7 @@ class DbBsddbRead(DbReadBase, Callback): return g # Use closure to define iterators for each primary object type - + iter_people = _f(get_person_cursor, Person) iter_families = _f(get_family_cursor, Family) iter_events = _f(get_event_cursor, Event) @@ -1237,15 +1237,15 @@ class DbBsddbRead(DbReadBase, Callback): def get_gramps_ids(self, obj_key): key2table = { - PERSON_KEY: self.id_trans, - FAMILY_KEY: self.fid_trans, - SOURCE_KEY: self.sid_trans, - CITATION_KEY: self.cid_trans, - EVENT_KEY: self.eid_trans, - MEDIA_KEY: self.oid_trans, - PLACE_KEY: self.pid_trans, - REPOSITORY_KEY: self.rid_trans, - NOTE_KEY: self.nid_trans, + PERSON_KEY: self.id_trans, + FAMILY_KEY: self.fid_trans, + SOURCE_KEY: self.sid_trans, + CITATION_KEY: self.cid_trans, + EVENT_KEY: self.eid_trans, + MEDIA_KEY: self.oid_trans, + PLACE_KEY: self.pid_trans, + REPOSITORY_KEY: self.rid_trans, + NOTE_KEY: self.nid_trans, } table = key2table[obj_key] @@ -1253,15 +1253,15 @@ class DbBsddbRead(DbReadBase, Callback): def has_gramps_id(self, obj_key, gramps_id): key2table = { - PERSON_KEY: self.id_trans, - FAMILY_KEY: self.fid_trans, - SOURCE_KEY: self.sid_trans, - CITATION_KEY: self.cid_trans, - EVENT_KEY: self.eid_trans, - MEDIA_KEY: self.oid_trans, - PLACE_KEY: self.pid_trans, - REPOSITORY_KEY: self.rid_trans, - NOTE_KEY: self.nid_trans, + PERSON_KEY: self.id_trans, + FAMILY_KEY: self.fid_trans, + SOURCE_KEY: self.sid_trans, + CITATION_KEY: self.cid_trans, + EVENT_KEY: self.eid_trans, + MEDIA_KEY: self.oid_trans, + PLACE_KEY: self.pid_trans, + REPOSITORY_KEY: self.rid_trans, + NOTE_KEY: self.nid_trans, } table = key2table[obj_key] @@ -1327,10 +1327,10 @@ class DbBsddbRead(DbReadBase, Callback): def set_person_id_prefix(self, val): """ - Set the naming template for Gramps Person ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Person ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as I%d or I%04d. """ self.person_prefix = self._validated_id_prefix(val, "I") @@ -1338,32 +1338,32 @@ class DbBsddbRead(DbReadBase, Callback): def set_source_id_prefix(self, val): """ - Set the naming template for Gramps Source ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Source ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as S%d or S%04d. """ self.source_prefix = self._validated_id_prefix(val, "S") self.sid2user_format = self.__id2user_format(self.source_prefix) - + def set_citation_id_prefix(self, val): """ - Set the naming template for Gramps Citation ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Citation ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as C%d or C%04d. """ self.citation_prefix = self._validated_id_prefix(val, "C") self.cid2user_format = self.__id2user_format(self.citation_prefix) - + def set_object_id_prefix(self, val): """ - Set the naming template for Gramps MediaObject ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps MediaObject ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as O%d or O%04d. """ self.mediaobject_prefix = self._validated_id_prefix(val, "O") @@ -1371,10 +1371,10 @@ class DbBsddbRead(DbReadBase, Callback): def set_place_id_prefix(self, val): """ - Set the naming template for Gramps Place ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Place ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as P%d or P%04d. """ self.place_prefix = self._validated_id_prefix(val, "P") @@ -1392,10 +1392,10 @@ class DbBsddbRead(DbReadBase, Callback): def set_event_id_prefix(self, val): """ - Set the naming template for Gramps Event ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Event ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as E%d or E%04d. """ self.event_prefix = self._validated_id_prefix(val, "E") @@ -1403,10 +1403,10 @@ class DbBsddbRead(DbReadBase, Callback): def set_repository_id_prefix(self, val): """ - Set the naming template for Gramps Repository ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Repository ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as R%d or R%04d. """ self.repository_prefix = self._validated_id_prefix(val, "R") @@ -1414,10 +1414,10 @@ class DbBsddbRead(DbReadBase, Callback): def set_note_id_prefix(self, val): """ - Set the naming template for Gramps Note ID values. - - The string is expected to be in the form of a simple text string, or - in a format that contains a C/Python style format string using %d, + Set the naming template for Gramps Note ID values. + + The string is expected to be in the form of a simple text string, or + in a format that contains a C/Python style format string using %d, such as N%d or N%04d. """ self.note_prefix = self._validated_id_prefix(val, "N") @@ -1426,9 +1426,9 @@ class DbBsddbRead(DbReadBase, Callback): def set_undo_callback(self, callback): """ Define the callback function that is called whenever an undo operation - is executed. - - The callback function receives a single argument that is a text string + is executed. + + The callback function receives a single argument that is a text string that defines the operation. """ self.undo_callback = callback @@ -1436,9 +1436,9 @@ class DbBsddbRead(DbReadBase, Callback): def set_redo_callback(self, callback): """ Define the callback function that is called whenever an redo operation - is executed. - - The callback function receives a single argument that is a text string + is executed. + + The callback function receives a single argument that is a text string that defines the operation. """ self.redo_callback = callback @@ -1491,7 +1491,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_researcher(self): """ - Return the Researcher instance, providing information about the owner + Return the Researcher instance, providing information about the owner of the database. """ return self.owner @@ -1540,14 +1540,14 @@ class DbBsddbRead(DbReadBase, Callback): def get_person_attribute_types(self): """ - Return a list of all Attribute types assocated with Person instances + Return a list of all Attribute types assocated with Person instances in the database. """ return list(self.individual_attributes) def get_family_attribute_types(self): """ - Return a list of all Attribute types assocated with Family instances + Return a list of all Attribute types assocated with Family instances in the database. """ return list(self.family_attributes) @@ -1560,7 +1560,7 @@ class DbBsddbRead(DbReadBase, Callback): def get_media_attribute_types(self): """ - Return a list of all Attribute types assocated with Media and MediaRef + Return a list of all Attribute types assocated with Media and MediaRef instances in the database. """ return list(self.media_attributes) @@ -1602,14 +1602,14 @@ class DbBsddbRead(DbReadBase, Callback): def get_repository_types(self): """ - Return a list of all custom repository types assocated with Repository + Return a list of all custom repository types assocated with Repository instances in the database. """ return list(self.repository_types) def get_note_types(self): """ - Return a list of all custom note types assocated with Note instances + Return a list of all custom note types assocated with Note instances in the database. """ return list(self.note_types) @@ -1623,14 +1623,14 @@ class DbBsddbRead(DbReadBase, Callback): def get_source_media_types(self): """ - Return a list of all custom source media types assocated with Source + Return a list of all custom source media types assocated with Source instances in the database. """ return list(self.source_media_types) def get_url_types(self): """ - Return a list of all custom names types assocated with Url instances + Return a list of all custom names types assocated with Url instances in the database. """ return list(self.url_types) @@ -1643,7 +1643,7 @@ class DbBsddbRead(DbReadBase, Callback): return list(self.place_types) def __log_error(self): - pass + pass def __get_raw_data(self, table, handle): """ @@ -1658,7 +1658,7 @@ class DbBsddbRead(DbReadBase, Callback): except DBERRS as msg: self.__log_error() raise DbError(msg) - + def get_raw_person_data(self, handle): return self.__get_raw_data(self.person_map, handle) @@ -1700,14 +1700,14 @@ class DbBsddbRead(DbReadBase, Callback): except DBERRS as msg: self.__log_error() raise DbError(msg) - + def has_person_handle(self, handle): """ Return True if the handle exists in the current Person database. """ return self.__has_handle(self.person_map, handle) - def has_family_handle(self, handle): + def has_family_handle(self, handle): """ Return True if the handle exists in the current Family database. """ @@ -1764,7 +1764,7 @@ class DbBsddbRead(DbReadBase, Callback): def __sortbyperson_key(self, handle): if isinstance(handle, str): handle = handle.encode('utf-8') - return glocale.sort_key(find_surname(handle, + return glocale.sort_key(find_surname(handle, self.person_map.get(handle))) def __sortbyplace(self, first, second): @@ -1772,7 +1772,7 @@ class DbBsddbRead(DbReadBase, Callback): first = first.encode('utf-8') if isinstance(second, str): second = second.encode('utf-8') - return glocale.strcoll(self.place_map.get(first)[2], + return glocale.strcoll(self.place_map.get(first)[2], self.place_map.get(second)[2]) def __sortbyplace_key(self, place): @@ -1788,7 +1788,7 @@ class DbBsddbRead(DbReadBase, Callback): source1 = str(self.source_map[first][2]) source2 = str(self.source_map[second][2]) return glocale.strcoll(source1, source2) - + def __sortbysource_key(self, key): if isinstance(key, str): key = key.encode('utf-8') @@ -1803,7 +1803,7 @@ class DbBsddbRead(DbReadBase, Callback): citation1 = str(self.citation_map[first][3]) citation2 = str(self.citation_map[second][3]) return glocale.strcoll(citation1, citation2) - + def __sortbycitation_key(self, key): if isinstance(key, str): key = key.encode('utf-8') @@ -1854,7 +1854,7 @@ class DbBsddbRead(DbReadBase, Callback): def find_backlink_handles(self, handle, include_classes=None): """ Find all objects that hold a reference to the object handle. - + Returns an interator over alist of (class_name, handle) tuples. :param handle: handle of the object to search for. @@ -1862,7 +1862,7 @@ class DbBsddbRead(DbReadBase, Callback): :param include_classes: list of class names to include in the results. Defaults to None, which includes all classes. :type include_classes: list of class names - + This default implementation does a sequencial scan through all the primary object databases and is very slow. Backends can override this method to provide much faster implementations that @@ -1878,43 +1878,43 @@ class DbBsddbRead(DbReadBase, Callback): # each of the primary object tables. primary_tables = { 'Person': { - 'cursor_func': self.get_person_cursor, + 'cursor_func': self.get_person_cursor, 'class_func': Person, - }, + }, 'Family': { - 'cursor_func': self.get_family_cursor, + 'cursor_func': self.get_family_cursor, 'class_func': Family, - }, + }, 'Event': { - 'cursor_func': self.get_event_cursor, + 'cursor_func': self.get_event_cursor, 'class_func': Event, - }, + }, 'Place': { - 'cursor_func': self.get_place_cursor, + 'cursor_func': self.get_place_cursor, 'class_func': Place, - }, + }, 'Source': { - 'cursor_func': self.get_source_cursor, + 'cursor_func': self.get_source_cursor, 'class_func': Source, - }, + }, 'Citation': { - 'cursor_func': self.get_citation_cursor, + 'cursor_func': self.get_citation_cursor, 'class_func': Citation, - }, + }, 'MediaObject': { - 'cursor_func': self.get_media_cursor, + 'cursor_func': self.get_media_cursor, 'class_func': MediaObject, - }, + }, 'Repository': { - 'cursor_func': self.get_repository_cursor, + 'cursor_func': self.get_repository_cursor, 'class_func': Repository, }, 'Note': { - 'cursor_func': self.get_note_cursor, + 'cursor_func': self.get_note_cursor, 'class_func': Note, }, 'Tag': { - 'cursor_func': self.get_tag_cursor, + 'cursor_func': self.get_tag_cursor, 'class_func': Tag, }, } @@ -1924,7 +1924,7 @@ class DbBsddbRead(DbReadBase, Callback): the_tables = list(primary_tables.keys()) else: the_tables = include_classes - + # Now we use the functions and classes defined above to loop through # each of the existing primary object tables for primary_table_name, funcs in the_tables.items(): @@ -1939,7 +1939,7 @@ class DbBsddbRead(DbReadBase, Callback): # Now we need to loop over all object types # that have been requests in the include_classes list - for classname in primary_tables: + for classname in primary_tables: if obj.has_handle_reference(classname, handle): yield (primary_table_name, found_handle) return diff --git a/gramps/plugins/database/bsddb_support/summary.py b/gramps/plugins/database/bsddb_support/summary.py index ccc94d2dc..8aefd705d 100644 --- a/gramps/plugins/database/bsddb_support/summary.py +++ b/gramps/plugins/database/bsddb_support/summary.py @@ -20,11 +20,11 @@ def get_dbdir_summary(dirpath, name): bsddb_version = vers_file.readline().strip() else: return "Unknown", "Unknown", "Unknown" - + current_bsddb_version = str(db.version()) if bsddb_version != current_bsddb_version: return "Unknown", bsddb_version, "Unknown" - + env = db.DBEnv() flags = db.DB_CREATE | db.DB_PRIVATE |\ db.DB_INIT_MPOOL |\ diff --git a/gramps/plugins/database/bsddb_support/test/cursor_test.py b/gramps/plugins/database/bsddb_support/test/cursor_test.py index 53297e7f4..beae6ae77 100644 --- a/gramps/plugins/database/bsddb_support/test/cursor_test.py +++ b/gramps/plugins/database/bsddb_support/test/cursor_test.py @@ -36,7 +36,7 @@ class Data(object): ## def __repr__(self): ## return repr((self.handle,self.surname,self.name)) - + class CursorTest(unittest.TestCase): """Test the cursor handling.""" @@ -73,7 +73,7 @@ class CursorTest(unittest.TestCase): self.env.open(env_name,env_flags) (self.person_map,self.surnames) = self._open_tables() (self.place_map, self.placerefs) = self._open_treetables() - + def _open_tables(self): dbmap = dbshelve.DBShelf(self.env) dbmap.db.set_pagesize(16384) @@ -87,13 +87,13 @@ class CursorTest(unittest.TestCase): surnames.set_flags(db.DB_DUP|db.DB_DUPSORT) surnames.open(self.full_name, "surnames", db.DB_BTREE, flags=table_flags) - + def find_surname(key,data): val = data.surname if isinstance(val, str): val = val.encode('utf-8') return val - + person_map.associate(surnames, find_surname, table_flags) return (person_map,surnames) @@ -129,7 +129,7 @@ class CursorTest(unittest.TestCase): self.placerefs.close() self.env.close() shutil.rmtree(self._tmpdir) - + def test_simple_insert(self): """test insert and retrieve works.""" @@ -137,27 +137,27 @@ class CursorTest(unittest.TestCase): the_txn = self.env.txn_begin() self.person_map.put(data.handle, data, txn=the_txn) the_txn.commit() - + v = self.person_map.get(data.handle) self.assertEqual(v.handle, data.handle) def test_insert_with_curor_closed(self): """test_insert_with_curor_closed""" - + cursor_txn = self.env.txn_begin() - + cursor = self.surnames.cursor(txn=cursor_txn) cursor.first() cursor.next() cursor.close() cursor_txn.commit() - + data = Data(b'2', 'surname2', 'name2') the_txn = self.env.txn_begin() self.person_map.put(data.handle, data, txn=the_txn) the_txn.commit() - + v = self.person_map.get(data.handle) self.assertEqual(v.handle, data.handle) @@ -165,20 +165,20 @@ class CursorTest(unittest.TestCase): @unittest.skip("Insert expected to fail with open cursor") def test_insert_with_curor_open(self): """test_insert_with_curor_open""" - + cursor_txn = self.env.txn_begin() cursor = self.surnames.cursor(txn=cursor_txn) cursor.first() cursor.next() - + data = Data(b'2', 'surname2', 'name2') the_txn = self.env.txn_begin() self.person_map.put(data.handle, data, txn=the_txn) the_txn.commit() - + cursor.close() cursor_txn.commit() - + v = self.person_map.get(data.handle) self.assertEqual(v.handle, data.handle) @@ -188,20 +188,20 @@ class CursorTest(unittest.TestCase): """test_insert_with_curor_open_and_db_open""" (person2,surnames2) = self._open_tables() - + cursor_txn = self.env.txn_begin() cursor = surnames2.cursor(txn=cursor_txn) cursor.first() cursor.next() - + data = Data(b'2', 'surname2', 'name2') the_txn = self.env.txn_begin() self.person_map.put(data.handle, data, txn=the_txn) the_txn.commit() - + cursor.close() cursor_txn.commit() - + v = self.person_map.get(data.handle) self.assertEqual(v.handle, data.handle) @@ -223,7 +223,7 @@ class CursorTest(unittest.TestCase): cursor = DbBsddbTreeCursor(self.placerefs, self.place_map, False, cursor_txn) placenames = set([d[1] for handle, d in cursor]) - + cursor.close() cursor_txn.commit() pldata = set([d[1] for d in data]) diff --git a/gramps/plugins/database/bsddb_support/test/grampsdbtestbase.py b/gramps/plugins/database/bsddb_support/test/grampsdbtestbase.py index 35cb9f93f..02ed1b2a4 100644 --- a/gramps/plugins/database/bsddb_support/test/grampsdbtestbase.py +++ b/gramps/plugins/database/bsddb_support/test/grampsdbtestbase.py @@ -25,18 +25,18 @@ import shutil from .. import DbBsddb, DbTxn from gramps.cli.clidbman import CLIDbManager from gramps.gen.dbstate import DbState -from gramps.gen.lib import (Source, RepoRef, Citation, Repository, Person, +from gramps.gen.lib import (Source, RepoRef, Citation, Repository, Person, Family, Event, Place, MediaObject) class GrampsDbBaseTest(unittest.TestCase): """Base class for unittest that need to be able to create test databases.""" - - def setUp(self): + + def setUp(self): def dummy_callback(dummy): pass self._tmpdir = tempfile.mkdtemp() - + self._db = DbBsddb() dbman = CLIDbManager(DbState()) self._filename, title = dbman.create_new_db_cli(title="Test") @@ -69,7 +69,7 @@ class GrampsDbBaseTest(unittest.TestCase): (num_events, self._add_event_with_sources), (num_places, self._add_place_with_sources), (num_media_objects, self._add_media_object_with_sources)): - + source_idx = 1 for person_idx in xrange(0, num): @@ -108,7 +108,7 @@ class GrampsDbBaseTest(unittest.TestCase): def _add_repository(self): # Add a Repository - + with DbTxn("Add Repository", self._db) as tran: repos = Repository() self._db.add_repository(repos, tran) @@ -116,8 +116,8 @@ class GrampsDbBaseTest(unittest.TestCase): return repos - - def _add_object_with_source(self, citations, object_class, add_method, + + def _add_object_with_source(self, citations, object_class, add_method, commit_method): object = object_class() diff --git a/gramps/plugins/database/bsddb_support/test/reference_map_test.py b/gramps/plugins/database/bsddb_support/test/reference_map_test.py index a374c8d2b..c5f3cc478 100644 --- a/gramps/plugins/database/bsddb_support/test/reference_map_test.py +++ b/gramps/plugins/database/bsddb_support/test/reference_map_test.py @@ -40,7 +40,7 @@ class ReferenceMapTest(GrampsDbBaseTest): citation = self._add_source() person = self._add_person_with_sources([citation]) - + references = list(self._db.find_backlink_handles(citation.get_handle())) self.assertEqual(len(references), 1) @@ -51,7 +51,7 @@ class ReferenceMapTest(GrampsDbBaseTest): repos = self._add_repository() citation = self._add_source(repos=repos) - + references = list(self._db.find_backlink_handles(repos.get_handle())) self.assertEqual(len(references), 1) @@ -77,24 +77,24 @@ class ReferenceMapTest(GrampsDbBaseTest): # make sure that we have the correct number of references (one for each object) references = list(self._db.find_backlink_handles(citation.get_handle())) - self.assertEqual(len(references), 5, + self.assertEqual(len(references), 5, "len(references) == %s " % str(len(references))) # should just return the person reference references = [ref for ref in self._db.find_backlink_handles(citation.get_handle(), (Person.__name__,))] - self.assertEqual(len(references), 1, + self.assertEqual(len(references), 1, "len(references) == %s " % str(len(references))) - self.assertEqual(references[0][0], Person.__name__, + self.assertEqual(references[0][0], Person.__name__, "references = %s" % repr(references)) # should just return the person and event reference references = list(self._db.find_backlink_handles(citation.get_handle(), (Person.__name__, Event.__name__))) - self.assertEqual(len(references), 2, + self.assertEqual(len(references), 2, "len(references) == %s " % str(len(references))) - self.assertEqual(references[0][0], Person.__name__, + self.assertEqual(references[0][0], Person.__name__, "references = %s" % repr(references)) - self.assertEqual(references[1][0], Event.__name__, + self.assertEqual(references[1][0], Event.__name__, "references = %s" % repr(references)) def test_delete_primary(self): @@ -103,17 +103,17 @@ class ReferenceMapTest(GrampsDbBaseTest): citation = self._add_source() person = self._add_person_with_sources([citation]) - + self.assertIsNotNone(self._db.get_person_from_handle(person.get_handle())) - + with DbTxn("Del Person", self._db) as tran: self._db.remove_person(person.get_handle(),tran) self.assertIsNone(self._db.get_person_from_handle(person.get_handle())) - + references = list(self._db.find_backlink_handles(citation.get_handle())) - self.assertEqual(len(references), 0, + self.assertEqual(len(references), 0, "len(references) == %s " % str(len(references))) def test_reindex_reference_map(self): @@ -121,7 +121,7 @@ class ReferenceMapTest(GrampsDbBaseTest): def cb(count): pass - + # unhook the reference_map update function so that we # can insert some records without the reference_map being updated. update_method = self._db.update_reference_map @@ -134,7 +134,7 @@ class ReferenceMapTest(GrampsDbBaseTest): # Check that the reference map does not contain the reference. references = list(self._db.find_backlink_handles(citation.get_handle())) - self.assertEqual(len(references), 0, + self.assertEqual(len(references), 0, "len(references) == %s " % str(len(references))) # Reinstate the reference_map method and reindex the database @@ -144,7 +144,7 @@ class ReferenceMapTest(GrampsDbBaseTest): # Check that the reference now appears in the reference_map references = list(self._db.find_backlink_handles(citation.get_handle())) - self.assertEqual(len(references), 1, + self.assertEqual(len(references), 1, "len(references) == %s " % str(len(references))) def perf_simple_search_speed(self): @@ -156,7 +156,7 @@ class ReferenceMapTest(GrampsDbBaseTest): num_places = 10 num_media_objects = 10 num_links = 10 - + self._populate_database(num_sources, num_persons, num_families, @@ -178,7 +178,7 @@ class ReferenceMapTest(GrampsDbBaseTest): with_reference_map = end - start remember = self._db.__class__.find_backlink_handles - + self._db.__class__.find_backlink_handles = self._db.__class__.__base__.find_backlink_handles start = time.time() @@ -186,11 +186,11 @@ class ReferenceMapTest(GrampsDbBaseTest): end = time.time() without_reference_map = end - start - + self._db.__class__.find_backlink_handles = remember logger.info("search test with following data: \n" - "num_sources = %d \n" + "num_sources = %d \n" "num_persons = %d \n" "num_families = %d \n" "num_events = %d \n" @@ -206,7 +206,7 @@ class ReferenceMapTest(GrampsDbBaseTest): logger.info("with refs %s\n", str(with_reference_map)) logger.info("without refs %s\n", str(without_reference_map)) - self.assertLess(with_reference_map, without_reference_map / 10, + self.assertLess(with_reference_map, without_reference_map / 10, "Reference_map should an order of magnitude faster.") def testSuite(): diff --git a/gramps/plugins/database/bsddb_support/undoredo.py b/gramps/plugins/database/bsddb_support/undoredo.py index da6b3368e..babcc942d 100644 --- a/gramps/plugins/database/bsddb_support/undoredo.py +++ b/gramps/plugins/database/bsddb_support/undoredo.py @@ -42,7 +42,7 @@ except: DBAccessError = 0 DBPageNotFoundError = 0 DBInvalidArgError = 0 - + from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext @@ -61,9 +61,9 @@ from gramps.gen.errors import DbError # Local Constants # #------------------------------------------------------------------------- -DBERRS = (db.DBRunRecoveryError, db.DBAccessError, +DBERRS = (db.DBRunRecoveryError, db.DBAccessError, db.DBPageNotFoundError, db.DBInvalidArgError) - + _SIGBASE = ('person', 'family', 'source', 'event', 'media', 'place', 'repository', 'reference', 'note', 'tag', 'citation') @@ -71,7 +71,7 @@ _SIGBASE = ('person', 'family', 'source', 'event', 'media', # # DbUndo class # -#------------------------------------------------------------------------- +#------------------------------------------------------------------------- class DbUndo(object): """ Base class for the Gramps undo/redo manager. Needs to be subclassed @@ -141,34 +141,34 @@ class DbUndo(object): """ Close the backing storage. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def append(self, value): """ Add a new entry on the end. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def __getitem__(self, index): """ Returns an entry by index number. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def __setitem__(self, index, value): """ Set an entry to a value. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def __len__(self): """ Returns the number of entries. Needs to be overridden in the derived class. - """ + """ raise NotImplementedError def commit(self, txn, msg): @@ -216,12 +216,12 @@ class DbUndo(object): self.db._log_error() raise DbError(msg) - return try_ + return try_ @undoredo def __undo(self, update_history=True): """ - Access the last committed transaction, and revert the data to the + Access the last committed transaction, and revert the data to the state before the transaction was committed. """ txn = self.undoq.pop() @@ -246,7 +246,7 @@ class DbUndo(object): db.undo_callback(_("_Undo %s") % self.undoq[-1].get_description()) else: - db.undo_callback(None) + db.undo_callback(None) if db.redo_callback: db.redo_callback(_("_Redo %s") @@ -259,7 +259,7 @@ class DbUndo(object): @undoredo def __redo(self, db=None, update_history=True): """ - Access the last undone transaction, and revert the data to the state + Access the last undone transaction, and revert the data to the state before the transaction was undone. """ txn = self.redoq.pop() @@ -289,11 +289,11 @@ class DbUndo(object): db.redo_callback(_("_Redo %s") % new_transaction.get_description()) else: - db.redo_callback(None) + db.redo_callback(None) if update_history and db.undo_history_callback: db.undo_history_callback() - return True + return True def undo_reference(self, data, handle, db_map): """ @@ -409,7 +409,7 @@ class DbUndoBSDDB(DbUndo): """ path = self.path self.undodb.open(path, db.DB_RECNO, db.DB_CREATE) - + def close(self): """ Close the undo/redo database @@ -418,12 +418,12 @@ class DbUndoBSDDB(DbUndo): self.undodb = None self.mapbase = None self.db = None - + try: os.remove(self.path) except OSError: pass - self.clear() + self.clear() def append(self, value): """ diff --git a/gramps/plugins/database/bsddb_support/upgrade.py b/gramps/plugins/database/bsddb_support/upgrade.py index ef9b62495..c7d3d9d49 100644 --- a/gramps/plugins/database/bsddb_support/upgrade.py +++ b/gramps/plugins/database/bsddb_support/upgrade.py @@ -50,8 +50,8 @@ from gramps.gen.utils.file import create_checksum from gramps.gen.utils.id import create_id from . import BSDDBTxn from .write import _mkname, SURNAMES -from gramps.gen.db.dbconst import (PERSON_KEY, FAMILY_KEY, EVENT_KEY, - MEDIA_KEY, PLACE_KEY, REPOSITORY_KEY, +from gramps.gen.db.dbconst import (PERSON_KEY, FAMILY_KEY, EVENT_KEY, + MEDIA_KEY, PLACE_KEY, REPOSITORY_KEY, SOURCE_KEY) from gramps.gui.dialog import (InfoDialog) @@ -110,9 +110,9 @@ def gramps_upgrade_18(self): def gramps_upgrade_17(self): """ - Upgrade database from version 16 to 17. + Upgrade database from version 16 to 17. - 1. This upgrade adds tags to event, place, repository, source and + 1. This upgrade adds tags to event, place, repository, source and citation objects. 2. Data of Source becomes SourceAttributes Secondary Object 3. Create a place hierarchy. @@ -173,7 +173,7 @@ def gramps_upgrade_17(self): for level, name in enumerate(main_loc): if name: break - + loc = list(main_loc[:]) loc[level] = '' @@ -281,10 +281,10 @@ def gramps_upgrade_17(self): for handle in self.citation_map.keys(): citation = self.citation_map[handle] - (handle, gramps_id, datelist, page, confidence, source_handle, + (handle, gramps_id, datelist, page, confidence, source_handle, notelist, medialist, datamap, change, taglist, private) = citation srcattributelist = upgrade_datamap_17(datamap) - new_citation = (handle, gramps_id, datelist, page, confidence, source_handle, + new_citation = (handle, gramps_id, datelist, page, confidence, source_handle, notelist, medialist, srcattributelist, change, taglist, private) with BSDDBTxn(self.env, self.citation_map) as txn: if isinstance(handle, str): @@ -362,15 +362,15 @@ def gramps_upgrade_16(self): """ Upgrade database from version 15 to 16. This upgrade converts all SourceRef child objects to Citation Primary objects. - - For each primary object that has a sourceref, what we have to do is: + + For each primary object that has a sourceref, what we have to do is: (1) create each citation (2) update the object to reference the Citations (3) remove backlinks for references from object to Source (4) add backlinks for references from object to Citations (5) add backlinks for references from Citation to Source - + the backlinks are all updated at the end by calling :py:meth:`reindex_reference_map <.write.DbBsddb.reindex_reference_map>` """ @@ -384,16 +384,16 @@ def gramps_upgrade_16(self): self.set_total(length) # Setup data for upgrade statistics information dialogue - keyorder = [PERSON_KEY, FAMILY_KEY, EVENT_KEY, MEDIA_KEY, + keyorder = [PERSON_KEY, FAMILY_KEY, EVENT_KEY, MEDIA_KEY, PLACE_KEY, REPOSITORY_KEY, SOURCE_KEY] key2data = { PERSON_KEY : 0, FAMILY_KEY : 1, - EVENT_KEY: 2, - MEDIA_KEY: 3, + EVENT_KEY: 2, + MEDIA_KEY: 3, PLACE_KEY: 4, REPOSITORY_KEY: 5, - SOURCE_KEY : 6, + SOURCE_KEY : 6, } key2string = { PERSON_KEY : _('%(n1)6d People upgraded with %(n2)6d citations in %(n3)6d secs\n'), @@ -425,10 +425,10 @@ def gramps_upgrade_16(self): " ".join([name[0] for name in person[3][5]]))) except: pass - (handle, gramps_id, gender, primary_name, alternate_names, - death_ref_index, birth_ref_index, event_ref_list, family_list, - parent_family_list, media_list, address_list, attribute_list, - urls, lds_seal_list, source_list, note_list, change, tag_list, + (handle, gramps_id, gender, primary_name, alternate_names, + death_ref_index, birth_ref_index, event_ref_list, family_list, + parent_family_list, media_list, address_list, attribute_list, + urls, lds_seal_list, source_list, note_list, change, tag_list, private, person_ref_list) = person if primary_name: primary_name = upgrade_name_16(self, primary_name) @@ -460,12 +460,12 @@ def gramps_upgrade_16(self): if primary_name or alternate_names or address_list or \ media_list or attribute_list or lds_seal_list or source_list or \ person_ref_list or event_ref_list: - new_person = (handle, gramps_id, gender, primary_name, - alternate_names, death_ref_index, - birth_ref_index, event_ref_list, family_list, - parent_family_list, media_list, address_list, - attribute_list, urls, lds_seal_list, - new_citation_list, note_list, change, tag_list, + new_person = (handle, gramps_id, gender, primary_name, + alternate_names, death_ref_index, + birth_ref_index, event_ref_list, family_list, + parent_family_list, media_list, address_list, + attribute_list, urls, lds_seal_list, + new_citation_list, note_list, change, tag_list, private, person_ref_list) LOG.debug(" upgrade new_person %s" % [new_person]) with BSDDBTxn(self.env, self.person_map) as txn: @@ -474,9 +474,9 @@ def gramps_upgrade_16(self): txn.put(handle, new_person) self.update() - LOG.debug("%d persons upgraded with %d citations in %d seconds. " % - (len(list(self.person_map.keys())), - self.cmap_index - start_num_citations, + LOG.debug("%d persons upgraded with %d citations in %d seconds. " % + (len(list(self.person_map.keys())), + self.cmap_index - start_num_citations, time.time() - start_time)) data_upgradeobject[key2data[PERSON_KEY]] = (len(list(self.person_map.keys())), self.cmap_index - start_num_citations, @@ -497,9 +497,9 @@ def gramps_upgrade_16(self): self, source_list) new_attribute_list = upgrade_attribute_list_16( self, attribute_list) - + new_media = (handle, gramps_id, path, mime, desc, - new_attribute_list, new_citation_list, note_list, + new_attribute_list, new_citation_list, note_list, change, date, tag_list, private) LOG.debug(" upgrade new_media %s" % [new_media]) with BSDDBTxn(self.env, self.media_map) as txn: @@ -508,9 +508,9 @@ def gramps_upgrade_16(self): txn.put(handle, new_media) self.update() - LOG.debug("%d media objects upgraded with %d citations in %d seconds" % + LOG.debug("%d media objects upgraded with %d citations in %d seconds" % (len(self.media_map.keys()), - self.cmap_index - start_num_citations, + self.cmap_index - start_num_citations, int(time.time() - start_time))) data_upgradeobject[key2data[MEDIA_KEY]] = (len(list(self.media_map.keys())), self.cmap_index - start_num_citations, @@ -536,9 +536,9 @@ def gramps_upgrade_16(self): media_list = upgrade_media_list_16( self, media_list) if source_list or media_list: - new_place = (handle, gramps_id, title, + new_place = (handle, gramps_id, title, longi, lat, main_loc, alt_loc, urls, - media_list, new_citation_list, note_list, + media_list, new_citation_list, note_list, change, private) LOG.debug(" upgrade new_place %s" % [new_place]) with BSDDBTxn(self.env, self.place_map) as txn: @@ -547,9 +547,9 @@ def gramps_upgrade_16(self): txn.put(handle, new_place) self.update() - LOG.debug("%d places upgraded with %d citations in %d seconds. " % - (len(list(self.place_map.keys())), - self.cmap_index - start_num_citations, + LOG.debug("%d places upgraded with %d citations in %d seconds. " % + (len(list(self.place_map.keys())), + self.cmap_index - start_num_citations, time.time() - start_time)) data_upgradeobject[key2data[PLACE_KEY]] = (len(list(self.place_map.keys())), self.cmap_index - start_num_citations, @@ -590,7 +590,7 @@ def gramps_upgrade_16(self): attribute_list or lds_seal_list or event_ref_list: new_family = (handle, gramps_id, father_handle, mother_handle, child_ref_list, the_type, event_ref_list, media_list, - attribute_list, lds_seal_list, new_citation_list, + attribute_list, lds_seal_list, new_citation_list, note_list, change, tag_list, private) LOG.debug(" upgrade new_family %s" % [new_family]) with BSDDBTxn(self.env, self.family_map) as txn: @@ -599,9 +599,9 @@ def gramps_upgrade_16(self): txn.put(handle, new_family) self.update() - LOG.debug("%d families upgraded with %d citations in %d seconds. " % - (len(list(self.family_map.keys())), - self.cmap_index - start_num_citations, + LOG.debug("%d families upgraded with %d citations in %d seconds. " % + (len(list(self.family_map.keys())), + self.cmap_index - start_num_citations, time.time() - start_time)) data_upgradeobject[key2data[FAMILY_KEY]] = (len(list(self.family_map.keys())), self.cmap_index - start_num_citations, @@ -614,7 +614,7 @@ def gramps_upgrade_16(self): for event_handle in self.event_map.keys(): event = self.event_map[event_handle] LOG.debug("upgrade event %s" % event[4]) - (handle, gramps_id, the_type, date, description, place, + (handle, gramps_id, the_type, date, description, place, source_list, note_list, media_list, attribute_list, change, private) = event if source_list: @@ -631,7 +631,7 @@ def gramps_upgrade_16(self): if source_list or attribute_list or media_list: new_event = (handle, gramps_id, the_type, date, description, place, new_citation_list, note_list, media_list, - attribute_list, + attribute_list, change, private) LOG.debug(" upgrade new_event %s" % [new_event]) with BSDDBTxn(self.env, self.event_map) as txn: @@ -640,9 +640,9 @@ def gramps_upgrade_16(self): txn.put(handle, new_event) self.update() - LOG.debug("%d events upgraded with %d citations in %d seconds. " % - (len(self.event_map.keys()), - self.cmap_index - start_num_citations, + LOG.debug("%d events upgraded with %d citations in %d seconds. " % + (len(self.event_map.keys()), + self.cmap_index - start_num_citations, time.time() - start_time)) data_upgradeobject[key2data[EVENT_KEY]] = (len(list(self.event_map.keys())), self.cmap_index - start_num_citations, @@ -671,9 +671,9 @@ def gramps_upgrade_16(self): txn.put(handle, new_repository) self.update() - LOG.debug("%d repositories upgraded with %d citations in %d seconds. " % - (len(list(self.repository_map.keys())), - self.cmap_index - start_num_citations, + LOG.debug("%d repositories upgraded with %d citations in %d seconds. " % + (len(list(self.repository_map.keys())), + self.cmap_index - start_num_citations, time.time() - start_time)) data_upgradeobject[key2data[REPOSITORY_KEY]] = (len(list(self.repository_map.keys())), self.cmap_index - start_num_citations, @@ -694,7 +694,7 @@ def gramps_upgrade_16(self): if media_list: media_list = upgrade_media_list_16( self, media_list) - + new_source = (handle, gramps_id, title, author, pubinfo, note_list, media_list, abbrev, change, datamap, reporef_list, @@ -706,9 +706,9 @@ def gramps_upgrade_16(self): txn.put(handle, new_source) self.update() - LOG.debug("%d sources upgraded with %d citations in %d seconds" % - (len(self.source_map.keys()), - self.cmap_index - start_num_citations, + LOG.debug("%d sources upgraded with %d citations in %d seconds" % + (len(self.source_map.keys()), + self.cmap_index - start_num_citations, int(time.time() - start_time))) data_upgradeobject[key2data[SOURCE_KEY]] = (len(self.source_map.keys()), self.cmap_index - start_num_citations, @@ -716,18 +716,18 @@ def gramps_upgrade_16(self): # --------------------------------- - + # --------------------------------- # Example database from repository took: # 3403 events upgraded with 8 citations in 23 seconds. Backlinks took 1071 seconds # actually 4 of these citations were from: - # Media upgrade 4 citations upgraded in 4 seconds + # Media upgrade 4 citations upgraded in 4 seconds # by only doing the backlinks when there might be something to do, # improved to: # 3403 events upgraded with 8 citations in 19 seconds. Backlinks took 1348 seconds # further improved by skipping debug logging: # 3403 events upgraded with 8 citations in 2 seconds. Backlinks took 167 seconds - + #Number of new objects upgraded: # 2090 People upgraded with 2092 citations in 2148 secs # 734 Families upgraded with 735 citations in 768 secs @@ -785,7 +785,7 @@ def gramps_upgrade_16(self): # Bump up database version. Separate transaction to save metadata. with BSDDBTxn(self.env, self.metadata) as txn: txn.put(b'version', 16) - + LOG.debug([data_upgradeobject]) txt = _("Number of new objects upgraded:\n") for key in keyorder: @@ -810,7 +810,7 @@ def upgrade_media_list_16(self, media_list): self, source_list) new_attribute_list = upgrade_attribute_list_16( self, attribute_list) - new_media = (privacy, new_citation_list, note_list, new_attribute_list, + new_media = (privacy, new_citation_list, note_list, new_attribute_list, ref, rect) new_media_list.append((new_media)) return new_media_list @@ -818,15 +818,15 @@ def upgrade_media_list_16(self, media_list): def upgrade_attribute_list_16(self, attribute_list): new_attribute_list = [] for attribute in attribute_list: - (privacy, source_list, note_list, the_type, + (privacy, source_list, note_list, the_type, value) = attribute new_citation_list = convert_source_list_to_citation_list_16( self, source_list) - new_attribute = (privacy, new_citation_list, note_list, + new_attribute = (privacy, new_citation_list, note_list, the_type, value) new_attribute_list.append((new_attribute)) return new_attribute_list - + def upgrade_child_ref_list_16(self, child_ref_list): new_child_ref_list = [] for child_ref in child_ref_list: @@ -867,13 +867,13 @@ def upgrade_name_list_16(self, name_list): return new_name_list def upgrade_name_16(self, name): - (privacy, source_list, note, date, first_name, surname_list, suffix, - title, name_type, group_as, sort_as, display_as, call, nick, + (privacy, source_list, note, date, first_name, surname_list, suffix, + title, name_type, group_as, sort_as, display_as, call, nick, famnick) = name new_citation_list = convert_source_list_to_citation_list_16( self, source_list) - new_name = (privacy, new_citation_list, note, date, first_name, - surname_list, suffix, title, name_type, group_as, sort_as, + new_name = (privacy, new_citation_list, note, date, first_name, + surname_list, suffix, title, name_type, group_as, sort_as, display_as, call, nick, famnick) return new_name @@ -1132,7 +1132,7 @@ def convert_marker(self, marker_field): marker = MarkerType() marker.unserialize(marker_field) tag_name = str(marker) - + if tag_name != '': if tag_name not in self.tags: tag = Tag() @@ -1153,7 +1153,7 @@ def convert_marker(self, marker_field): def convert_locbase(loc): """Convert location base to include an empty locality field.""" return tuple([loc[0], ''] + list(loc[1:])) - + def convert_location(loc): """Convert a location into the new format.""" return (convert_locbase(loc[0]), loc[1]) @@ -1163,15 +1163,15 @@ def convert_address(addr): return (addr[0], addr[1], addr[2], addr[3], convert_locbase(addr[4])) def convert_name_15(name): - (privacy, source_list, note_list, date, + (privacy, source_list, note_list, date, first_name, surname, suffix, title, name_type, prefix, patronymic, group_as, sort_as, display_as, call) = name - + connector = "" origintype = (NameOriginType.NONE, "") patorigintype = (NameOriginType.PATRONYMIC, "") - + if patronymic.strip() == "": #no patronymic, create a single surname surname_list = [(surname, prefix, True, origintype, connector)] @@ -1183,7 +1183,7 @@ def convert_name_15(name): #two surnames, first patronymic, then surname which is primary surname_list = [(patronymic, "", False, patorigintype, ""), (surname, prefix, True, origintype, connector)] - + #return new value, add two empty strings for nick and family nick return (privacy, source_list, note_list, date, first_name, surname_list, suffix, title, name_type, @@ -1221,7 +1221,7 @@ def gramps_upgrade_14(self): # update dates with newyear for handle in self.event_map.keys(): event = self.event_map[handle] - (junk_handle, gramps_id, the_type, date, description, place, + (junk_handle, gramps_id, the_type, date, description, place, source_list, note_list, media_list, attribute_list, change, marker, private) = event new_date = convert_date_14(date) @@ -1229,7 +1229,7 @@ def gramps_upgrade_14(self): new_media_list = new_media_list_14(media_list) new_attribute_list = new_attribute_list_14(attribute_list) new_event = (junk_handle, gramps_id, the_type, new_date, - description, place, new_source_list, note_list, + description, place, new_source_list, note_list, new_media_list, new_attribute_list, change,marker,private) with BSDDBTxn(self.env, self.event_map) as txn: if isinstance(handle, str): @@ -1271,7 +1271,7 @@ def gramps_upgrade_14(self): (privacy, asource_list, anote_list, date, location) = address new_date = convert_date_14(date) new_asource_list = new_source_list_14(asource_list) - new_address_list.append((privacy, new_asource_list, anote_list, + new_address_list.append((privacy, new_asource_list, anote_list, new_date, location)) new_ord_list = [] for ldsord in lds_ord_list: @@ -1279,14 +1279,14 @@ def gramps_upgrade_14(self): famc, temple, status, lprivate) = ldsord new_date = convert_date_14(date) new_lsource_list = new_source_list_14(lsource_list) - new_ord_list.append( (new_lsource_list, lnote_list, new_date, type, + new_ord_list.append( (new_lsource_list, lnote_list, new_date, type, place, famc, temple, status, lprivate)) new_primary_name = convert_name_14(primary_name) - new_alternate_names = [convert_name_14(name) for name + new_alternate_names = [convert_name_14(name) for name in alternate_names] - + new_media_list = new_media_list_14(media_list) new_psource_list = new_source_list_14(psource_list) new_attribute_list = new_attribute_list_14(attribute_list) @@ -1341,7 +1341,7 @@ def gramps_upgrade_14(self): famc, temple, status, lprivate) = ldsord new_date = convert_date_14(date) new_lsource_list = new_source_list_14(lsource_list) - new_seal_list.append( (new_lsource_list, lnote_list, new_date, type, + new_seal_list.append( (new_lsource_list, lnote_list, new_date, type, place, famc, temple, status, lprivate)) new_family = (junk_handle, gramps_id, father_handle, mother_handle, @@ -1370,7 +1370,7 @@ def gramps_upgrade_14(self): (privacy, asource_list, anote_list, date, location) = address new_date = convert_date_14(date) new_asource_list = new_source_list_14(asource_list) - new_address_list.append((privacy, new_asource_list, anote_list, + new_address_list.append((privacy, new_asource_list, anote_list, new_date, location)) new_repository = (junk_handle, gramps_id, the_type, name, note_list, @@ -1413,8 +1413,8 @@ def gramps_upgrade_14(self): new_media_list = new_media_list_14(media_list) new_source_list = new_source_list_14(source_list) new_place = (handle, gramps_id, title, longi, lat, - main_loc, alt_loc, urls, new_media_list, - new_source_list, note_list, change, marker, private) + main_loc, alt_loc, urls, new_media_list, + new_source_list, note_list, change, marker, private) with BSDDBTxn(self.env, self.place_map) as txn: if isinstance(handle, str): @@ -1499,13 +1499,13 @@ def convert_date_14(date): return None def convert_name_14(name): - (privacy, source_list, note_list, date, + (privacy, source_list, note_list, date, first_name, surname, suffix, title, name_type, prefix, patronymic, group_as, sort_as, display_as, call) = name new_date = convert_date_14(date) new_source_list = new_source_list_14(source_list) - return (privacy, new_source_list, note_list, new_date, + return (privacy, new_source_list, note_list, new_date, first_name, surname, suffix, title, name_type, prefix, patronymic, group_as, sort_as, display_as, call) diff --git a/gramps/plugins/database/bsddb_support/write.py b/gramps/plugins/database/bsddb_support/write.py index 3ef6e5819..ccd7b3f2a 100644 --- a/gramps/plugins/database/bsddb_support/write.py +++ b/gramps/plugins/database/bsddb_support/write.py @@ -63,9 +63,9 @@ from gramps.gen.lib.mediaobj import MediaObject from gramps.gen.lib.note import Note from gramps.gen.lib.tag import Tag from gramps.gen.lib.genderstats import GenderStats -from gramps.gen.lib.researcher import Researcher +from gramps.gen.lib.researcher import Researcher -from . import (DbBsddbRead, DbWriteBase, BSDDBTxn, +from . import (DbBsddbRead, DbWriteBase, BSDDBTxn, DbTxn, BsddbBaseCursor, BsddbDowngradeError, DbVersionError, DbEnvironmentError, DbUpgradeRequiredError, find_surname, find_byte_surname, find_surname_name, DbUndoBSDDB as DbUndo) @@ -121,7 +121,7 @@ REF_MAP = "reference_map" REF_PRI = "primary_map" REF_REF = "referenced_map" -DBERRS = (db.DBRunRecoveryError, db.DBAccessError, +DBERRS = (db.DBRunRecoveryError, db.DBAccessError, db.DBPageNotFoundError, db.DBInvalidArgError) # The following two dictionaries provide fast translation @@ -135,7 +135,7 @@ DBERRS = (db.DBRunRecoveryError, db.DBAccessError, # Helper functions # #------------------------------------------------------------------------- - + def find_idmap(key, data): """ return id for association of secondary index. returns a byte string @@ -200,7 +200,7 @@ class DbBsddbAssocCursor(BsddbBaseCursor): BsddbBaseCursor.__init__(self, txn=txn, **kwargs) self.cursor = source.cursor(txn) self.source = source - + #------------------------------------------------------------------------- # # DbBsddb @@ -208,7 +208,7 @@ class DbBsddbAssocCursor(BsddbBaseCursor): #------------------------------------------------------------------------- class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ - Gramps database write access object. + Gramps database write access object. """ # Set up dictionary for callback signal handler @@ -232,20 +232,20 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): # 3. Special signal for change in home person __signals__['home-person-changed'] = None - + # 4. Signal for change in person group name, parameters are __signals__['person-groupname-rebuild'] = (str, str) def __init__(self): """Create a new GrampsDB.""" - + self.txn = None DbBsddbRead.__init__(self) DbWriteBase.__init__(self) #UpdateCallback.__init__(self) self._tables['Person'].update( { - "handle_func": self.get_person_from_handle, + "handle_func": self.get_person_from_handle, "gramps_id_func": self.get_person_from_gramps_id, "class_func": Person, "cursor_func": self.get_person_cursor, @@ -256,7 +256,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): }) self._tables['Family'].update( { - "handle_func": self.get_family_from_handle, + "handle_func": self.get_family_from_handle, "gramps_id_func": self.get_family_from_gramps_id, "class_func": Family, "cursor_func": self.get_family_cursor, @@ -267,7 +267,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): }) self._tables['Source'].update( { - "handle_func": self.get_source_from_handle, + "handle_func": self.get_source_from_handle, "gramps_id_func": self.get_source_from_gramps_id, "class_func": Source, "cursor_func": self.get_source_cursor, @@ -278,7 +278,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): }) self._tables['Citation'].update( { - "handle_func": self.get_citation_from_handle, + "handle_func": self.get_citation_from_handle, "gramps_id_func": self.get_citation_from_gramps_id, "class_func": Citation, "cursor_func": self.get_citation_cursor, @@ -289,7 +289,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): }) self._tables['Event'].update( { - "handle_func": self.get_event_from_handle, + "handle_func": self.get_event_from_handle, "gramps_id_func": self.get_event_from_gramps_id, "class_func": Event, "cursor_func": self.get_event_cursor, @@ -300,7 +300,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): }) self._tables['Media'].update( { - "handle_func": self.get_object_from_handle, + "handle_func": self.get_object_from_handle, "gramps_id_func": self.get_object_from_gramps_id, "class_func": MediaObject, "cursor_func": self.get_media_cursor, @@ -311,7 +311,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): }) self._tables['Place'].update( { - "handle_func": self.get_place_from_handle, + "handle_func": self.get_place_from_handle, "gramps_id_func": self.get_place_from_gramps_id, "class_func": Place, "cursor_func": self.get_place_cursor, @@ -322,7 +322,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): }) self._tables['Repository'].update( { - "handle_func": self.get_repository_from_handle, + "handle_func": self.get_repository_from_handle, "gramps_id_func": self.get_repository_from_gramps_id, "class_func": Repository, "cursor_func": self.get_repository_cursor, @@ -333,7 +333,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): }) self._tables['Note'].update( { - "handle_func": self.get_note_from_handle, + "handle_func": self.get_note_from_handle, "gramps_id_func": self.get_note_from_gramps_id, "class_func": Note, "cursor_func": self.get_note_cursor, @@ -344,7 +344,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): }) self._tables['Tag'].update( { - "handle_func": self.get_tag_from_handle, + "handle_func": self.get_tag_from_handle, "gramps_id_func": None, "class_func": Tag, "cursor_func": self.get_tag_cursor, @@ -401,7 +401,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def __all_handles(self, table): return table.keys(self.txn) - + def __log_error(self): mypath = os.path.join(self.get_save_path(),DBRECOVFN) ofile = open(mypath, "w") @@ -443,7 +443,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Returns a reference to a cursor over the reference map primary map """ - return DbBsddbAssocCursor(self.reference_map_primary_map, + return DbBsddbAssocCursor(self.reference_map_primary_map, self.txn) @catch_db_error @@ -451,7 +451,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Returns a reference to a cursor over the reference map referenced map """ - return DbBsddbAssocCursor(self.reference_map_referenced_map, + return DbBsddbAssocCursor(self.reference_map_referenced_map, self.txn) @catch_db_error @@ -485,7 +485,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): elif (self.metadata) and (not self.readonly): # Start transaction with BSDDBTxn(self.env, self.metadata) as txn: - txn.put(b'default', None) + txn.put(b'default', None) return None def set_mediapath(self, path): @@ -493,7 +493,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): if self.metadata and not self.readonly: # Start transaction with BSDDBTxn(self.env, self.metadata) as txn: - txn.put(b'mediapath', path) + txn.put(b'mediapath', path) def __make_zip_backup(self, dirname): import zipfile @@ -503,7 +503,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): title = self.get_dbname() trans = title.maketrans(reserved_char, replace_char) title = title.translate(trans) - + if not os.access(dirname, os.W_OK): _LOG.warning("Can't write technical DB backup for %s" % title) return @@ -519,7 +519,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): _LOG.warning("If upgrade and loading the Family Tree works, you can " "delete the zip file at %s" % zippath) - + def __check_bdb_version(self, name, force_bsddb_upgrade=False, force_bsddb_downgrade=False): """Older version of Berkeley DB can't read data created by a newer @@ -559,8 +559,8 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): _LOG.warning("Bsddb upgrade requested from %s to %s" % (bsddb_version, str(bdb_version))) self.update_env_version = True - # Make a backup of the database files anyway - self.__make_zip_backup(name) + # Make a backup of the database files anyway + self.__make_zip_backup(name) elif (env_version[0] > bdb_version[0]) or \ (env_version[0] == bdb_version[0] and env_version[1] > bdb_version[1]): @@ -581,8 +581,8 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): _LOG.warning("Bsddb downgrade requested from %s to %s" % (bsddb_version, str(bdb_version))) self.update_env_version = True - # Make a backup of the database files anyway - self.__make_zip_backup(name) + # Make a backup of the database files anyway + self.__make_zip_backup(name) elif env_version == bdb_version: # Bsddb version is OK pass @@ -609,7 +609,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): db_python_version = int(version_file.read().strip()) else: db_python_version = 2 - + if db_python_version == 3 and current_python_version == 2: clear_lock_file(name) raise exceptions.PythonDowngradeError(db_python_version, @@ -626,11 +626,11 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): _LOG.warning("Python upgrade requested from %s to %s" % (db_python_version, current_python_version)) self.update_python_version = True - # Make a backup of the database files anyway + # Make a backup of the database files anyway self.__make_zip_backup(name) elif db_python_version == 2 and current_python_version == 2: pass - + @catch_db_error def version_supported(self): dbversion = self.metadata.get(b'version', default=0) @@ -652,7 +652,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): return True # See if we lack write access to any files in the directory - for base in [FAMILY_TBL, PLACES_TBL, SOURCES_TBL, CITATIONS_TBL, + for base in [FAMILY_TBL, PLACES_TBL, SOURCES_TBL, CITATIONS_TBL, MEDIA_TBL, EVENTS_TBL, PERSON_TBL, REPO_TBL, NOTE_TBL, REF_MAP, META]: path = os.path.join(name, base + DBEXT) @@ -670,7 +670,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): if self.__check_readonly(name): mode = DBMODE_R else: - write_lock_file(name) + write_lock_file(name) if self.db_is_open: self.close() @@ -691,7 +691,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): if not force_python_upgrade: self.__check_bdb_version(name, force_bsddb_upgrade, force_bsddb_downgrade) - + self.__check_python_version(name, force_python_upgrade) # Check for pickle upgrade @@ -704,7 +704,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): _LOG.debug("Make backup in case there is a pickle upgrade") self.__make_zip_backup(name) self.update_pickle_version = True - + # Check for schema upgrade versionpath = os.path.join(self.path, str(SCHVERSFN)) if os.path.isfile(versionpath): @@ -716,7 +716,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): force_schema_upgrade: _LOG.debug("Make backup in case there is a schema upgrade") self.__make_zip_backup(name) - + # Set up database environment self.env = db.DBEnv() self.env.set_cachesize(0, DBCACHE) @@ -724,17 +724,17 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): # These env settings are only needed for Txn environment self.env.set_lk_max_locks(DBLOCKS) self.env.set_lk_max_objects(DBOBJECTS) - + # Set to auto remove stale logs self.set_auto_remove() - # Set not to flush to disk synchronous, this greatly speeds up + # Set not to flush to disk synchronous, this greatly speeds up # database changes, but comes at the cause of loss of durability, so # power loss might cause a need to run db recovery, see BSDDB manual - ## NOTE: due to pre 4.8 bsddb bug it is needed to set this flag before + ## NOTE: due to pre 4.8 bsddb bug it is needed to set this flag before ## open of env, #16492 - http://download.oracle.com/docs/cd/E17076_02/html/installation/changelog_4_8.html self.env.set_flags(db.DB_TXN_WRITE_NOSYNC, 1) - + # The DB_PRIVATE flag must go if we ever move to multi-user setup env_flags = db.DB_CREATE | db.DB_PRIVATE |\ db.DB_INIT_MPOOL |\ @@ -770,7 +770,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): tree_vers = self.metadata.get(b'version', default=0) self.__close_early() raise DbVersionError(tree_vers, _MINVERSION, _DBVERSION) - + gstats = self.metadata.get(b'gender_stats', default=None) # Ensure version info in metadata @@ -786,7 +786,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): # Not new database, but the version is missing. # Use 0, but it is likely to fail anyway. txn.put(b'version', 0) - + self.genderStats = GenderStats(gstats) # Open main tables in gramps database @@ -817,8 +817,8 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): db.DB_HASH, db.DB_DUP) # We have now successfully opened the database, so if the BSDDB version - # has changed, we update the DBSDB version file. - + # has changed, we update the DBSDB version file. + if self.update_env_version: versionpath = os.path.join(name, BDBVERSFN) with open(versionpath, "w") as version_file: @@ -832,7 +832,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): _LOG.debug("Updated python version file to %s" % version) with open(versionpath, "w") as version_file: version_file.write(version) - + # Here we take care of any changes in the tables related to new code. # If secondary indices change, then they should removed # or rebuilt by upgrade as well. In any case, the @@ -846,9 +846,9 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): version = "Yes" version_file.write(version) _LOG.debug("Updated pickle version file to %s" % str(version)) - + self.__load_metadata() - + if self.need_schema_upgrade(): oldschema = self.metadata.get(b'version', default=0) newschema = _DBVERSION @@ -882,7 +882,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): if callback: callback(87) - + self.abort_possible = True return 1 @@ -900,7 +900,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): try: self.undodb.close() except db.DBNoSuchFileError: - pass + pass def get_undodb(self): """ @@ -917,7 +917,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): if len(format) == 3: format = format + (True,) self.name_formats[format_ix] = format - + # database owner try: owner_data = self.metadata.get(b'researcher') @@ -927,11 +927,11 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): self.owner.unserialize(owner_data) except ImportError: #handle problems with pre-alpha 3.0 pass - + # bookmarks def meta(key): return self.metadata.get(key, default=[]) - + self.bookmarks.set(meta(b'bookmarks')) self.family_bookmarks.set(meta(b'family_bookmarks')) self.event_bookmarks.set(meta(b'event_bookmarks')) @@ -967,14 +967,14 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def __connect_secondary(self): """ Connect or creates secondary index tables. - + It assumes that the tables either exist and are in the right format or do not exist (in which case they get created). It is the responsibility of upgrade code to either create or remove invalid secondary index tables. """ - + # index tables used just for speeding up searches self.surnames = self.__open_db(self.full_name, SURNAMES, db.DB_BTREE, db.DB_DUP | db.DB_DUPSORT) @@ -992,7 +992,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): ("tag_trans", TAGTRANS, db.DB_HASH, 0), ("parents", PPARENT, db.DB_HASH, 0), ("reference_map_primary_map", REF_PRI, db.DB_BTREE, 0), - ("reference_map_referenced_map", REF_REF, db.DB_BTREE, db.DB_DUPSORT), + ("reference_map_referenced_map", REF_REF, db.DB_BTREE, db.DB_DUPSORT), ] for (dbmap, dbname, dbtype, dbflags) in db_maps: @@ -1099,7 +1099,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): while (ret is not None): (key, data) = ret - + ### FIXME: this is a dirty hack that works without no ### sensible explanation. For some reason, for a readonly ### database, secondary index returns a primary table key @@ -1118,7 +1118,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def find_backlink_handles(self, handle, include_classes=None): """ Find all objects that hold a reference to the object handle. - + Returns an interator over a list of (class_name, handle) tuples. :param handle: handle of the object to search for. @@ -1145,7 +1145,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): while (ret is not None): (key, data) = ret - + # data values are of the form: # ((primary_object_class_name, primary_object_handle), # (referenced_object_class_name, referenced_object_handle)) @@ -1163,11 +1163,11 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): key, handle = data[0][:2] name = KEY_TO_CLASS_MAP[key] assert name == KEY_TO_CLASS_MAP[data[0][0]] - assert handle == data[0][1] + assert handle == data[0][1] if (include_classes is None or name in include_classes): yield (name, handle) - + ret = referenced_cur.next_dup() referenced_cur.close() @@ -1183,19 +1183,19 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): ret = primary_cur.set(handle) except: ret = None - + remove_list = set() while (ret is not None): (key, data) = ret - + # data values are of the form: # ((primary_object_class_name, primary_object_handle), # (referenced_object_class_name, referenced_object_handle)) - + # so we need the second tuple give us a reference that we can # combine with the primary_handle to get the main key. main_key = (handle.decode('utf-8'), pickle.loads(data)[1][1]) - + # The trick is not to remove while inside the cursor, # but collect them all and remove after the cursor is closed remove_list.add(main_key) @@ -1207,12 +1207,12 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): # Now that the cursor is closed, we can remove things for main_key in remove_list: self.__remove_reference(main_key, transaction, txn) - + def update_reference_map(self, obj, transaction, txn=None): """ If txn is given, then changes are written right away using txn. """ - + # Add references to the reference_map for all primary object referenced # from the primary object 'obj' or any of its secondary objects. handle = obj.handle @@ -1251,7 +1251,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): no_longer_required_references = existing_references.difference( current_references) new_references = current_references.difference(existing_references) - + # handle addition of new references for (ref_class_name, ref_handle) in new_references: data = ((CLASS_TO_KEY_MAP[obj.__class__.__name__], handle), @@ -1268,7 +1268,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def __remove_reference(self, key, transaction, txn): """ - Remove the reference specified by the key, preserving the change in + Remove the reference specified by the key, preserving the change in the passed transaction. """ if isinstance(key, tuple): @@ -1290,7 +1290,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def __add_reference(self, key, data, transaction, txn): """ - Add the reference specified by the key and the data, preserving the + Add the reference specified by the key and the data, preserving the change in the passed transaction. """ if isinstance(key, tuple): @@ -1300,7 +1300,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): key = key.encode('utf-8') if self.readonly or not key: return - + self.reference_map.put(key, data, txn=txn) if not transaction.batch: transaction.add(REFERENCE_KEY, TXNADD, key, None, data) @@ -1310,7 +1310,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def reindex_reference_map(self, callback): """ Reindex all primary records in the database. - + This will be a slow process for large databases. """ @@ -1332,9 +1332,9 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): callback(index+1) # Open reference_map and primary map - self.reference_map = self.__open_shelf(self.full_name, REF_MAP, + self.reference_map = self.__open_shelf(self.full_name, REF_MAP, dbtype=db.DB_BTREE) - + self.reference_map_primary_map = self.__open_db(self.full_name, REF_PRI, db.DB_BTREE, db.DB_DUP) @@ -1360,10 +1360,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): (self.get_note_cursor, Note), (self.get_tag_cursor, Tag), ) - + # Now we use the functions and classes defined above # to loop through each of the primary object tables. - + for cursor_func, class_func in primary_table: logging.info("Rebuilding %s reference map" % class_func.__name__) @@ -1391,7 +1391,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): # name display formats txn.put(b'name_formats', self.name_formats) - + # database owner owner_data = self.owner.serialize() txn.put(b'researcher', owner_data) @@ -1433,7 +1433,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): txn.put(b'surname_list', self.surname_list) self.metadata.close() - + def __close_early(self): """ Bail out if the incompatible version is discovered: @@ -1445,7 +1445,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): self.metadata = None self.env = None self.db_is_open = False - + @catch_db_error def close(self): if not self.db_is_open: @@ -1503,9 +1503,9 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): self.metadata = None self.db_is_open = False self.surname_list = None - + DbBsddbRead.close(self) - + self.person_map = None self.family_map = None self.repository_map = None @@ -1541,11 +1541,11 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Add a Person to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ - handle = self.__add_object(person, transaction, - self.find_next_person_gramps_id if set_gid else None, + handle = self.__add_object(person, transaction, + self.find_next_person_gramps_id if set_gid else None, self.commit_person) return handle @@ -1553,45 +1553,45 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Add a Family to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ - return self.__add_object(family, transaction, - self.find_next_family_gramps_id if set_gid else None, + return self.__add_object(family, transaction, + self.find_next_family_gramps_id if set_gid else None, self.commit_family) def add_source(self, source, transaction, set_gid=True): """ Add a Source to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ - return self.__add_object(source, transaction, - self.find_next_source_gramps_id if set_gid else None, + return self.__add_object(source, transaction, + self.find_next_source_gramps_id if set_gid else None, self.commit_source) def add_citation(self, citation, transaction, set_gid=True): """ Add a Citation to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ - return self.__add_object(citation, transaction, - self.find_next_citation_gramps_id if set_gid else None, + return self.__add_object(citation, transaction, + self.find_next_citation_gramps_id if set_gid else None, self.commit_citation) def add_event(self, event, transaction, set_gid=True): """ Add an Event to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ if event.type.is_custom(): self.event_names.add(str(event.type)) - return self.__add_object(event, transaction, + return self.__add_object(event, transaction, self.find_next_event_gramps_id if set_gid else None, self.commit_event) @@ -1611,10 +1611,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Add a Place to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ - return self.__add_object(place, transaction, + return self.__add_object(place, transaction, self.find_next_place_gramps_id if set_gid else None, self.commit_place) @@ -1622,10 +1622,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Add a MediaObject to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ - return self.__add_object(obj, transaction, + return self.__add_object(obj, transaction, self.find_next_object_gramps_id if set_gid else None, self.commit_media_object) @@ -1633,10 +1633,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Add a Repository to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ - return self.__add_object(obj, transaction, + return self.__add_object(obj, transaction, self.find_next_repository_gramps_id if set_gid else None, self.commit_repository) @@ -1644,10 +1644,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Add a Note to the database, assigning internal IDs if they have not already been defined. - + If not set_gid, then gramps_id is not set. """ - return self.__add_object(obj, transaction, + return self.__add_object(obj, transaction, self.find_next_note_gramps_id if set_gid else None, self.commit_note) @@ -1678,8 +1678,8 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def remove_person(self, handle, transaction): """ - Remove the Person specified by the database handle from the database, - preserving the change in the passed transaction. + Remove the Person specified by the database handle from the database, + preserving the change in the passed transaction. """ if self.readonly or not handle: @@ -1690,7 +1690,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): if isinstance(handle, str): handle = handle.encode('utf-8') if transaction.batch: - with BSDDBTxn(self.env, self.person_map) as txn: + with BSDDBTxn(self.env, self.person_map) as txn: self.delete_primary_from_reference_map(handle, transaction, txn=txn.txn) txn.delete(handle) @@ -1703,73 +1703,73 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def remove_source(self, handle, transaction): """ Remove the Source specified by the database handle from the - database, preserving the change in the passed transaction. + database, preserving the change in the passed transaction. """ - self.__do_remove(handle, transaction, self.source_map, + self.__do_remove(handle, transaction, self.source_map, SOURCE_KEY) def remove_citation(self, handle, transaction): """ Remove the Citation specified by the database handle from the - database, preserving the change in the passed transaction. + database, preserving the change in the passed transaction. """ - self.__do_remove(handle, transaction, self.citation_map, + self.__do_remove(handle, transaction, self.citation_map, CITATION_KEY) def remove_event(self, handle, transaction): """ Remove the Event specified by the database handle from the - database, preserving the change in the passed transaction. + database, preserving the change in the passed transaction. """ - self.__do_remove(handle, transaction, self.event_map, + self.__do_remove(handle, transaction, self.event_map, EVENT_KEY) def remove_object(self, handle, transaction): """ Remove the MediaObjectPerson specified by the database handle from the - database, preserving the change in the passed transaction. + database, preserving the change in the passed transaction. """ - self.__do_remove(handle, transaction, self.media_map, + self.__do_remove(handle, transaction, self.media_map, MEDIA_KEY) def remove_place(self, handle, transaction): """ Remove the Place specified by the database handle from the - database, preserving the change in the passed transaction. + database, preserving the change in the passed transaction. """ - self.__do_remove(handle, transaction, self.place_map, + self.__do_remove(handle, transaction, self.place_map, PLACE_KEY) def remove_family(self, handle, transaction): """ Remove the Family specified by the database handle from the - database, preserving the change in the passed transaction. + database, preserving the change in the passed transaction. """ - self.__do_remove(handle, transaction, self.family_map, + self.__do_remove(handle, transaction, self.family_map, FAMILY_KEY) def remove_repository(self, handle, transaction): """ Remove the Repository specified by the database handle from the - database, preserving the change in the passed transaction. + database, preserving the change in the passed transaction. """ - self.__do_remove(handle, transaction, self.repository_map, + self.__do_remove(handle, transaction, self.repository_map, REPOSITORY_KEY) def remove_note(self, handle, transaction): """ Remove the Note specified by the database handle from the - database, preserving the change in the passed transaction. + database, preserving the change in the passed transaction. """ - self.__do_remove(handle, transaction, self.note_map, + self.__do_remove(handle, transaction, self.note_map, NOTE_KEY) def remove_tag(self, handle, transaction): """ Remove the Tag specified by the database handle from the - database, preserving the change in the passed transaction. + database, preserving the change in the passed transaction. """ - self.__do_remove(handle, transaction, self.tag_map, + self.__do_remove(handle, transaction, self.tag_map, TAG_KEY) @catch_db_error @@ -1796,12 +1796,12 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def build_surname_list(self): """ Build surname list for use in autocompletion - This is a list of unicode objects, which are decoded from the utf-8 in + This is a list of unicode objects, which are decoded from the utf-8 in bsddb """ #TODO GTK3: Why double conversion? Convert to a list of str objects! self.surname_list = sorted( - map(conv_dbstr_to_unicode, set(self.surnames.keys())), + map(conv_dbstr_to_unicode, set(self.surnames.keys())), key=glocale.sort_key) def add_to_surname_list(self, person, batch_transaction): @@ -1810,7 +1810,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ if batch_transaction: return - name = conv_to_unicode(find_surname_name(person.handle, + name = conv_to_unicode(find_surname_name(person.handle, person.get_primary_name().serialize()), 'utf-8') i = bisect.bisect(self.surname_list, name) if 0 < i <= len(self.surname_list): @@ -1823,12 +1823,12 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def remove_from_surname_list(self, person): """ Check whether there are persons with the same surname left in - the database. - + the database. + If not then we need to remove the name from the list. The function must be overridden in the derived class. """ - name = find_surname_name(person.handle, + name = find_surname_name(person.handle, person.get_primary_name().serialize()) if isinstance(name, str): uname = name @@ -1851,14 +1851,14 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): finally: if 'cursor' in locals(): cursor.close() - + def commit_base(self, obj, data_map, key, transaction, change_time): """ - Commit the specified object to the database, storing the changes as + Commit the specified object to the database, storing the changes as part of the transaction. """ if self.readonly or not obj or not obj.handle: - return + return obj.change = int(change_time or time.time()) handle = obj.handle @@ -1875,10 +1875,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): transaction.add(key, op, handle, old_data, new_data) data_map.put(handle, new_data, txn=self.txn) return old_data - + def commit_person(self, person, transaction, change_time=None): """ - Commit the specified Person to the database, storing the changes as + Commit the specified Person to the database, storing the changes as part of the transaction. """ old_data = self.commit_base( @@ -1896,8 +1896,8 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): self.genderStats.count_person(person) # Update surname list if necessary - if (find_surname_name(old_person.handle, - old_person.primary_name.serialize()) != + if (find_surname_name(old_person.handle, + old_person.primary_name.serialize()) != find_surname_name(person.handle, person.primary_name.serialize())): self.remove_from_surname_list(old_person) @@ -1919,7 +1919,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): + person.alternate_names) if name.type.is_custom()]) all_surn = [] # new list we will use for storage - all_surn += person.primary_name.get_surname_list() + all_surn += person.primary_name.get_surname_list() for asurname in person.alternate_names: all_surn += asurname.get_surname_list() self.origin_types.update([str(surn.origintype) for surn in all_surn @@ -1946,18 +1946,18 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): self.media_attributes.update( [str(attr.type) for attr in obj.attribute_list if attr.type.is_custom() and str(attr.type)]) - + def commit_source(self, source, transaction, change_time=None): """ - Commit the specified Source to the database, storing the changes as + Commit the specified Source to the database, storing the changes as part of the transaction. """ - self.commit_base(source, self.source_map, SOURCE_KEY, + self.commit_base(source, self.source_map, SOURCE_KEY, transaction, change_time) self.source_media_types.update( [str(ref.media_type) for ref in source.reporef_list - if ref.media_type.is_custom()]) + if ref.media_type.is_custom()]) attr_list = [] for mref in source.media_list: @@ -1971,10 +1971,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def commit_citation(self, citation, transaction, change_time=None): """ - Commit the specified Citation to the database, storing the changes as + Commit the specified Citation to the database, storing the changes as part of the transaction. """ - self.commit_base(citation, self.citation_map, CITATION_KEY, + self.commit_base(citation, self.citation_map, CITATION_KEY, transaction, change_time) attr_list = [] @@ -1989,10 +1989,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def commit_place(self, place, transaction, change_time=None): """ - Commit the specified Place to the database, storing the changes as + Commit the specified Place to the database, storing the changes as part of the transaction. """ - self.commit_base(place, self.place_map, PLACE_KEY, + self.commit_base(place, self.place_map, PLACE_KEY, transaction, change_time) if place.get_type().is_custom(): @@ -2021,10 +2021,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def commit_event(self, event, transaction, change_time=None): """ - Commit the specified Event to the database, storing the changes as + Commit the specified Event to the database, storing the changes as part of the transaction. """ - self.commit_base(event, self.event_map, EVENT_KEY, + self.commit_base(event, self.event_map, EVENT_KEY, transaction, change_time) self.event_attributes.update( @@ -2042,10 +2042,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def commit_family(self, family, transaction, change_time=None): """ - Commit the specified Family to the database, storing the changes as + Commit the specified Family to the database, storing the changes as part of the transaction. """ - self.commit_base(family, self.family_map, FAMILY_KEY, + self.commit_base(family, self.family_map, FAMILY_KEY, transaction, change_time) self.family_attributes.update( @@ -2078,7 +2078,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): Commit the specified Repository to the database, storing the changes as part of the transaction. """ - self.commit_base(repository, self.repository_map, REPOSITORY_KEY, + self.commit_base(repository, self.repository_map, REPOSITORY_KEY, transaction, change_time) if repository.type.is_custom(): @@ -2089,21 +2089,21 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def commit_note(self, note, transaction, change_time=None): """ - Commit the specified Note to the database, storing the changes as part + Commit the specified Note to the database, storing the changes as part of the transaction. """ - self.commit_base(note, self.note_map, NOTE_KEY, + self.commit_base(note, self.note_map, NOTE_KEY, transaction, change_time) if note.type.is_custom(): - self.note_types.add(str(note.type)) + self.note_types.add(str(note.type)) def commit_tag(self, tag, transaction, change_time=None): """ - Commit the specified Tag to the database, storing the changes as part + Commit the specified Tag to the database, storing the changes as part of the transaction. """ - self.commit_base(tag, self.tag_map, TAG_KEY, + self.commit_base(tag, self.tag_map, TAG_KEY, transaction, change_time) def get_from_handle(self, handle, class_type, data_map): @@ -2228,7 +2228,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): Revert the changes made to the database so far during the transaction. """ if self._LOG_ALL: - _LOG.debug("%s: Transaction abort '%s'\n" % + _LOG.debug("%s: Transaction abort '%s'\n" % (self.__class__.__name__, transaction.get_description())) if self.readonly: @@ -2288,7 +2288,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): if self.redo_callback: self.redo_callback(None) if self.undo_history_callback: - self.undo_history_callback() + self.undo_history_callback() def undo(self, update_history=True): return self.undodb.undo(update_history) @@ -2298,11 +2298,11 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): def gramps_upgrade(self, callback=None): UpdateCallback.__init__(self, callback) - + version = self.metadata.get(b'version', default=_MINVERSION) t = time.time() - + from . import upgrade if version < 14: @@ -2315,7 +2315,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): upgrade.gramps_upgrade_17(self) if version < 18: upgrade.gramps_upgrade_18(self) - + self.reset() self.set_total(6) self.__connect_secondary() @@ -2380,11 +2380,11 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): self.env.txn_checkpoint() self.metadata = self.__open_shelf(full_name, META) - + _LOG.debug("Write schema version %s" % _DBVERSION) with BSDDBTxn(self.env, self.metadata) as txn: txn.put(b'version', _DBVERSION) - + versionpath = os.path.join(name, BDBVERSFN) version = str(db.version()) _LOG.debug("Write bsddb version %s" % version) @@ -2416,7 +2416,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): self.metadata.close() self.env.close() - + def get_dbid(self): """ In BSDDB, we use the file directory name as the unique ID for @@ -2434,10 +2434,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Exports the database to a set of backup files. These files consist of the pickled database tables, one file for each table. - + The heavy lifting is done by the private :py:func:`__do__export` function. The purpose of this function is to catch any exceptions that occur. - + :param database: database instance to backup :type database: DbDir """ @@ -2450,10 +2450,10 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback): """ Restores the database to a set of backup files. These files consist of the pickled database tables, one file for each table. - + The heavy lifting is done by the private :py:func:`__do__restore` function. The purpose of this function is to catch any exceptions that occur. - + :param database: database instance to restore :type database: DbDir """ @@ -2497,7 +2497,7 @@ def mk_backup_name(database, base): """ Return the backup name of the database table - :param database: database instance + :param database: database instance :type database: DbDir :param base: base name of the table :type base: str @@ -2508,7 +2508,7 @@ def mk_tmp_name(database, base): """ Return the temporary backup name of the database table - :param database: database instance + :param database: database instance :type database: DbDir :param base: base name of the table :type base: str @@ -2527,7 +2527,7 @@ def do_export(database): for (base, tbl) in build_tbl_map(database): backup_name = mk_tmp_name(database, base) backup_table = open(backup_name, 'wb') - + cursor = tbl.cursor() data = cursor.first() while data: @@ -2564,7 +2564,7 @@ def load_tbl_txn(database, backup_table, tbl): """ Return the temporary backup name of the database table - :param database: database instance + :param database: database instance :type database: DbDir :param backup_table: file containing the backup data :type backup_table: file @@ -2631,7 +2631,7 @@ def write_lock_file(name): if host: text = "%s@%s" % (user, host) else: - text = user + text = user # Save only the username and host, so the massage can be # printed with correct locale in DbManager.py when a lock is found f.write(text) @@ -2648,7 +2648,7 @@ def upgrade_researcher(owner_data): if __name__ == "__main__": import os, sys, pdb - + d = DbBsddb() if len(sys.argv) > 1: db_name = sys.argv[1] diff --git a/gramps/plugins/database/dictionarydb.py b/gramps/plugins/database/dictionarydb.py index e100bbc82..c98b36491 100644 --- a/gramps/plugins/database/dictionarydb.py +++ b/gramps/plugins/database/dictionarydb.py @@ -215,7 +215,7 @@ class DictionaryDb(DbGeneric): self.genderStats.uncount_person(old_person) self.genderStats.count_person(person) # Update surname list if necessary - if (self._order_by_person_key(person) != + if (self._order_by_person_key(person) != self._order_by_person_key(old_person)): self.remove_from_surname_list(old_person) self.add_to_surname_list(person, trans.batch) @@ -234,12 +234,12 @@ class DictionaryDb(DbGeneric): if not trans.batch: self.update_backlinks(person) if old_person: - trans.add(PERSON_KEY, TXNUPD, person.handle, - old_person.serialize(), + trans.add(PERSON_KEY, TXNUPD, person.handle, + old_person.serialize(), person.serialize()) else: - trans.add(PERSON_KEY, TXNADD, person.handle, - None, + trans.add(PERSON_KEY, TXNADD, person.handle, + None, person.serialize()) # Other misc update tasks: self.individual_attributes.update( @@ -255,7 +255,7 @@ class DictionaryDb(DbGeneric): + person.alternate_names) if name.type.is_custom()]) all_surn = [] # new list we will use for storage - all_surn += person.primary_name.get_surname_list() + all_surn += person.primary_name.get_surname_list() for asurname in person.alternate_names: all_surn += asurname.get_surname_list() self.origin_types.update([str(surn.origintype) for surn in all_surn @@ -288,8 +288,8 @@ class DictionaryDb(DbGeneric): if not trans.batch: self.update_backlinks(family) op = TXNUPD if old_family else TXNADD - trans.add(FAMILY_KEY, op, family.handle, - old_family, + trans.add(FAMILY_KEY, op, family.handle, + old_family, family.serialize()) # Misc updates: @@ -337,8 +337,8 @@ class DictionaryDb(DbGeneric): if not trans.batch: self.update_backlinks(citation) op = TXNUPD if old_citation else TXNADD - trans.add(CITATION_KEY, op, citation.handle, - old_citation, + trans.add(CITATION_KEY, op, citation.handle, + old_citation, citation.serialize()) # Misc updates: attr_list = [] @@ -371,13 +371,13 @@ class DictionaryDb(DbGeneric): if not trans.batch: self.update_backlinks(source) op = TXNUPD if old_source else TXNADD - trans.add(SOURCE_KEY, op, source.handle, - old_source, + trans.add(SOURCE_KEY, op, source.handle, + old_source, source.serialize()) # Misc updates: self.source_media_types.update( [str(ref.media_type) for ref in source.reporef_list - if ref.media_type.is_custom()]) + if ref.media_type.is_custom()]) attr_list = [] for mref in source.media_list: @@ -407,8 +407,8 @@ class DictionaryDb(DbGeneric): if not trans.batch: self.update_backlinks(repository) op = TXNUPD if old_repository else TXNADD - trans.add(REPOSITORY_KEY, op, repository.handle, - old_repository, + trans.add(REPOSITORY_KEY, op, repository.handle, + old_repository, repository.serialize()) # Misc updates: if repository.type.is_custom(): @@ -436,12 +436,12 @@ class DictionaryDb(DbGeneric): if not trans.batch: self.update_backlinks(note) op = TXNUPD if old_note else TXNADD - trans.add(NOTE_KEY, op, note.handle, - old_note, + trans.add(NOTE_KEY, op, note.handle, + old_note, note.serialize()) # Misc updates: if note.type.is_custom(): - self.note_types.add(str(note.type)) + self.note_types.add(str(note.type)) # Emit after added: if emit: self.emit(emit, ([note.handle],)) @@ -462,8 +462,8 @@ class DictionaryDb(DbGeneric): if not trans.batch: self.update_backlinks(place) op = TXNUPD if old_place else TXNADD - trans.add(PLACE_KEY, op, place.handle, - old_place, + trans.add(PLACE_KEY, op, place.handle, + old_place, place.serialize()) # Misc updates: if place.get_type().is_custom(): @@ -497,8 +497,8 @@ class DictionaryDb(DbGeneric): if not trans.batch: self.update_backlinks(event) op = TXNUPD if old_event else TXNADD - trans.add(EVENT_KEY, op, event.handle, - old_event, + trans.add(EVENT_KEY, op, event.handle, + old_event, event.serialize()) # Misc updates: self.event_attributes.update( @@ -547,8 +547,8 @@ class DictionaryDb(DbGeneric): if not trans.batch: self.update_backlinks(media) op = TXNUPD if old_media else TXNADD - trans.add(MEDIA_KEY, op, media.handle, - old_media, + trans.add(MEDIA_KEY, op, media.handle, + old_media, media.serialize()) # Misc updates: self.media_attributes.update( @@ -560,9 +560,9 @@ class DictionaryDb(DbGeneric): def update_backlinks(self, obj): # First, delete the current references: - # self._reference_list = [[obj.handle, + # self._reference_list = [[obj.handle, # obj.__class__.__name__, - # ref_handle, + # ref_handle, # ref_class_name], ...] for item in list(self._reference_list): if item[0] == obj.handle: @@ -570,16 +570,16 @@ class DictionaryDb(DbGeneric): # Now, add the current ones: references = set(obj.get_referenced_handles_recursively()) for (ref_class_name, ref_handle) in references: - self._reference_list.append([obj.handle, + self._reference_list.append([obj.handle, obj.__class__.__name__, - ref_handle, + ref_handle, ref_class_name]) # This function is followed by a commit. def remove_person(self, handle, transaction): """ - Remove the Person specified by the database handle from the database, - preserving the change in the passed transaction. + Remove the Person specified by the database handle from the database, + preserving the change in the passed transaction. """ if self.readonly or not handle: @@ -590,20 +590,20 @@ class DictionaryDb(DbGeneric): del self._person_id_dict[person.gramps_id] self.emit("person-delete", ([handle],)) if not transaction.batch: - transaction.add(PERSON_KEY, TXNDEL, person.handle, + transaction.add(PERSON_KEY, TXNDEL, person.handle, person.serialize(), None) def _do_remove(self, handle, transaction, data_map, data_id_map, key): key2table = { - PERSON_KEY: "person", - FAMILY_KEY: "family", - SOURCE_KEY: "source", - CITATION_KEY: "citation", - EVENT_KEY: "event", - MEDIA_KEY: "media", - PLACE_KEY: "place", - REPOSITORY_KEY: "repository", - NOTE_KEY: "note", + PERSON_KEY: "person", + FAMILY_KEY: "family", + SOURCE_KEY: "source", + CITATION_KEY: "citation", + EVENT_KEY: "event", + MEDIA_KEY: "media", + PLACE_KEY: "place", + REPOSITORY_KEY: "repository", + NOTE_KEY: "note", TAG_KEY: "tag", } if self.readonly or not handle: @@ -622,7 +622,7 @@ class DictionaryDb(DbGeneric): def find_backlink_handles(self, handle, include_classes=None): """ Find all objects that hold a reference to the object handle. - + Returns an interator over a list of (class_name, handle) tuples. :param handle: handle of the object to search for. @@ -636,9 +636,9 @@ class DictionaryDb(DbGeneric): result_list = list(find_backlink_handles(handle)) """ - #self._reference_list = [[obj.handle, + #self._reference_list = [[obj.handle, # obj.__class__.__name__, - # ref_handle, + # ref_handle, # ref_class_name], ...] rows = (x for x in self._reference_list if x[2] == handle) for row in rows: @@ -711,15 +711,15 @@ class DictionaryDb(DbGeneric): references = set(obj.get_referenced_handles_recursively()) # handle addition of new references for (ref_class_name, ref_handle) in references: - self._reference_list.append([obj.handle, + self._reference_list.append([obj.handle, obj.__class__.__name__, - ref_handle, + ref_handle, ref_class_name]) callback(5) def rebuild_secondary(self, update): gstats = self.get_gender_stats() - self.genderStats = GenderStats(gstats) + self.genderStats = GenderStats(gstats) self.surname_list = self.build_surname_list() def has_handle_for_person(self, key): @@ -884,18 +884,18 @@ class DictionaryDb(DbGeneric): def rebuild_gender_stats(self): """ - Builds and returns a dictionary of - {given_name: (male_count, female_count, unknown_count)} + Builds and returns a dictionary of + {given_name: (male_count, female_count, unknown_count)} Called locally: this is a database-efficient version """ - # In dictionarydb, there is no separate persistent storage of + # In dictionarydb, there is no separate persistent storage of # gender stats, so we just get from the source: return self.get_gender_stats() def get_gender_stats(self): """ - Returns a dictionary of - {given_name: (male_count, female_count, unknown_count)} + Returns a dictionary of + {given_name: (male_count, female_count, unknown_count)} UNKNOWN = 2 MALE = 1 FEMALE = 0 @@ -907,15 +907,15 @@ class DictionaryDb(DbGeneric): if first_name not in gstats: gstats[first_name] = (0, 0, 0) if person.gender == Person.MALE: - gstats[first_name] = (gstats[first_name][0] + 1, + gstats[first_name] = (gstats[first_name][0] + 1, gstats[first_name][1], gstats[first_name][2]) elif person.gender == Person.FEMALE: - gstats[first_name] = (gstats[first_name][0], + gstats[first_name] = (gstats[first_name][0], gstats[first_name][1] + 1, gstats[first_name][2]) else: - gstats[first_name] = (gstats[first_name][0], + gstats[first_name] = (gstats[first_name][0], gstats[first_name][1], gstats[first_name][2] + 1) return gstats @@ -976,21 +976,21 @@ class DictionaryDb(DbGeneric): self._metadata_dict = {} self._gender_stats_dict = {} - def load(self, directory, callback=None, mode=None, - force_schema_upgrade=False, - force_bsddb_upgrade=False, - force_bsddb_downgrade=False, + def load(self, directory, callback=None, mode=None, + force_schema_upgrade=False, + force_bsddb_upgrade=False, + force_bsddb_downgrade=False, force_python_upgrade=False): - super().load(directory, - callback, - mode, - force_schema_upgrade, - force_bsddb_upgrade, - force_bsddb_downgrade, + super().load(directory, + callback, + mode, + force_schema_upgrade, + force_bsddb_upgrade, + force_bsddb_downgrade, force_python_upgrade) # Dictionary-specific load: from gramps.plugins.importer.importxml import importData - from gramps.cli.user import User + from gramps.cli.user import User if self._directory: filename = os.path.join(self._directory, "data.gramps") if os.path.isfile(filename): diff --git a/gramps/plugins/docgen/asciidoc.py b/gramps/plugins/docgen/asciidoc.py index f4fb48108..a91105c29 100644 --- a/gramps/plugins/docgen/asciidoc.py +++ b/gramps/plugins/docgen/asciidoc.py @@ -65,7 +65,7 @@ LEFT, RIGHT, CENTER = 'LEFT', 'RIGHT', 'CENTER' def reformat_para(para='', left=0, right=72, just=LEFT, right_pad=0, first=0): if not para.strip(): return "\n" - + lines = [] real_left = left+first alllines = para.split('\n') @@ -115,7 +115,7 @@ def reformat_para(para='', left=0, right=72, just=LEFT, right_pad=0, first=0): return '\n'.join([line.rjust(right) for line in lines]) else: return '\n'.join([line.rjust(right).rstrip() for line in lines]) - else: # left justify + else: # left justify if right_pad: return '\n'.join( [' '*(left+first) + line.ljust(right-left-first) @@ -167,7 +167,7 @@ class AsciiDoc(BaseDoc, TextDoc): #-------------------------------------------------------------------- # - # Close the file. Call the app if required. + # Close the file. Call the app if required. # #-------------------------------------------------------------------- def close(self): @@ -198,7 +198,7 @@ class AsciiDoc(BaseDoc, TextDoc): #-------------------------------------------------------------------- # - # Starts a paragraph. + # Starts a paragraph. # #-------------------------------------------------------------------- def start_paragraph(self, style_name, leader=None): @@ -208,7 +208,7 @@ class AsciiDoc(BaseDoc, TextDoc): #-------------------------------------------------------------------- # - # End a paragraph. First format it to the desired widths. + # End a paragraph. First format it to the desired widths. # If not in table cell, write it immediately. If in the cell, # add it to the list for this cell after formatting. # @@ -274,18 +274,18 @@ class AsciiDoc(BaseDoc, TextDoc): # don't add LF if there is this_text is a LF this_text += the_pad + '\n' else: - this_text += '\n' + the_pad + '\n' - + this_text += '\n' + the_pad + '\n' + if self.in_cell: self.cellpars[self.cellnum] += this_text else: self.f.write(this_text) - + self.text = "" #-------------------------------------------------------------------- # - # Start a table. Grab the table style, and store it. + # Start a table. Grab the table style, and store it. # #-------------------------------------------------------------------- def start_table(self, name, style_name): @@ -358,7 +358,7 @@ class AsciiDoc(BaseDoc, TextDoc): ) self.cell_widths[self.cellnum-span] = 0 span -= 1 - + #-------------------------------------------------------------------- # @@ -383,12 +383,12 @@ class AsciiDoc(BaseDoc, TextDoc): def write_styled_note(self, styledtext, format, style_name, contains_html=False, links=False): """ - Convenience function to write a styledtext to the ASCII doc. + Convenience function to write a styledtext to the ASCII doc. styledtext : assumed a StyledText object to write format : = 0 : Flowed, = 1 : Preformatted style_name : name of the style to use for default presentation - contains_html: bool, the backend should not check if html is present. - If contains_html=True, then the textdoc is free to handle that in + contains_html: bool, the backend should not check if html is present. + If contains_html=True, then the textdoc is free to handle that in some way. Eg, a textdoc could remove all tags, or could make sure a link is clickable. AsciiDoc prints the html without handling it links: bool, make the URL in the text clickable (if supported) @@ -417,7 +417,7 @@ class AsciiDoc(BaseDoc, TextDoc): #-------------------------------------------------------------------- # - # Writes text. + # Writes text. #-------------------------------------------------------------------- def write_text(self, text, mark=None, links=False): self.text = self.text + text @@ -434,7 +434,7 @@ class AsciiDocOptions(DocOptions): def __init__(self, name, dbase): DocOptions.__init__(self, name) - + def add_menu_options(self, menu): """ Add options to the document menu for the AsciiDoc docgen. diff --git a/gramps/plugins/docgen/cairodoc.py b/gramps/plugins/docgen/cairodoc.py index a02ac9fa1..0df744852 100644 --- a/gramps/plugins/docgen/cairodoc.py +++ b/gramps/plugins/docgen/cairodoc.py @@ -75,7 +75,7 @@ class CairoDocgen(libcairodoc.CairoDoc): """Render the document into a file using a Cairo surface. """ def create_cairo_surface(self, fobj, width_in_points, height_in_points): - # See + # See # http://cairographics.org/documentation/pycairo/3/reference/surfaces.html#class-pssurface-surface # for the arg semantics. raise "Missing surface factory override!!!" @@ -146,7 +146,7 @@ class CairoDocgen(libcairodoc.CairoDoc): rebuild_required = True else: toc_pages = [] - + # paginate the index if index_page is not None: index_pages = self.__generate_index(layout, page_width, @@ -157,7 +157,7 @@ class CairoDocgen(libcairodoc.CairoDoc): rebuild_required = True else: index_pages = [] - + # rebuild the table of contents and index if required if rebuild_required: if toc_page is not None: @@ -193,7 +193,7 @@ class CairoDocgen(libcairodoc.CairoDoc): except Exception as err: errmsg = "%s\n%s" % (_("Could not create %s") % filename, err) raise ReportError(errmsg) - + def __increment_pages(self, toc, index, start_page, offset): """ Increment the page numbers in the table of contents and index. @@ -226,7 +226,7 @@ class CairoDocgen(libcairodoc.CairoDoc): write_index(index, self) self.paginate_document(layout, page_width, page_height, DPI, DPI) return self._pages - + def write_toc(toc, doc): """ Write the table of contents. @@ -237,7 +237,7 @@ def write_toc(toc, doc): doc.start_paragraph('TOC-Title') doc.write_text(doc.toc_title) doc.end_paragraph() - + doc.start_table('toc', 'TOC-Table') for mark, page_nr in toc: doc.start_row() @@ -259,7 +259,7 @@ def write_toc(toc, doc): doc.end_cell() doc.end_row() doc.end_table() - + def write_index(index, doc): """ Write the alphabetical index. @@ -270,7 +270,7 @@ def write_index(index, doc): doc.start_paragraph('IDX-Title') doc.write_text(doc.index_title) doc.end_paragraph() - + doc.start_table('index', 'IDX-Table') for key in sorted(index.keys()): doc.start_row() diff --git a/gramps/plugins/docgen/docgen.gpr.py b/gramps/plugins/docgen/docgen.gpr.py index b9f492511..272cab506 100644 --- a/gramps/plugins/docgen/docgen.gpr.py +++ b/gramps/plugins/docgen/docgen.gpr.py @@ -18,7 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # diff --git a/gramps/plugins/docgen/gtkprint.py b/gramps/plugins/docgen/gtkprint.py index de9259293..00f4048d2 100644 --- a/gramps/plugins/docgen/gtkprint.py +++ b/gramps/plugins/docgen/gtkprint.py @@ -81,7 +81,7 @@ MARGIN = 6 (ZOOM_BEST_FIT, ZOOM_FIT_WIDTH, ZOOM_FREE,) = list(range(3)) - + #------------------------------------------------------------------------ # # Converter functions @@ -90,7 +90,7 @@ MARGIN = 6 def paperstyle_to_pagesetup(paper_style): """Convert a PaperStyle instance into a Gtk.PageSetup instance. - + @param paper_style: Gramps paper style object to convert @param type: PaperStyle @return: page_setup @@ -123,7 +123,7 @@ def paperstyle_to_pagesetup(paper_style): # First set the paper size gramps_paper_size = paper_style.get_size() gramps_paper_name = gramps_paper_size.get_name() - + # All sizes not included in the translation table (even if a standard size) # are handled as custom format, because we are not intelligent enough. if gramps_paper_name in gramps_to_gtk: @@ -140,10 +140,10 @@ def paperstyle_to_pagesetup(paper_style): paper_width, paper_height, Gtk.Unit.MM) log.debug("Selected paper size: (%f,%f)" % (paper_width, paper_height)) - + page_setup = Gtk.PageSetup() page_setup.set_paper_size(paper_size) - + # Set paper orientation if paper_style.get_orientation() == PAPER_PORTRAIT: page_setup.set_orientation(Gtk.PageOrientation.PORTRAIT) @@ -159,7 +159,7 @@ def paperstyle_to_pagesetup(paper_style): Gtk.Unit.MM) page_setup.set_right_margin(paper_style.get_right_margin() * 10, Gtk.Unit.MM) - + return page_setup #------------------------------------------------------------------------ @@ -181,17 +181,17 @@ class PrintPreview(object): 3.00: '300%', 4.00: '400%', } - + def __init__(self, operation, preview, context, parent): self._operation = operation self._preview = preview self._context = context - + self.__build_window() self._current_page = None # Private - + def __build_window(self): """Build the window from Glade. """ @@ -199,7 +199,7 @@ class PrintPreview(object): glade_xml = Glade() self._window = glade_xml.toplevel #self._window.set_transient_for(parent) - + # remember active widgets for future use self._swin = glade_xml.get_object('swin') self._drawing_area = glade_xml.get_object('drawingarea') @@ -226,47 +226,47 @@ class PrintPreview(object): ##return cairo.PDFSurface(StringIO(), ##self._context.get_width(), ##self._context.get_height()) - + ##def get_page(self, page_no): ##"""Get the cairo surface of the given page. - + ##Surfaces are also cached for instant access. - + ##""" ##if page_no >= len(self._page_numbers): ##log.debug("Page number %d doesn't exist." % page_no) ##page_no = 0 - + ##if page_no not in self._page_surfaces: ##surface = self.create_surface() ##cr = cairo.Context(surface) - + ##if PRINTER_SCALE != 1.0: ##cr.scale(PRINTER_SCALE, PRINTER_SCALE) - + ##self._context.set_cairo_context(cr, PRINTER_DPI, PRINTER_DPI) ##self._preview.render_page(self._page_numbers[page_no]) - + ##self._page_surfaces[page_no] = surface - + ##return self._page_surfaces[page_no] - + def __set_page(self, page_no): if page_no < 0 or page_no >= self._page_no: return - + if self._current_page != page_no: self._drawing_area.queue_draw() - + self._current_page = page_no self._first_button.set_sensitive(self._current_page) self._prev_button.set_sensitive(self._current_page) self._next_button.set_sensitive(self._current_page < self._page_no - 1) self._last_button.set_sensitive(self._current_page < self._page_no - 1) - + self._pages_entry.set_text('%d' % (self._current_page + 1)) - + def __set_zoom(self, zoom): self._zoom = zoom @@ -274,12 +274,12 @@ class PrintPreview(object): screen_height = int(self._paper_height * self._zoom + 2 * MARGIN) self._drawing_area.set_size_request(screen_width, screen_height) self._drawing_area.queue_draw() - + self._zoom_in_button.set_sensitive(self._zoom != max(self.zoom_factors)) self._zoom_out_button.set_sensitive(self._zoom != min(self.zoom_factors)) - + def __zoom_in(self): zoom = [z for z in self.zoom_factors if z > self._zoom] @@ -287,10 +287,10 @@ class PrintPreview(object): return min(zoom) else: return self._zoom - + def __zoom_out(self): zoom = [z for z in self.zoom_factors if z < self._zoom] - + if zoom: return max(zoom) else: @@ -311,7 +311,7 @@ class PrintPreview(object): zoom = min(width / self._paper_width, height / self._paper_height) return zoom - + def __get_view_size(self): """Get the dimensions of the scrolled window. """ @@ -329,24 +329,24 @@ class PrintPreview(object): spacing = spacing.get_int() else: spacing = 0 - + reqmin, req = self._swin.get_vscrollbar().get_preferred_size() vsb_w = spacing + req.width reqmin, req = self._swin.get_hscrollbar().get_preferred_size() hsb_h = spacing + req.height - + return width, height, vsb_w, hsb_h def __end_preview(self): self._operation.end_preview() - + # Signal handlers - + def on_drawingarea_draw_event(self, drawing_area, context): cr = context #cr.rectangle(event.area) #cr.clip() - + # get the extents of the page and the screen paper_w = int(self._paper_width * self._zoom) paper_h = int(self._paper_height * self._zoom) @@ -356,18 +356,18 @@ class PrintPreview(object): width -= vsb_w if paper_w > width: height -= hsb_h - + # put the paper on the middle of the window xtranslate = MARGIN if paper_w < width: xtranslate += (width - paper_w) / 2 - + ytranslate = MARGIN if paper_h < height: ytranslate += (height - paper_h) / 2 - + cr.translate(xtranslate, ytranslate) - + # draw an empty white page cr.set_source_rgb(1.0, 1.0, 1.0) cr.rectangle(0, 0, paper_w, paper_h) @@ -375,18 +375,18 @@ class PrintPreview(object): cr.set_source_rgb(0, 0, 0) cr.set_line_width(1) cr.stroke() - + if self._orientation == Gtk.PageOrientation.LANDSCAPE: cr.rotate(radians(-90)) cr.translate(-paper_h, 0) - + ##page_setup = self._context.get_page_setup() ##cr.translate(page_setup.get_left_margin(Gtk.Unit.POINTS), ##page_setup.get_top_margin(Gtk.Unit.POINTS)) - + ##cr.set_source_surface(self.get_page(0)) ##cr.paint() - + # draw the content of the currently selected page # Here we use dpi scaling instead of scaling the cairo context, # because it gives better result. In the latter case the distance @@ -394,40 +394,40 @@ class PrintPreview(object): dpi = PRINTER_DPI * self._zoom self._context.set_cairo_context(cr, dpi, dpi) self._preview.render_page(self._current_page) - + def on_swin_size_allocate(self, scrolledwindow, allocation): if self._zoom_mode == ZOOM_FIT_WIDTH: self.__set_zoom(self.__zoom_fit_width()) - + if self._zoom_mode == ZOOM_BEST_FIT: self.__set_zoom(self.__zoom_best_fit()) def on_print_clicked(self, toolbutton): pass - + def on_first_clicked(self, toolbutton): self.__set_page(0) - + def on_prev_clicked(self, toolbutton): self.__set_page(self._current_page - 1) - + def on_next_clicked(self, toolbutton): self.__set_page(self._current_page + 1) - + def on_last_clicked(self, toolbutton): self.__set_page(self._page_no - 1) - + def on_entry_activate(self, entry): try: new_page = int(entry.get_text()) - 1 except ValueError: new_page = self._current_page - + if new_page < 0 or new_page >= self._page_no: new_page = self._current_page - + self.__set_page(new_page) - + def on_zoom_fit_width_toggled(self, toggletoolbutton): if toggletoolbutton.get_active(): self._zoom_best_fit_button.set_active(False) @@ -435,7 +435,7 @@ class PrintPreview(object): self.__set_zoom(self.__zoom_fit_width()) else: self._zoom_mode = ZOOM_FREE - + def on_zoom_best_fit_toggled(self, toggletoolbutton): if toggletoolbutton.get_active(): self._zoom_fit_width_button.set_active(False) @@ -449,13 +449,13 @@ class PrintPreview(object): self._zoom_best_fit_button.set_active(False) self._zoom_mode = ZOOM_FREE self.__set_zoom(self.__zoom_in()) - + def on_zoom_out_clicked(self, toolbutton): self._zoom_fit_width_button.set_active(False) self._zoom_best_fit_button.set_active(False) self._zoom_mode = ZOOM_FREE self.__set_zoom(self.__zoom_out()) - + def on_window_delete_event(self, widget, event): self.__end_preview() return False @@ -485,10 +485,10 @@ class PrintPreview(object): self._zoom_mode = ZOOM_FREE self.__set_zoom(1.0) self.__set_page(0) - + # let's the show begin... self._window.show() - + #------------------------------------------------------------------------ # # GtkPrint class @@ -496,9 +496,9 @@ class PrintPreview(object): #------------------------------------------------------------------------ class GtkPrint(libcairodoc.CairoDoc): """Print document via GtkPrint* interface. - + Requires Gtk+ 2.10. - + """ def run(self): """Run the Gtk Print operation. @@ -507,7 +507,7 @@ class GtkPrint(libcairodoc.CairoDoc): # get a page setup from the paper style we have page_setup = paperstyle_to_pagesetup(self.paper) - + # set up a print operation operation = Gtk.PrintOperation() operation.set_default_page_setup(page_setup) @@ -536,7 +536,7 @@ class GtkPrint(libcairodoc.CairoDoc): # set print settings if it was stored previously if PRINT_SETTINGS is not None: operation.set_print_settings(PRINT_SETTINGS) - + # store print settings if printing was successful if res == Gtk.PrintOperationResult.APPLY: PRINT_SETTINGS = operation.get_print_settings() @@ -549,7 +549,7 @@ class GtkPrint(libcairodoc.CairoDoc): self.page_height = round(context.get_height()) self.dpi_x = context.get_dpi_x() self.dpi_y = context.get_dpi_y() - + def on_paginate(self, operation, context): """Paginate the whole document in chunks. """ @@ -562,11 +562,11 @@ class GtkPrint(libcairodoc.CairoDoc): self.dpi_y) # update page number operation.set_n_pages(len(self._pages)) - + # start preview if needed if finished and self.preview: self.preview.start() - + return finished def on_draw_page(self, operation, context, page_nr): @@ -580,15 +580,15 @@ class GtkPrint(libcairodoc.CairoDoc): dpi_y = context.get_dpi_y() self.draw_page(page_nr, cr, layout, width, height, dpi_x, dpi_y) - + def on_preview(self, operation, preview, context, parent): """Implement custom print preview functionality. """ ##if constfunc.win()': ##return False - + self.preview = PrintPreview(operation, preview, context, parent) - + # give a dummy cairo context to Gtk.PrintContext, # PrintPreview will update it with the real one try: @@ -602,5 +602,5 @@ class GtkPrint(libcairodoc.CairoDoc): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) cr = cairo.Context(surface) context.set_cairo_context(cr, PRINTER_DPI, PRINTER_DPI) - + return True diff --git a/gramps/plugins/docgen/htmldoc.py b/gramps/plugins/docgen/htmldoc.py index 4a46d5afc..663ec2358 100644 --- a/gramps/plugins/docgen/htmldoc.py +++ b/gramps/plugins/docgen/htmldoc.py @@ -31,7 +31,7 @@ Report output generator for html documents, based on Html and HtmlBackend #------------------------------------------------------------------------ # -# python modules +# python modules # #------------------------------------------------------------------------ import os @@ -40,7 +40,7 @@ import time #------------------------------------------------------------------------ # -# GRAMPS modules +# GRAMPS modules # #------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale @@ -76,20 +76,20 @@ _CLICKABLE = r'''\1''' # #------------------------------------------------------------------------ class HtmlDoc(BaseDoc, TextDoc): - """Implementation of the BaseDoc and TextDoc gen.plug.docgen api for the + """Implementation of the BaseDoc and TextDoc gen.plug.docgen api for the creation of Html files. This is achieved by writing on a HtmlBackend object - + div id's defined here: id="grampstextdoc" : the entire text report id="grampsheading" : a small defined heading, but not h1 to h6 ! - id="grampsstylednote" : start of part with a styled note, divided in + id="grampsstylednote" : start of part with a styled note, divided in paragraphs - id="grampsnote" : start of part with a note. This id is normally not + id="grampsnote" : start of part with a note. This id is normally not used - + The styles as defined in the stylesheed of the textdoc, will be converted - to css class. Color is removed to avoid conflicts with the css. Also + to css class. Color is removed to avoid conflicts with the css. Also Fontface is removed. Size, italic, bold, margins, borders are retained """ @@ -110,7 +110,7 @@ class HtmlDoc(BaseDoc, TextDoc): def set_css_filename(self, css_filename): """ - Set the css file to use. The path must be included. + Set the css file to use. The path must be included. Note: DocReportDialog sets this for html doc """ if css_filename and os.path.basename(css_filename): @@ -127,7 +127,7 @@ class HtmlDoc(BaseDoc, TextDoc): self.htmllist += [self._backend.html_body] #start a gramps report self.htmllist += [Html('div', id="grampstextdoc")] - + self.build_header() def build_header(self): @@ -138,24 +138,24 @@ class HtmlDoc(BaseDoc, TextDoc): # create additional meta tags _meta1 = 'name="generator" content="%s %s %s"' % (PROGRAM_NAME, VERSION, URL_HOMEPAGE) - meta = Html('meta', attr = _meta1) - + meta = Html('meta', attr = _meta1) + #set styles of the report as inline css self.build_style_declaration() - - + + # GRAMPS favicon en css fname1 = '/'.join([self._backend.datadir(), 'favicon.ico']) fname2 = '/'.join([self._backend.datadir(), _TEXTDOCSCREEN]) fname3 = '/'.join([self._backend.datadir(), _HTMLSCREEN]) - + # links for GRAMPS favicon and stylesheets links = Html('link', rel='shortcut icon', href=fname1, type='image/x-icon') + ( Html('link', rel='stylesheet', href=fname2, type='text/css', media='screen', indent=False),) if self.css_filename: - links += (Html('link', rel='stylesheet', href=fname3, + links += (Html('link', rel='stylesheet', href=fname3, type='text/css', media='screen', indent=False), ) self._backend.html_header += (meta, links) @@ -165,7 +165,7 @@ class HtmlDoc(BaseDoc, TextDoc): Convert the styles of the report into inline css for the html doc """ styles = self.get_style_sheet() - + text = [] for sname in styles.get_cell_style_names(): @@ -182,9 +182,9 @@ class HtmlDoc(BaseDoc, TextDoc): right = 'thin solid #000000' text.append('#%s .%s {\n' '\tpadding: %s %s %s %s;\n' - '\tborder-top:%s; border-bottom:%s;\n' - '\tborder-left:%s; border-right:%s;\n}' - % (id, sname, pad, pad, pad, pad, top, bottom, + '\tborder-top:%s; border-bottom:%s;\n' + '\tborder-left:%s; border-right:%s;\n}' + % (id, sname, pad, pad, pad, pad, top, bottom, left, right)) @@ -219,18 +219,18 @@ class HtmlDoc(BaseDoc, TextDoc): # family = '"Helvetica","Arial","sans-serif"' #else: # family = '"Times New Roman","Times","serif"' - # do not allow color, set in base css ! - # so no : 'color: %s' % font_color + # do not allow color, set in base css ! + # so no : 'color: %s' % font_color # so no : 'font-family:%s;' % family text.append('#%s .%s {\n' - '\tfont-size: %dpt;\n' - '\ttext-align: %s; text-indent: %scm;\n' - '\tmargin-right: %scm; margin-left: %scm;\n' - '\tmargin-top: %scm; margin-bottom: %scm;\n' - '\tborder-top:%s; border-bottom:%s;\n' - '\tborder-left:%s; border-right:%s;\n' - '\t%s%s\n}' - % (id, style_name, font_size, + '\tfont-size: %dpt;\n' + '\ttext-align: %s; text-indent: %scm;\n' + '\tmargin-right: %scm; margin-left: %scm;\n' + '\tmargin-top: %scm; margin-bottom: %scm;\n' + '\tborder-top:%s; border-bottom:%s;\n' + '\tborder-left:%s; border-right:%s;\n' + '\t%s%s\n}' + % (id, style_name, font_size, align, text_indent, right_margin, left_margin, top_margin, bottom_margin, @@ -279,13 +279,13 @@ class HtmlDoc(BaseDoc, TextDoc): "a different directory to store your generated " "web pages.")) self.warn_dir = False - + def write_support_files(self): """ Copy support files to the datadir that needs to hold them """ #css of textdoc styles - tdfile = open(os.path.join(self._backend.datadirfull(), + tdfile = open(os.path.join(self._backend.datadirfull(), _TEXTDOCSCREEN), 'w') tdfile.write(self.style_declaration) tdfile.close() @@ -296,26 +296,26 @@ class HtmlDoc(BaseDoc, TextDoc): if os.path.exists(fullpath): self.copy_file(fullpath, _HTMLSCREEN) #favicon - self.copy_file(os.path.join(IMAGE_DIR, 'webstuff', 'favicon.ico'), + self.copy_file(os.path.join(IMAGE_DIR, 'webstuff', 'favicon.ico'), 'favicon.ico') def __reduce_list(self): """ - Takes the internal list of html objects, and adds the last to the + Takes the internal list of html objects, and adds the last to the previous. This closes the upper tag """ self.htmllist[-2] += self.htmllist[-1] self.htmllist.pop() - + def __write_text(self, text, mark=None, markup=False, links=False): """ @param text: text to write. @param mark: IndexMark to use for indexing (not supported) - @param markup: True if text already contains markup info. + @param markup: True if text already contains markup info. Then text will no longer be escaped @param links: make URLs clickable if True """ - if not markup: + if not markup: text = self._backend.ESCAPE_FUNC()(text) if self.__title_written == 0 : self.title += text @@ -323,14 +323,14 @@ class HtmlDoc(BaseDoc, TextDoc): import re text = re.sub(URL_PATTERN, _CLICKABLE, text) self.htmllist[-1] += text - + def __empty_char(self): """ - Output a non breaking whitespace so as to have browser behave ok on + Output a non breaking whitespace so as to have browser behave ok on empty content """ self.__write_text(' ', markup=True) - + def write_text(self, text, mark=None, links=False): """ Overwrite base method @@ -343,9 +343,9 @@ class HtmlDoc(BaseDoc, TextDoc): """ Add title field to header """ - self._backend.html_header += Html('title', self.title, + self._backend.html_header += Html('title', self.title, inline=True) - + def start_table(self, name, style): """ Overwrite base method @@ -386,11 +386,11 @@ class HtmlDoc(BaseDoc, TextDoc): tag = "td" self._empty = 1 if span > 1: - self.htmllist += (Html(tag, colspan=str(span), + self.htmllist += (Html(tag, colspan=str(span), class_=style_name),) self._col += span else: - self.htmllist += (Html(tag, colspan=str(span), + self.htmllist += (Html(tag, colspan=str(span), width=str(self._tbl.get_column_width( self._col))+ '%', class_=style_name),) @@ -456,7 +456,7 @@ class HtmlDoc(BaseDoc, TextDoc): Overwrite base method """ self.__reduce_list() - + def start_superscript(self): """ Overwrite base method @@ -472,14 +472,14 @@ class HtmlDoc(BaseDoc, TextDoc): def write_styled_note(self, styledtext, format, style_name, contains_html=False, links=False): """ - Convenience function to write a styledtext to the html doc. + Convenience function to write a styledtext to the html doc. styledtext : assumed a StyledText object to write format : = 0 : Flowed, = 1 : Preformatted style_name : name of the style to use for default presentation - contains_html: bool, the backend should not check if html is present. - If contains_html=True, then the textdoc is free to handle that in + contains_html: bool, the backend should not check if html is present. + If contains_html=True, then the textdoc is free to handle that in some way. Eg, a textdoc could remove all tags, or could make sure - a link is clickable. HtmlDoc will show the html as pure text, so + a link is clickable. HtmlDoc will show the html as pure text, so no escaping will happen. links: bool, make URLs clickable if True """ @@ -488,13 +488,13 @@ class HtmlDoc(BaseDoc, TextDoc): self.htmllist += [Html('div', id='grampsstylednote')] if contains_html: #just dump the note out as it is. Adding markup would be dangerous - # as it could destroy the html. If html code, one can do the + # as it could destroy the html. If html code, one can do the self.start_paragraph(style_name) self.__write_text(text, markup=True, links=links) self.end_paragraph() else: s_tags = styledtext.get_tags() - markuptext = self._backend.add_markup_from_styled(text, s_tags, + markuptext = self._backend.add_markup_from_styled(text, s_tags, split='\n') self.start_paragraph(style_name) inpara = True @@ -528,7 +528,7 @@ class HtmlDoc(BaseDoc, TextDoc): linenb += 1 if inpara == True: self.end_paragraph() - if sigcount == 0: + if sigcount == 0: # if the last line was blank, then as well as outputting the previous para, # which we have just done, # we also output a new blank para @@ -551,7 +551,7 @@ class HtmlDoc(BaseDoc, TextDoc): try: resize_to_jpeg(name, imdir + os.sep + refname, size, size, crop=crop) except: - LOG.warn(_("Could not create jpeg version of image %(name)s") % + LOG.warn(_("Could not create jpeg version of image %(name)s") % {'name' : name}) return @@ -566,7 +566,7 @@ class HtmlDoc(BaseDoc, TextDoc): Html('p', class_="DDR-Caption") + alt ) else: - self.htmllist[-1] += Html('img', src= imdir + os.sep + refname, + self.htmllist[-1] += Html('img', src= imdir + os.sep + refname, border = '0', alt=alt) else: if len(alt): @@ -576,7 +576,7 @@ class HtmlDoc(BaseDoc, TextDoc): Html('p', class_="DDR-Caption") + alt ) else: - self.htmllist[-1] += Html('img', src= imdir + os.sep + refname, + self.htmllist[-1] += Html('img', src= imdir + os.sep + refname, border = '0', alt=alt, align=pos) def page_break(self): diff --git a/gramps/plugins/docgen/latexdoc.py b/gramps/plugins/docgen/latexdoc.py index 7f1910eb7..3161fafd7 100644 --- a/gramps/plugins/docgen/latexdoc.py +++ b/gramps/plugins/docgen/latexdoc.py @@ -59,7 +59,7 @@ except: "in LaTeX documents will not be available. " "Use your package manager to install python-imaging " "or python-pillow or python3-pillow")) - + _CLICKABLE = '\\url{\\1}' #------------------------------------------------------------------------ @@ -1230,7 +1230,7 @@ class LaTeXDoc(BaseDoc, TextDoc): self.emit(''.join(('%\n *** Error: cannot convert ', infile, '\n *** to ', outfile, 'PIL not installed %\n'))) - + if self.in_table: self.pict_in_table = True diff --git a/gramps/plugins/docgen/odfdoc.py b/gramps/plugins/docgen/odfdoc.py index 6257f29dd..cb92945d5 100644 --- a/gramps/plugins/docgen/odfdoc.py +++ b/gramps/plugins/docgen/odfdoc.py @@ -14,7 +14,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -54,11 +54,11 @@ ODFDoc : used to generate Open Office Document # pylint: disable-msg=W0613 # errors : # disable-msg=E1101 # has no member -# pylint: disable-msg=E1101 +# pylint: disable-msg=E1101 #------------------------------------------------------------------------- # -# Standard Python Modules +# Standard Python Modules # #------------------------------------------------------------------------- import os @@ -76,7 +76,7 @@ from xml.sax.saxutils import escape #------------------------------------------------------------------------- from gramps.gen.plug.docgen import (BaseDoc, TextDoc, DrawDoc, graphicstyle, FONT_SANS_SERIF, SOLID, PAPER_PORTRAIT, - INDEX_TYPE_TOC, PARA_ALIGN_CENTER, PARA_ALIGN_LEFT, + INDEX_TYPE_TOC, PARA_ALIGN_CENTER, PARA_ALIGN_LEFT, INDEX_TYPE_ALP, PARA_ALIGN_RIGHT, URL_PATTERN, LOCAL_HYPERLINK, LOCAL_TARGET) from gramps.gen.plug.docgen.fontscale import string_width @@ -99,9 +99,9 @@ _ = glocale.translation.gettext _apptype = 'application/vnd.oasis.opendocument.text' _esc_map = { - '\x1a' : '', - '\x0c' : '', - '\n' : '', + '\x1a' : '', + '\x0c' : '', + '\n' : '', '\t' : '', } @@ -161,11 +161,11 @@ _FONTS = '''\ _META_XML = '''\ - @@ -207,35 +207,35 @@ _META_XML = '''\ ''' _STYLES = '''\ - - - - - - - - + + - - + + - - - ''' @@ -317,7 +317,7 @@ _CLEAR_STYLE = '''\ \n ''' _OTHER_STYLES = '''\ -\n \n \n @@ -486,7 +486,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): self.init_called = True wrt = self.cntnt.write wrt1, wrt2 = self.cntnt1.write, self.cntnt2.write - + self.lang = glocale.lang self.lang = self.lang.replace('_', '-') if self.lang else "en-US" @@ -516,12 +516,12 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): 'style:family="graphic">\n' '\n' + '\n' + - + '\n' + @@ -613,7 +613,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): wrt('fo:text-align="end" ') elif align == PARA_ALIGN_CENTER: wrt( - 'fo:text-align="center" ' + 'fo:text-align="center" ' 'style:justify-single-word="false" ' ) else: @@ -711,11 +711,11 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): '' + - '' % width_str + '\n' ) - + for cell in styles.get_cell_style_names(): cell_style = styles.get_cell_style(cell) wrt( @@ -728,7 +728,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): ("0.002cm solid #000000" if cell_style.get_top_border() else "none") - ) + ) wrt(' fo:border-bottom="%s"' % ("0.002cm solid #000000" @@ -740,19 +740,19 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): ("0.002cm solid #000000" if cell_style.get_left_border() else "none") - ) + ) wrt(' fo:border-right="%s"' % ("0.002cm solid #000000" if cell_style.get_right_border() else "none") - ) + ) wrt( - '/>\n' + '/>\n' '\n' ) - + wrt( _OTHER_STYLES ) @@ -776,7 +776,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): result = [] for item in list_: marker = funct(item[0]) - if marker in seen: + if marker in seen: continue seen.add(marker) result.append(item) @@ -805,8 +805,8 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): Close the document and create the odt file """ self.cntnt.write( - '\n' - '\n' + '\n' + '\n' '\n' ) self.finish_cntnt_creation() @@ -830,7 +830,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): wrt1( '\n\n' ) @@ -884,7 +884,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): 'style:name="FontFace__%s__"\n' % style[2] + ' style:family="text">\n' + ' \n' + '\n\n' @@ -1008,7 +1008,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): (x, y) = image_size(file_name) if (x, y) == (0, 0): return - + not_extension, extension = os.path.splitext(file_name) file_name_hash = file_name file_name_hash = file_name_hash.encode('utf-8') @@ -1020,7 +1020,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): base = escape(os.path.basename(file_name)) tag = base.replace('.', '_') - + if self.new_cell: self.cntnt.write('') @@ -1029,13 +1029,13 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): if crop: (start_x, start_y, end_x, end_y ) = crop_percentage_to_subpixel(x, y, crop) - + # Need to keep the ratio intact, otherwise scaled images look stretched # if the dimensions aren't close in size (act_width, act_height) = image_actual_size( x_cm, y_cm, int(end_x-start_x), int(end_y-start_y) - ) - + ) + dpi = image_dpi(file_name) # ODF wants crop measurements in inch and as margins from each side @@ -1137,7 +1137,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): ) if span > 1: self.cntnt.write(' table:number-columns-spanned="%s">\n' % span) - else: + else: self.cntnt.write('>\n') self.new_cell = 1 @@ -1161,7 +1161,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): close bold """ self.cntnt.write('') - + def start_superscript(self): """ open superscript @@ -1195,7 +1195,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): raise ReportError(errmsg) except: raise ReportError(_("Could not create %s") % self.filename) - + t = time.localtime(time.time())[:6] self._add_zip(zfile, "META-INF/manifest.xml", self.mfile.getvalue(), t) @@ -1211,7 +1211,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): self.stfile.close() self.sfile.close() self.mimetype.close() - + for image in self.media_list: try: ifile = open(image[0], mode='rb') @@ -1229,7 +1229,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): """ self.sfile = StringIO() wrtf = self.sfile.write - + wrtf('\n') wrtf('\n' + _STYLES ) - + styles = self.get_style_sheet() - + for style_name in styles.get_paragraph_style_names(): style = styles.get_paragraph_style(style_name) wrtf( @@ -1360,7 +1360,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): #wrtf('\n') #wrtf('\n') - + wrtf( '\n' + '\n' ) - + # header wrtf( '\n' @@ -1446,7 +1446,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): '\n' ) - # Master Styles + # Master Styles wrtf( '\n' '' '\n' ) - # End of document styles + # End of document styles wrtf('\n') def page_break(self): @@ -1491,7 +1491,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): close the page """ self.cntnt.write('\n') - + def start_paragraph(self, style_name, leader=None): """ open a new paragraph @@ -1527,12 +1527,12 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): def write_styled_note(self, styledtext, format, style_name, contains_html=False, links=False): """ - Convenience function to write a styledtext to the ODF doc. + Convenience function to write a styledtext to the ODF doc. styledtext : assumed a StyledText object to write format : = 0 : Flowed, = 1 : Preformatted style_name : name of the style to use for default presentation - contains_html: bool, the backend should not check if html is present. - If contains_html=True, then the textdoc is free to handle that in + contains_html: bool, the backend should not check if html is present. + If contains_html=True, then the textdoc is free to handle that in some way. Eg, a textdoc could remove all tags, or could make sure a link is clickable. ODFDoc prints the html without handling it links: bool, make URLs clickable if True @@ -1629,7 +1629,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): 'text:outline-level="3" ' + 'text:use-outline-level="false">') - self.cntnt.write('' + title) self.cntnt.write('') @@ -1650,7 +1650,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): self.cntnt.write('') self.cntnt.write('') - self.cntnt.write('%s' % + self.cntnt.write('%s' % title) self.cntnt.write('') self.cntnt.write('') @@ -1668,10 +1668,10 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): 'text:combine-entries="false" ' + 'text:combineentries-with-pp="false">') - self.cntnt.write('' + title) self.cntnt.write('') - + self.cntnt.write('') @@ -1686,7 +1686,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): self.cntnt.write('') self.cntnt.write('') - self.cntnt.write('%s' % + self.cntnt.write('%s' % title) self.cntnt.write('') self.cntnt.write('') @@ -1750,7 +1750,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): 'xmlns:ooo="http://openoffice.org/2004/office"\n' + 'xmlns:xlink="http://www.w3.org/1999/xlink" />' ) - + def _write_mimetype_file(self): """ create the mimetype.xml file @@ -1813,7 +1813,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): escape('\n'.join(text), _esc_map) + '\n\n' + '\n') - + def draw_path(self, style, path): """ Draw a path @@ -1840,7 +1840,7 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc): 'svg:width="%.4fcm" ' % (maxx - minx) + 'svg:height="%.4fcm" ' % (maxy - miny) ) - + point = path[0] x1 = int((point[0] - minx) * 1000) y1 = int((point[1] - miny) * 1000) @@ -1989,12 +1989,12 @@ def process_spaces(line, format): Function to process spaces in text lines for flowed and pre-formatted notes. line : text to process format : = 0 : Flowed, = 1 : Preformatted - + If the text is flowed (format==0), then leading spaces (after ignoring XML) are removed. Embedded multiple spaces are reduced to one by ODF If the text is pre-formatted (format==1). then all spaces (after ignoring XML) are replaced by "" - + Returns the processed text, and the number of significant (i.e. non-white-space) chars. """ txt = "" @@ -2003,7 +2003,7 @@ def process_spaces(line, format): # we loop through every character, which is very inefficient, but an attempt to use # a regex replace didn't always work. This was the code that was replaced. # Problem, we may not replace ' ' in xml tags, so we use a regex - # self.cntnt.write(re.sub(' (?=([^(<|>)]*<[^>]*>)*[^>]*$)', + # self.cntnt.write(re.sub(' (?=([^(<|>)]*<[^>]*>)*[^>]*$)', # "", line)) for char in line: if char == '<' and xml == False: @@ -2027,4 +2027,4 @@ def process_spaces(line, format): sigcount += 1 txt += char return [txt, sigcount] - + diff --git a/gramps/plugins/docgen/rtfdoc.py b/gramps/plugins/docgen/rtfdoc.py index 908e8cb92..be6a9548c 100644 --- a/gramps/plugins/docgen/rtfdoc.py +++ b/gramps/plugins/docgen/rtfdoc.py @@ -52,8 +52,8 @@ _CLICKABLE = r'''{\\field{\\*\\fldinst HYPERLINK "\1"}{\\fldrslt \1}}''' #------------------------------------------------------------------------ # -# RTF uses a unit called "twips" for its measurements. According to the -# RTF specification, 1 point is 20 twips. This routines converts +# RTF uses a unit called "twips" for its measurements. According to the +# RTF specification, 1 point is 20 twips. This routines converts # centimeters to twips # # 2.54 cm/inch 72pts/inch, 20twips/pt @@ -74,7 +74,7 @@ class RTFDoc(BaseDoc,TextDoc): # # Opens the file, and writes the header. Builds the color and font # tables. Fonts are chosen using the MS TrueType fonts, since it - # is assumed that if you are generating RTF, you are probably + # is assumed that if you are generating RTF, you are probably # targeting Word. This generator assumes a Western Europe character # set. # @@ -92,7 +92,7 @@ class RTFDoc(BaseDoc,TextDoc): raise ReportError(errmsg) except: raise ReportError(_("Could not create %s") % self.filename) - + style_sheet = self.get_style_sheet() self.f.write( @@ -153,7 +153,7 @@ class RTFDoc(BaseDoc,TextDoc): #-------------------------------------------------------------------- # # Starts a paragraph. Instead of using a style sheet, generate the - # the style for each paragraph on the fly. Not the ideal, but it + # the style for each paragraph on the fly. Not the ideal, but it # does work. # #-------------------------------------------------------------------- @@ -222,12 +222,12 @@ class RTFDoc(BaseDoc,TextDoc): self.text = "" self.f.write('\\tab}') self.opened = 0 - + #-------------------------------------------------------------------- # - # Ends a paragraph. Care has to be taken to make sure that the + # Ends a paragraph. Care has to be taken to make sure that the # braces are closed properly. The self.opened flag is used to indicate - # if braces are currently open. If the last write was the end of + # if braces are currently open. If the last write was the end of # a bold-faced phrase, braces may already be closed. # #-------------------------------------------------------------------- @@ -240,7 +240,7 @@ class RTFDoc(BaseDoc,TextDoc): # there is no newline between the description and the note. if not self.in_table: self.f.write(self.text) - LOG.debug("end_paragraph: opened: %d write: %s" % + LOG.debug("end_paragraph: opened: %d write: %s" % (self.opened, self.text + '}' if self.opened else "" + "newline")) if self.opened: @@ -267,8 +267,8 @@ class RTFDoc(BaseDoc,TextDoc): # #-------------------------------------------------------------------- def start_bold(self): - LOG.debug("start_bold: opened: %d saved text: %s" % - (self.opened, + LOG.debug("start_bold: opened: %d saved text: %s" % + (self.opened, '}' if self.opened else "" + '{%s\\b ' % self.font_type)) if self.opened: self.text += '}' @@ -281,8 +281,8 @@ class RTFDoc(BaseDoc,TextDoc): # #-------------------------------------------------------------------- def end_bold(self): - LOG.debug("end_bold: opened: %d saved text: %s" % - (self.opened, + LOG.debug("end_bold: opened: %d saved text: %s" % + (self.opened, self.text + '}')) if not self.opened == 1: print(self.opened) @@ -300,7 +300,7 @@ class RTFDoc(BaseDoc,TextDoc): # # Start a table. Grab the table style, and store it. Keep a flag to # indicate that we are in a table. This helps us deal with paragraphs - # internal to a table. RTF does not require anything to start a + # internal to a table. RTF does not require anything to start a # table, since a table is treated as a bunch of rows. # #-------------------------------------------------------------------- @@ -349,8 +349,8 @@ class RTFDoc(BaseDoc,TextDoc): # # Start a cell. Dump out the cell specifics, such as borders. Cell # widths are kind of interesting. RTF doesn't specify how wide a cell - # is, but rather where it's right edge is in relationship to the - # left margin. This means that each cell is the cumlative of the + # is, but rather where it's right edge is in relationship to the + # left margin. This means that each cell is the cumlative of the # previous cells plus its own width. # #-------------------------------------------------------------------- @@ -385,7 +385,7 @@ class RTFDoc(BaseDoc,TextDoc): #-------------------------------------------------------------------- # - # Add a photo. Embed the photo in the document. Use the Python + # Add a photo. Embed the photo in the document. Use the Python # imaging library to load and scale the photo. The image is converted # to JPEG, since it is smaller, and supported by RTF. The data is # dumped as a string of HEX numbers. @@ -424,12 +424,12 @@ class RTFDoc(BaseDoc,TextDoc): def write_styled_note(self, styledtext, format, style_name, contains_html=False, links=False): """ - Convenience function to write a styledtext to the RTF doc. + Convenience function to write a styledtext to the RTF doc. styledtext : assumed a StyledText object to write format : = 0 : Flowed, = 1 : Preformatted style_name : name of the style to use for default presentation - contains_html: bool, the backend should not check if html is present. - If contains_html=True, then the textdoc is free to handle that in + contains_html: bool, the backend should not check if html is present. + If contains_html=True, then the textdoc is free to handle that in some way. Eg, a textdoc could remove all tags, or could make sure a link is clickable. RTFDoc prints the html without handling it links: bool, make URLs clickable if True @@ -463,17 +463,17 @@ class RTFDoc(BaseDoc,TextDoc): #-------------------------------------------------------------------- # - # Writes text. If braces are not currently open, open them. Loop + # Writes text. If braces are not currently open, open them. Loop # character by character (terribly inefficient, but it works). If a - # character is 8 bit (>127), convert it to a hex representation in + # character is 8 bit (>127), convert it to a hex representation in # the form of \`XX. Make sure to escape braces. # #-------------------------------------------------------------------- def write_text(self, text, mark=None, links=False): # Convert to unicode, just in case it's not. Fix of bug 2449. text = str(text) - LOG.debug("write_text: opened: %d input text: %s" % - (self.opened, + LOG.debug("write_text: opened: %d input text: %s" % + (self.opened, text)) if self.opened == 0: self.opened = 1 @@ -484,7 +484,7 @@ class RTFDoc(BaseDoc,TextDoc): if ord(i) < 256: self.text += '\\\'%2x' % ord(i) else: - # If (uni)code with more than 8 bits: + # If (uni)code with more than 8 bits: # RTF req valus in decimal, not hex. self.text += '{\\uc1\\u%d\\uc0}' % ord(i) elif i == '\n': @@ -497,8 +497,8 @@ class RTFDoc(BaseDoc,TextDoc): if links == True: import re self.text = re.sub(URL_PATTERN, _CLICKABLE, self.text) - LOG.debug("write_text, exit: opened: %d saved text: %s" % - (self.opened, + LOG.debug("write_text, exit: opened: %d saved text: %s" % + (self.opened, self.text)) def process_spaces(line, format): @@ -506,12 +506,12 @@ def process_spaces(line, format): Function to process spaces in text lines for flowed and pre-formatted notes. line : text to process format : = 0 : Flowed, = 1 : Preformatted - + If the text is flowed (format==0), then leading spaces are removed, and multiple spaces are reduced to one. If the text is pre-formatted (format==1). then all spaces are preserved - - Note that xml is just treated like any other text, + + Note that xml is just treated like any other text, because it will be from the original note, and it is just printed, not interpreted. Returns the processed text, and the number of significant (i.e. non-white-space) chars. """ diff --git a/gramps/plugins/docgen/svgdrawdoc.py b/gramps/plugins/docgen/svgdrawdoc.py index a8bf77bda..eb0fe5ace 100644 --- a/gramps/plugins/docgen/svgdrawdoc.py +++ b/gramps/plugins/docgen/svgdrawdoc.py @@ -88,9 +88,9 @@ class SvgDrawDoc(BaseDoc, DrawDoc): raise ReportError(_("Could not create %s") % name, msg) except: raise ReportError(_("Could not create %s") % name) - + self.t = StringIO() - + width = self.paper.get_size().get_width() height = self.paper.get_size().get_height() @@ -121,8 +121,8 @@ class SvgDrawDoc(BaseDoc, DrawDoc): centerx, centery = units(( x+self.paper.get_left_margin(), y+self.paper.get_top_margin() )) - xpos = (centerx - (width/2.0)) - ypos = (centery - (height/2.0)) + xpos = (centerx - (width/2.0)) + ypos = (centery - (height/2.0)) self.t.write( '') - + for line in text: # Center this line relative to the rest of the text linex = xpos + (width - self.string_width(font, line) ) / 2 @@ -150,15 +150,15 @@ class SvgDrawDoc(BaseDoc, DrawDoc): '' ) self.t.write('\n') - + def end_page(self): - # Print the text last for each page so that it is rendered on top of + # Print the text last for each page so that it is rendered on top of # other graphic elements. self.f.write(self.t.getvalue()) self.t.close() self.f.write('\n') self.f.close() - + def draw_line(self, style, x1, y1, x2, y2): x1 += self.paper.get_left_margin() x2 += self.paper.get_left_margin() @@ -230,7 +230,7 @@ class SvgDrawDoc(BaseDoc, DrawDoc): if box_style.get_line_style() != SOLID: line_out += 'stroke-dasharray: %s; ' % ( ",".join(map(str, box_style.get_dash_style())) - ) + ) line_out += 'stroke-width:%f;"/>\n' % box_style.get_line_width() self.f.write(line_out) @@ -272,12 +272,12 @@ class SvgDrawDoc(BaseDoc, DrawDoc): """ @param mark: IndexMark to use for indexing (not supported) """ x += self.paper.get_left_margin() y += self.paper.get_top_margin() - + style_sheet = self.get_style_sheet() box_style = style_sheet.get_draw_style(style) para_name = box_style.get_paragraph_style() p = style_sheet.get_paragraph_style(para_name) - + font = p.get_font() font_size = font.get_size() fs = (font_size/28.35) * 1.2 @@ -328,7 +328,7 @@ class SvgDrawDocOptions(DocOptions): def __init__(self, name, dbase): DocOptions.__init__(self, name) - + def add_menu_options(self, menu): """ Add options to the document menu for the docgen. diff --git a/gramps/plugins/drawreport/ancestortree.py b/gramps/plugins/drawreport/ancestortree.py index ac796751a..9a06dfc58 100644 --- a/gramps/plugins/drawreport/ancestortree.py +++ b/gramps/plugins/drawreport/ancestortree.py @@ -280,7 +280,7 @@ class MakeAncestorTree(AscendPerson): first off of a forumula, then remove blank areas around the edges, then compress the tree if desired ''' - min_y = self.y_index(self.canvas.boxes[0].level[LVL_GEN], + min_y = self.y_index(self.canvas.boxes[0].level[LVL_GEN], self.canvas.boxes[0].level[LVL_INDX]) for box in self.canvas.boxes: if "fam" in box.boxstr: @@ -310,7 +310,7 @@ class MakeAncestorTree(AscendPerson): y_index = box.level[LVL_Y] if y_index > current_y: current_y = y_index - y_level += 1 + y_level += 1 box.level = box.level[:LVL_Y] + (y_level,) def do_sibs(self): @@ -334,7 +334,7 @@ class MakeAncestorTree(AscendPerson): for box in self.canvas.boxes: box.level = (box.level[0], box.level[1], box.level[2]-move) move = 0 - + line.start = [] r = -1 # if len(mykids)%2 == 1 else 0 diff --git a/gramps/plugins/drawreport/calendarreport.py b/gramps/plugins/drawreport/calendarreport.py index 0987bf45b..94d8c7245 100644 --- a/gramps/plugins/drawreport/calendarreport.py +++ b/gramps/plugins/drawreport/calendarreport.py @@ -36,14 +36,14 @@ import time from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gen.const import URL_HOMEPAGE -from gramps.gen.display.name import displayer as _nd +from gramps.gen.display.name import displayer as _nd from gramps.gen.errors import ReportError from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle, GraphicsStyle, FONT_SERIF, PARA_ALIGN_CENTER, PARA_ALIGN_LEFT, PARA_ALIGN_RIGHT, IndexMark, INDEX_TYPE_TOC) from gramps.gen.plug.docgen.fontscale import string_trim -from gramps.gen.plug.menu import (BooleanOption, StringOption, NumberOption, +from gramps.gen.plug.menu import (BooleanOption, StringOption, NumberOption, EnumeratedListOption, FilterOption, PersonOption) from gramps.gen.plug.report import Report @@ -93,7 +93,7 @@ class Calendar(Report): stdoptions.run_private_data_option(self, menu) get_value = lambda name: menu.get_option_by_name(name).get_value() - + self.year = get_value('year') self.name_format = get_value('name_format') self.country = get_value('country') @@ -115,8 +115,8 @@ class Calendar(Report): self._locale = self.set_locale(get_value('trans')) def get_name(self, person, maiden_name = None): - """ Return person's name, unless maiden_name given, - unless married_name listed. + """ Return person's name, unless maiden_name given, + unless married_name listed. """ # Get all of a person's names: primary_name = person.get_primary_name() @@ -139,7 +139,7 @@ class Calendar(Report): name = Name(primary_name) name.set_display_as(self.name_format) return _nd.display_name(name) - + def draw_rectangle(self, style, sx, sy, ex, ey): """ This should be in BaseDoc """ self.doc.draw_line(style, sx, sy, sx, ey) @@ -164,7 +164,7 @@ class Calendar(Report): holiday_table.load_holidays(self.year, country) for month in range(1, 13): for day in range(1, 32): - holiday_names = holiday_table.get_holidays(month, day) + holiday_names = holiday_table.get_holidays(month, day) for holiday_name in holiday_names: self.add_day_item(self._(holiday_name), month, day, "CAL-Holiday") @@ -187,15 +187,15 @@ class Calendar(Report): """ # initialize the dict to fill: self.calendar = {} - + # get the information, first from holidays: if self.country != 0: self.__get_holidays() - + # get data from database: self.collect_data() # generate the report: - with self._user.progress(_('Calendar Report'), + with self._user.progress(_('Calendar Report'), _('Formatting months...'), 12) as step: for month in range(1, 13): @@ -226,7 +226,7 @@ class Calendar(Report): self.doc.draw_box("CAL-Title", "", 0, 0, width, header, mark) self.doc.draw_line("CAL-Border", 0, header, width, header) year = self.year - # TRANSLATORS: see + # TRANSLATORS: see # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates # to learn how to select proper inflection for your language. title = self._("{long_month} {year}").format( @@ -250,10 +250,10 @@ class Calendar(Report): current_ord = current_date.toordinal() for day_col in range(7): font_height = pt2cm(pdaynames.get_font().get_size()) - self.doc.center_text("CAL-Daynames", + self.doc.center_text("CAL-Daynames", long_days[(day_col+ g2iso(self.start_dow + 1)) - % 7 + 1].capitalize(), - day_col * cell_width + cell_width/2, + % 7 + 1].capitalize(), + day_col * cell_width + cell_width/2, header - font_height * 1.5) for week_row in range(6): something_this_week = 0 @@ -261,13 +261,13 @@ class Calendar(Report): thisday = current_date.fromordinal(current_ord) if thisday.month == month: something_this_week = 1 - self.draw_rectangle("CAL-Border", day_col * cell_width, - header + week_row * cell_height, - (day_col + 1) * cell_width, + self.draw_rectangle("CAL-Border", day_col * cell_width, + header + week_row * cell_height, + (day_col + 1) * cell_width, header + (week_row + 1) * cell_height) last_edge = (day_col + 1) * cell_width - self.doc.center_text("CAL-Numbers", str(thisday.day), - day_col * cell_width + cell_width/2, + self.doc.center_text("CAL-Numbers", str(thisday.day), + day_col * cell_width + cell_width/2, header + week_row * cell_height) list_ = self.calendar.get(month, {}).get(thisday.day, []) list_.sort() # to get CAL-Holiday on bottom @@ -279,8 +279,8 @@ class Calendar(Report): break font = ptext.get_font() line = string_trim(font, line, cm2pt(cell_width + 0.2)) - self.doc.draw_text(format, line, - day_col * cell_width + 0.1, + self.doc.draw_text(format, line, + day_col * cell_width + 0.1, header + (week_row + 1) * cell_height - position - 0.1, m_list[0]) if len(m_list) > 1: # index the spouse too self.doc.draw_text(format, "",0,0, m_list[1]) @@ -294,14 +294,14 @@ class Calendar(Report): if text1 == _(_TITLE1): text1 = self._(_TITLE1) self.doc.center_text("CAL-Text1style", text1, - x, height - font_height * 3) + x, height - font_height * 3) text2 = str(self.text2) if text2 == _(_TITLE2): text2 = self._(_TITLE2) self.doc.center_text("CAL-Text2style", text2, - x, height - font_height * 2) + x, height - font_height * 2) self.doc.center_text("CAL-Text3style", self.text3, - x, height - font_height * 1) + x, height - font_height * 1) self.doc.end_page() def collect_data(self): @@ -311,14 +311,14 @@ class Calendar(Report): """ db = self.database people = db.iter_person_handles() - with self._user.progress(_('Calendar Report'), - _('Applying Filter...'), + with self._user.progress(_('Calendar Report'), + _('Applying Filter...'), db.get_number_of_people()) as step: people = self.filter.apply(self.database, people, step) ngettext = self._locale.translation.ngettext # to see "nearby" comments - with self._user.progress(_('Calendar Report'), + with self._user.progress(_('Calendar Report'), _('Reading database...'), len(people)) as step: for person_handle in people: @@ -375,7 +375,7 @@ class Calendar(Report): self.add_day_item(text, month, day, marks=[mark]) if self.anniversaries: family_list = person.get_family_handle_list() - for fhandle in family_list: + for fhandle in family_list: fam = db.get_family_from_handle(fhandle) father_handle = fam.get_father_handle() mother_handle = fam.get_mother_handle() @@ -397,15 +397,15 @@ class Calendar(Report): event = db.get_event_from_handle(event_ref.ref) et = EventType rt = EventRoleType - if event.type in [et.MARRIAGE, + if event.type in [et.MARRIAGE, et.MARR_ALT] and \ - (event_ref.get_role() == rt.FAMILY or + (event_ref.get_role() == rt.FAMILY or event_ref.get_role() == rt.PRIMARY ): are_married = event - elif event.type in [et.DIVORCE, - et.ANNULMENT, + elif event.type in [et.DIVORCE, + et.ANNULMENT, et.DIV_FILING] and \ - (event_ref.get_role() == rt.FAMILY or + (event_ref.get_role() == rt.FAMILY or event_ref.get_role() == rt.PRIMARY ): are_married = None if are_married is not None: @@ -421,7 +421,7 @@ class Calendar(Report): day = event_obj.get_day() prob_alive_date = Date(self.year, month, day) - + nyears = self.year - year if nyears == 0: text = self._('%(spouse)s and\n %(person)s, wedding') % { @@ -430,7 +430,7 @@ class Calendar(Report): } else: # translators: leave all/any {...} untranslated - text = ngettext("{spouse} and\n {person}, {nyears}", + text = ngettext("{spouse} and\n {person}, {nyears}", "{spouse} and\n {person}, {nyears}", nyears).format(spouse=spouse_name, person=short_name, nyears=nyears) @@ -456,7 +456,7 @@ class CalendarOptions(MenuReportOptions): self.__pid = None self.__filter = None MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add the options for the graphical calendar """ @@ -470,7 +470,7 @@ class CalendarOptions(MenuReportOptions): _("Select filter to restrict people that appear on calendar")) add_option("filter", self.__filter) self.__filter.connect('value-changed', self.__filter_changed) - + self.__pid = PersonOption(_("Center Person")) self.__pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", self.__pid) @@ -494,7 +494,7 @@ class CalendarOptions(MenuReportOptions): add_option = partial(menu.add_option, category_name) ########################## - year = NumberOption(_("Year of calendar"), time.localtime()[0], + year = NumberOption(_("Year of calendar"), time.localtime()[0], 1000, 3000) year.set_help(_("Year of calendar")) add_option("year", year) @@ -503,7 +503,7 @@ class CalendarOptions(MenuReportOptions): holiday_table = libholiday.HolidayTable() countries = holiday_table.get_countries() countries.sort() - if (len(countries) == 0 or + if (len(countries) == 0 or (len(countries) > 0 and countries[0] != '')): countries.insert(0, '') count = 0 @@ -517,9 +517,9 @@ class CalendarOptions(MenuReportOptions): long_days = date_displayer.long_days for count in range(1, 8): # conversion between gramps numbering (sun=1) and iso numbering (mon=1) of weekdays below - start_dow.add_item((count+5) % 7 + 1, long_days[count].capitalize()) + start_dow.add_item((count+5) % 7 + 1, long_days[count].capitalize()) start_dow.set_help(_("Select the first day of the week for the calendar")) - add_option("start_dow", start_dow) + add_option("start_dow", start_dow) maiden_name = EnumeratedListOption(_("Birthday surname"), "own") maiden_name.add_item("spouse_first", _("Wives use husband's surname (from first family listed)")) @@ -541,7 +541,7 @@ class CalendarOptions(MenuReportOptions): add_option = partial(menu.add_option, _("Text Options")) ########################## - text1 = StringOption(_("Text Area 1"), _(_TITLE1)) + text1 = StringOption(_("Text Area 1"), _(_TITLE1)) text1.set_help(_("First line of text at bottom of calendar")) add_option("text1", text1) @@ -552,7 +552,7 @@ class CalendarOptions(MenuReportOptions): text3 = StringOption(_("Text Area 3"), URL_HOMEPAGE) text3.set_help(_("Third line of text at bottom of calendar")) add_option("text3", text3) - + def __update_filters(self): """ Update the filter list based on the selected person @@ -578,9 +578,9 @@ class CalendarOptions(MenuReportOptions): # The rest don't self.__pid.set_available(False) - def make_my_style(self, default_style, name, description, - size=9, font=FONT_SERIF, justified ="left", - color=None, align=PARA_ALIGN_CENTER, + def make_my_style(self, default_style, name, description, + size=9, font=FONT_SERIF, justified ="left", + color=None, align=PARA_ALIGN_CENTER, shadow = None, italic=0, bold=0, borders=0, indent=None): """ Create paragraph and graphic styles of the same name """ # Paragraph: @@ -600,11 +600,11 @@ class CalendarOptions(MenuReportOptions): if indent: p.set(first_indent=indent) if justified == "left": - p.set_alignment(PARA_ALIGN_LEFT) + p.set_alignment(PARA_ALIGN_LEFT) elif justified == "right": - p.set_alignment(PARA_ALIGN_RIGHT) + p.set_alignment(PARA_ALIGN_RIGHT) elif justified == "center": - p.set_alignment(PARA_ALIGN_CENTER) + p.set_alignment(PARA_ALIGN_CENTER) default_style.add_paragraph_style(name, p) # Graphics: g = GraphicsStyle() @@ -616,30 +616,30 @@ class CalendarOptions(MenuReportOptions): if not borders: g.set_line_width(0) default_style.add_draw_style(name, g) - + def make_default_style(self, default_style): """ Add the styles used in this report """ - self.make_my_style(default_style, "CAL-Title", - _('Title text and background color'), 20, - bold=1, italic=1, + self.make_my_style(default_style, "CAL-Title", + _('Title text and background color'), 20, + bold=1, italic=1, color=(0xEA, 0xEA, 0xEA)) - self.make_my_style(default_style, "CAL-Numbers", - _('Calendar day numbers'), 13, + self.make_my_style(default_style, "CAL-Numbers", + _('Calendar day numbers'), 13, bold=1) - self.make_my_style(default_style, "CAL-Text", + self.make_my_style(default_style, "CAL-Text", _('Daily text display'), 9) - self.make_my_style(default_style, "CAL-Holiday", + self.make_my_style(default_style, "CAL-Holiday", _('Holiday text display'), 9, bold=1, italic=1) - self.make_my_style(default_style, "CAL-Daynames", - _('Days of the week text'), 12, - italic=1, bold=1, + self.make_my_style(default_style, "CAL-Daynames", + _('Days of the week text'), 12, + italic=1, bold=1, color = (0xEA, 0xEA, 0xEA)) - self.make_my_style(default_style, "CAL-Text1style", + self.make_my_style(default_style, "CAL-Text1style", _('Text at bottom, line 1'), 12) - self.make_my_style(default_style, "CAL-Text2style", + self.make_my_style(default_style, "CAL-Text2style", _('Text at bottom, line 2'), 12) - self.make_my_style(default_style, "CAL-Text3style", + self.make_my_style(default_style, "CAL-Text3style", _('Text at bottom, line 3'), 9) - self.make_my_style(default_style, "CAL-Border", + self.make_my_style(default_style, "CAL-Border", _('Borders'), borders=True) diff --git a/gramps/plugins/drawreport/descendtree.py b/gramps/plugins/drawreport/descendtree.py index 9c9c3b596..0f7463c5a 100644 --- a/gramps/plugins/drawreport/descendtree.py +++ b/gramps/plugins/drawreport/descendtree.py @@ -31,7 +31,7 @@ Reports/Graphical Reports/Personal Tree # # GRAMPS modules # -#------------------------------------------------------------------------ +#------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext from gramps.gen.errors import ReportError @@ -90,7 +90,7 @@ class PersonBox(DescendantBoxBase): def __init__(self, level, boldable = 0): DescendantBoxBase.__init__(self, "CG2-box") self.level = level - + def set_bold(self): """ update me to a bolded box """ self.boxstr = "CG2b-box" @@ -103,7 +103,7 @@ class FamilyBox(DescendantBoxBase): def __init__(self, level): DescendantBoxBase.__init__(self, "CG2-fam-box") self.level = level - + class PlaceHolderBox(BoxBase): """ I am a box that does not print. I am used to make sure information @@ -116,7 +116,7 @@ class PlaceHolderBox(BoxBase): self.level = level self.line_to = None self.linked_box = None - + def calc_text(self, database, person, family): """ move along. Nothing to see here """ return @@ -134,7 +134,7 @@ class DescendantTitleBase(TitleBox): TitleBox.__init__(self, doc, boxstr) self.database = dbase self._ = locale.translation.sgettext - + def descendant_print(self, person_list, person_list2 = []): """ calculate the Descendant title Person_list will always be passed @@ -184,26 +184,26 @@ class DescendantTitleBase(TitleBox): 'mother': names[1], } return title - + def get_parents(self, family_id): """ For a family_id, return the father and mother """ - + family1 = self.database.get_family_from_gramps_id(family_id) father_h = family1.get_father_handle() mother_h = family1.get_mother_handle() - + parents = [self.database.get_person_from_handle(handle) for handle in [father_h, mother_h] if handle] - + return parents class TitleNone(TitleNoDisplay): """No Title class for the report """ - + def __init__(self, dbase, doc, locale): TitleNoDisplay.__init__(self, doc, "CG2-Title") self._ = locale.translation.sgettext - + def calc_title(self, persons): """Calculate the title of the report""" #we want no text, but need a text for the TOC in a book! @@ -211,39 +211,39 @@ class TitleNone(TitleNoDisplay): self.text = '' class TitleDPY(DescendantTitleBase): - """Descendant (Person yes start with parents) Chart + """Descendant (Person yes start with parents) Chart Title class for the report """ - + def __init__(self, dbase, doc, locale, name_displayer): DescendantTitleBase.__init__(self, dbase, doc, locale, name_displayer) - + def calc_title(self, person_id): """Calculate the title of the report""" center = self.database.get_person_from_gramps_id(person_id) family2_h = center.get_main_parents_family_handle() family2 = self.database.get_family_from_handle(family2_h) - + person_list = None if family2: father2_h = family2.get_father_handle() mother2_h = family2.get_mother_handle() person_list = [self.database.get_person_from_handle(handle) - for handle in [father2_h, mother2_h] if handle] - + for handle in [father2_h, mother2_h] if handle] + if not person_list: person_list = [center] - + self.text = self.descendant_print(person_list) self.set_box_height_width() class TitleDPN(DescendantTitleBase): - """Descendant (Person no start with parents) Chart + """Descendant (Person no start with parents) Chart Title class for the report """ - + def __init__(self, dbase, doc, locale, name_displayer): DescendantTitleBase.__init__(self, dbase, doc, locale, name_displayer) - + def calc_title(self, person_id): """Calculate the title of the report""" @@ -254,17 +254,17 @@ class TitleDPN(DescendantTitleBase): self.set_box_height_width() class TitleDFY(DescendantTitleBase): - """Descendant (Family yes start with parents) Chart + """Descendant (Family yes start with parents) Chart Title class for the report """ - + def __init__(self, dbase, doc, locale, name_displayer): DescendantTitleBase.__init__(self, dbase, doc, locale, name_displayer) - + def get_parent_list(self, person): """ return a list of my parents. If none, return me """ if not person: return None - + parent_list = None family_h = person.get_main_parents_family_handle() family = self.database.get_family_from_handle(family_h) @@ -273,33 +273,33 @@ class TitleDFY(DescendantTitleBase): mother_h = family.get_mother_handle() parent_list = [self.database.get_person_from_handle(handle) for handle in [father_h, mother_h] if handle] - + return parent_list or [person] - + def calc_title(self, family_id): """Calculate the title of the report""" - + my_parents = self.get_parents(family_id) - + dad_parents = self.get_parent_list(my_parents[0]) - + mom_parents = [] if len(my_parents) > 1: if not dad_parents: dad_parents = self.get_parent_list(my_parents[1]) else: mom_parents = self.get_parent_list(my_parents[1]) - + self.text = self.descendant_print(dad_parents, mom_parents) self.set_box_height_width() class TitleDFN(DescendantTitleBase): """Descendant (Family no start with parents) Chart Title class for the report """ - + def __init__(self, dbase, doc, locale, name_displayer): DescendantTitleBase.__init__(self, dbase, doc, locale, name_displayer) - + def calc_title(self, family_id): """Calculate the title of the report""" @@ -312,7 +312,7 @@ class TitleF(DescendantTitleBase): def __init__(self, dbase, doc, locale, name_displayer): DescendantTitleBase.__init__(self, dbase, doc, locale, name_displayer) - + def calc_title(self, family_id): """Calculate the title of the report""" parents = self.get_parents(family_id) @@ -329,28 +329,28 @@ class TitleF(DescendantTitleBase): # title = str(tmp) + " " + str(len(tmp)) self.text = title self.set_box_height_width() - + class TitleC(DescendantTitleBase): """Cousin Chart Title class for the report """ def __init__(self, dbase, doc, locale, name_displayer): DescendantTitleBase.__init__(self, dbase, doc, locale, name_displayer) - + def calc_title(self, family_id): """Calculate the title of the report""" family = self.database.get_family_from_gramps_id(family_id) - + kids = [self.database.get_person_from_handle(kid.ref) for kid in family.get_child_ref_list()] #ok we have the children. Make a title off of them # translators: needed for Arabic, ignore otherwise cousin_names = self._(', ').join(self._get_names(kids, self._nd)) - + self.text = self._("Cousin Chart for %(names)s") % { 'names' : cousin_names} - + self.set_box_height_width() @@ -361,7 +361,7 @@ class TitleC(DescendantTitleBase): #------------------------------------------------------------------------ class RecurseDown: """ - The main recursive functions that will use add_person to make + The main recursive functions that will use add_person to make the tree of people (Descendants) to be included within the report. """ def __init__(self, dbase, canvas): @@ -371,7 +371,7 @@ class RecurseDown: self.families_seen = set() self.cols = [] self.__last_direct = [] - + gui = GuiConnect() self.do_parents = gui.get_val('show_parents') self.max_generations = gui.get_val('maxgen') @@ -380,7 +380,7 @@ class RecurseDown: if not self.max_spouses: self.inlc_marr = False self.spouse_indent = gui.get_val('ind_spouse') - + #is the option even available? self.bold_direct = gui.get_val('bolddirect') #can we bold direct descendants? @@ -390,7 +390,7 @@ class RecurseDown: #2 - Bold all direct descendants self.bold_now = 0 gui = None - + def add_to_col(self, box): """ Add the box to a column on the canvas. we will do these things: @@ -399,7 +399,7 @@ class RecurseDown: also we set the .x_cm to any s_level (indentation) here we will calculate the real .x_cm later (with indentation) """ - + level = box.level[0] #make the column list of people while len(self.cols) <= level: @@ -409,18 +409,18 @@ class RecurseDown: if self.cols[level]: #if (not the first box in this column) last_box = self.cols[level] last_box.linked_box = box - + #calculate the .y_cm for this box. box.y_cm = last_box.y_cm box.y_cm += last_box.height if last_box.boxstr in ["CG2-box", "CG2b-box"]: box.y_cm += self.canvas.report_opts.box_shadow - + if box.boxstr in ["CG2-box", "CG2b-box"]: box.y_cm += self.canvas.report_opts.box_pgap else: box.y_cm += self.canvas.report_opts.box_mgap - + if box.level[1] == 0 and self.__last_direct[level]: #ok, a new direct descendant. #print level, box.father is not None, self.__last_direct[level].father is not None, box.text[0], \ @@ -428,23 +428,23 @@ class RecurseDown: if box.father != self.__last_direct[level].father and \ box.father != self.__last_direct[level]: box.y_cm += self.canvas.report_opts.box_pgap - + self.cols[level] = box if box.level[1] == 0: self.__last_direct[level] = box - + if self.spouse_indent: box.x_cm = self.canvas.report_opts.spouse_offset * box.level[1] else: box.x_cm = 0.0 - + self.canvas.set_box_height_width(box) - + def add_person_box(self, level, indi_handle, fams_handle, father): """ Makes a person box and add that person into the Canvas. """ myself = PersonBox(level) myself.father = father - + if myself.level[1] == 0 and self.bold_direct and self.bold_now: if self.bold_now == 1: self.bold_now = 0 @@ -458,21 +458,21 @@ class RecurseDown: line = LineBase(father) father.line_to = line #self.canvas.add_line(line) - + line.end.append(myself) - + #calculate the text. myself.calc_text(self.database, indi_handle, fams_handle) - myself.add_mark(self.database, + myself.add_mark(self.database, self.database.get_person_from_handle(indi_handle)) self.add_to_col(myself) - + self.canvas.add_box(myself) return myself - + def add_marriage_box(self, level, indi_handle, fams_handle, father): """ Makes a marriage box and add that person into the Canvas. """ myself = FamilyBox(level) @@ -481,17 +481,17 @@ class RecurseDown: # myself.father = father #calculate the text. myself.calc_text(self.database, indi_handle, fams_handle) - + self.add_to_col(myself) self.canvas.add_box(myself) - + return myself - + def recurse(self, person_handle, x_level, s_level, father): - """traverse the ancestors recursively until - either the end of a line is found, - or until we reach the maximum number of generations + """traverse the ancestors recursively until + either the end of a line is found, + or until we reach the maximum number of generations or we reach the max number of spouses that we want to deal with""" @@ -531,7 +531,7 @@ class RecurseDown: if self.max_spouses > s_level and \ spouse_handle not in self.families_seen: def _spouse_box(who): - return self.add_person_box((x_level, s_level+1), + return self.add_person_box((x_level, s_level+1), spouse_handle, family_handle, who) if s_level > 0: spouse = _spouse_box(father) @@ -565,11 +565,11 @@ class RecurseDown: Adds a family into the canvas. only will be used for my direct grandparents, and my parents only. """ - + family_h = family.get_handle() father_h = family.get_father_handle() mother_h = family.get_mother_handle() - + self.bold_now = 2 if father_h: father_b = self.add_person_box( @@ -578,13 +578,13 @@ class RecurseDown: father_b = self.add_person_box( (level, 0), None, None, father2) retrn = [father_b] - + if self.inlc_marr: family_b = self.add_marriage_box( (level, 1), father_h, family_h, father_b) retrn.append(family_b) self.families_seen.add(family_h) - + if mother_h: mother_b = self.add_person_box( (level, 0), mother_h, family_h, father_b) @@ -592,13 +592,13 @@ class RecurseDown: mother_b = self.add_person_box( (level, 0), None, None, father_b) retrn.append(mother_b) - + family_line = family_b if self.inlc_marr else father_b for child_ref in family.get_child_ref_list(): self.recurse(child_ref.ref, level+1, 0, family_line) - + self.bold_now = 0 - + #Set up the lines for the family if not family_line.line_to: #no children. @@ -634,7 +634,7 @@ class RecurseDown: Quickly check to see if we want to continue recursion still we want to respect the FamiliesSeen list """ - + person = self.database.get_person_from_handle(person_handle) show = False @@ -645,7 +645,7 @@ class RecurseDown: #if the condition is true, we only want to show #this parent again IF s/he has other children show = self.has_children(person_handle) - + #if self.max_spouses == 0 and not self.has_children(person_handle): # self.families_seen.add(person_handle) # show = False @@ -669,26 +669,26 @@ class MakePersonTree(RecurseDown): def __init__(self, dbase, canvas): RecurseDown.__init__(self, dbase, canvas) self.max_generations -= 1 - + def start(self, person_id): """follow the steps to make a tree off of a person""" persons = [] - + center1 = self.database.get_person_from_gramps_id(person_id) if center1 is None: raise ReportError(_("Person %s is not in the Database") % person_id) center1_h = center1.get_handle() #could be mom too. - + family2 = family2_h = None - if self.do_parents: + if self.do_parents: family2_h = center1.get_main_parents_family_handle() family2 = self.database.get_family_from_handle(family2_h) - + mother2_h = father2_h = None if family2: father2_h = family2.get_father_handle() mother2_h = family2.get_mother_handle() - + ####################### #don't do center person's parents family. @@ -733,10 +733,10 @@ class MakeFamilyTree(RecurseDown): order of people inserted into Persons is important. makes sure that order is done correctly. """ - + def __init__(self, dbase, canvas): RecurseDown.__init__(self, dbase, canvas) - + def start(self, family_id): """follow the steps to make a tree off of a family""" ## (my) referes to the children of family_id @@ -745,7 +745,7 @@ class MakeFamilyTree(RecurseDown): family1 = self.database.get_family_from_gramps_id(family_id) if family1 is None: raise ReportError(_("Family %s is not in the Database") % family_id) - family1_h = family1.get_handle() + family1_h = family1.get_handle() ####################### #Initial setup of variables @@ -768,37 +768,37 @@ class MakeFamilyTree(RecurseDown): mother2 = self.database.get_person_from_handle(mother2_h) father2_h = family2.get_father_handle() father2 = self.database.get_person_from_handle(father2_h) - + #Helper variables. Assigned in one section, used in another. father2_id = family2_id = None mother1_id = None - + ####################### #don't do my fathers parents family. will be done later if family2_h: self.families_seen.add(family2_h) - + ####################### #my father mothers OTHER husbands ####################### #update to only run if she HAD other husbands! if mother2_h: self.recurse_if(mother2_h, 0) - + ####################### #father Fathers OTHER wives ####################### #update to only run if he HAD other wives! if father2_h: self.recurse_if(father2_h, 0) - + ####################### #don't do my parents family in recurse. will be done later self.families_seen.add(family1_h) ##If dad has no other children from other marriages. remove him if self.max_spouses == 0 and not self.has_children(father1_h): self.families_seen.add(father1_h) - + ####################### #my fathers parents! ####################### @@ -815,9 +815,9 @@ class MakeFamilyTree(RecurseDown): show = self.has_children(father1_h) if not show: self.families_seen.add(father1_h) - + family2_l = self.add_family( 0, family2, None ) - + elif father1: ####################### #my father other wives (if all of the above does nothing) @@ -825,8 +825,8 @@ class MakeFamilyTree(RecurseDown): ####################### #do his OTHER wives first. self.recurse_if(father1_h, 1) - - + + ####################### #my father, marriage info, mother, siblings, me ####################### @@ -838,7 +838,7 @@ class MakeFamilyTree(RecurseDown): family1_l = self.add_family(1, family1, family2_line) mother1_b = family1_l[-1] #Mom's Box - + #make sure there is at least one child in this family. #if not put in a placeholder family1_line = family1_l[1] if self.inlc_marr else family1_l[0] @@ -909,7 +909,7 @@ class MakeFamilyTree(RecurseDown): family2_line.end.insert(0, mother1_b) else: family2_line.end = [mother1_b] - + #fix me. Moms other siblings have been given an extra space #Because Moms-father is not siblings-father right now. @@ -972,17 +972,17 @@ class MakeReport(object): self.cols.append([]) self.cols[box.level[0]].append(box) - + #tmp = box.level[0] #if tmp > self.max_generations: # self.max_generations = tmp - + def __move_col_from_here_down(self, box, amount): """Move me and everyone below me in this column only down""" while box: box.y_cm += amount box = box.linked_box - + def __move_next_cols_from_here_down(self, box, amount): """Move me, everyone below me in this column, and all of our children (and childrens children) down.""" @@ -990,36 +990,36 @@ class MakeReport(object): while col: if len(col) == 1 and col[0].line_to: col.append(col[0].line_to.end[0]) - + col[0].y_cm += amount - + col[0] = col[0].linked_box if col[0] is None: col.pop(0) - + def __next_family_group(self, box): """ a helper function. Assume box is at the start of a family block. get this family block. """ while box: left_group = [] line = None - + #Form the parental (left) group. - #am I a direct descendant? + #am I a direct descendant? if box.level[1] == 0: - #I am the father/mother. + #I am the father/mother. left_group.append(box) if box.line_to: line = box.line_to box = box.linked_box - + if box and box.level[1] != 0 and self.inlc_marr: #add/start with the marriage box left_group.append(box) if box.line_to: line = box.line_to box = box.linked_box - + if box and box.level[1] != 0 and self.max_spouses > 0: #add/start with the spousal box left_group.append(box) @@ -1037,9 +1037,9 @@ class MakeReport(object): return left_group, line.end #else # no children, so no family. go again until we find one to return. - + return None, None - + def __reverse_family_group(self): """ go through the n-1 to 0 cols of boxes looking for families (parents with children) that may need to be moved. """ @@ -1052,30 +1052,30 @@ class MakeReport(object): else: yield left_group, right_group box = left_group[-1].linked_box - + def __calc_movements(self, left_group, right_group): """ for a family group, see if parents or children need to be moved down so everyone is to the right/left of each other. - + return a right y_cm and a left y_cm. these points will be used to move parents/children down. """ left_up = left_group[0].y_cm right_up = right_group[0].y_cm - + left_center = left_up right_center = right_up - + if self.compress_tree: #calculate a new left and right move points for left_line in left_group: if left_line.line_to: break left_center = left_line.y_cm + (left_line.height /2) - + left_down = left_group[-1].y_cm + left_group[-1].height right_down = right_group[-1].y_cm + right_group[-1].height - + #Lazy. Move down either side only as much as we NEED to. if left_center < right_up: right_center = right_group[0].y_cm @@ -1085,23 +1085,23 @@ class MakeReport(object): right_center = right_down else: right_center = left_center - + return right_center, left_center def Make_report(self): """ Everyone on the page is as far up as they can go. Move them down to where they belong. - + We are going to go through everyone from right to left top to bottom moving everyone down as needed to make the report. """ seen_parents = False - + for left_group, right_group in self.__reverse_family_group(): right_y_cm, left_y_cm = self.__calc_movements(left_group, right_group) - + #1. Are my children too high? if so move then down! if right_y_cm < left_y_cm: #we have to push our kids (and their kids) down. @@ -1109,21 +1109,21 @@ class MakeReport(object): #these kids (in their column) amt = (left_y_cm - right_y_cm) self.__move_next_cols_from_here_down(right_group[0], amt) - + #2. Am I (and spouses) too high? if so move us down! elif left_y_cm < right_y_cm: #Ok, I am too high. Move me down amt = (right_y_cm - left_y_cm) self.__move_col_from_here_down(left_group[0], amt) - + #6. now check to see if we are working with dad and mom. #if so we need to move down marriage information - #and mom! + #and mom! left_line = left_group[0].line_to if not left_line: left_line = left_group[1].line_to #left_line = left_line.start - + if len(left_line.start) > 1 and not seen_parents: #only do Dad and Mom. len(left_line) > 1 seen_parents = True @@ -1132,7 +1132,7 @@ class MakeReport(object): last_child_cm = right_group[-1].y_cm if not self.compress_tree: last_child_cm += right_group[-1].height/2 - move_amt = last_child_cm - mom_cm + move_amt = last_child_cm - mom_cm #if the moms height is less than the last childs height #The 0.2 is to see if this is even worth it. @@ -1140,14 +1140,14 @@ class MakeReport(object): #our children take up more space than us parents. #so space mom out! self.__move_col_from_here_down(left_group[-1], move_amt) - + #move marriage info if self.inlc_marr: left_group[1].y_cm += move_amt/2 if left_line.end[0].boxstr == 'None': left_line.end = [] - + def start(self): """Make the report""" #for person in self.persons.depth_first_gen(): @@ -1164,7 +1164,7 @@ class MakeReport(object): self.cols.pop(0) for box in self.canvas.boxes: box.level = (box.level[0] - 1, box.level[1]) - + #go ahead and set it now. width = self.canvas.report_opts.max_box_width for box in self.canvas.boxes: @@ -1173,7 +1173,7 @@ class MakeReport(object): box.x_cm += (box.level[0] * (self.canvas.report_opts.col_width + self.canvas.report_opts.max_box_width)) - + box.y_cm += self.canvas.report_opts.littleoffset box.y_cm += self.canvas.title.height @@ -1185,7 +1185,7 @@ class GuiConnect(): This give some common routines that EVERYONE can use like get the value from a GUI variable """ - + __shared_state = {} def __init__(self): #We are BORG! self.__dict__ = self.__shared_state @@ -1195,20 +1195,20 @@ class GuiConnect(): self._which_report = which.split(",")[0] self._locale = locale self._nd = name_displayer - + def get_val(self, val): """ Get a GUI value. """ value = self._opts.get_option_by_name(val) if value: - return value.get_value() + return value.get_value() else: False - + def Title_class(self, database, doc): Title_type = self.get_val('report_title') if Title_type == 0: #None return TitleNone(database, doc, self._locale) - + if Title_type == 1: #Descendant Chart if self._which_report == _RPT_NAME: if self.get_val('show_parents'): @@ -1220,18 +1220,18 @@ class GuiConnect(): return TitleDFY(database, doc, self._locale, self._nd) else: return TitleDFN(database, doc, self._locale, self._nd) - + if Title_type == 2: return TitleF(database, doc, self._locale, self._nd) else: #Title_type == 3 return TitleC(database, doc, self._locale, self._nd) - + def Make_Tree(self, database, canvas): if self._which_report == _RPT_NAME: return MakePersonTree(database, canvas) else: return MakeFamilyTree(database, canvas) - + def calc_lines(self, database): #calculate the printed lines for each box display_repl = self.get_val("replace_list") @@ -1239,7 +1239,7 @@ class GuiConnect(): #if self.get_val('miss_val'): # str = "_____" return CalcLines(database, display_repl, self._locale, self._nd) - + def working_lines(self, box): display = self.get_val("descend_disp") #if self.get_val('diffspouse'): @@ -1247,7 +1247,7 @@ class GuiConnect(): #else: # display_spou = display display_marr = [self.get_val("marr_disp")] - + if box.boxstr == "CG2-fam-box": #((((( workinglines = display_marr elif box.level[1] > 0 or (box.level[0] == 0 and box.father): @@ -1278,7 +1278,7 @@ class DescendTree(Report): Report.__init__(self, database, options, user) self.options = options - + stdoptions.run_private_data_option(self, options.menu) lang = options.menu.get_option_by_name('trans').get_value() @@ -1296,12 +1296,12 @@ class DescendTree(Report): self.Connect = GuiConnect() self.Connect.set__opts(self.options.menu, self.options.name, self._locale, self._nd) - + style_sheet = self.doc.get_style_sheet() font_normal = style_sheet.get_paragraph_style("CG2-Normal").get_font() #The canvas that we will put our report on and print off of - self.canvas = Canvas(self.doc, + self.canvas = Canvas(self.doc, ReportOptions(self.doc, font_normal, "CG2-line")) self.canvas.report_opts.box_shadow *= \ @@ -1309,13 +1309,13 @@ class DescendTree(Report): self.canvas.report_opts.box_pgap *= self.Connect.get_val('box_Yscale') self.canvas.report_opts.box_mgap *= self.Connect.get_val('box_Yscale') - center_id = self.Connect.get_val('pid') + center_id = self.Connect.get_val('pid') #make the tree tree = self.Connect.Make_Tree(database, self.canvas) tree.start(center_id) tree = None - + #Title title = self.Connect.Title_class(database, self.doc) title.calc_title(center_id) @@ -1327,7 +1327,7 @@ class DescendTree(Report): report = MakeReport(database, self.canvas, ind_spouse, compress_tree) report.start() report = None - + #note? if self.Connect.get_val("inc_note"): note_box = NoteBox(self.doc, "CG2-note-box", @@ -1342,17 +1342,17 @@ class DescendTree(Report): #Do we want to scale the report? one_page = self.Connect.get_val("resize_page") scale_report = self.Connect.get_val("scale_tree") - + scale = self.canvas.scale_report(one_page, scale_report != 0, scale_report == 2) - + if scale != 1 or self.Connect.get_val('shadowscale') != 1.0: self.scale_styles(scale) def write_report(self): """ Canvas now has everyone ready to print. Get some misc stuff together and print. """ - + one_page = self.Connect.get_val("resize_page") scale_report = self.Connect.get_val("scale_tree") @@ -1372,19 +1372,19 @@ class DescendTree(Report): tmp += self.canvas.report_opts.col_width colsperpage = int(colsperpage / tmp) colsperpage = colsperpage or 1 - + ##################### #Vars #p = self.doc.get_style_sheet().get_paragraph_style("CG2-Normal") #font = p.get_font() if prnnum: page_num_box = PageNumberBox(self.doc, 'CG2-box', self._locale) - + ##################### #ok, everyone is now ready to print on the canvas. Paginate? self.canvas.sort_boxes_on_y_cm() self.canvas.paginate(colsperpage, one_page) - + ##################### #Yeah!!! #lets finally make some pages!!! @@ -1392,17 +1392,17 @@ class DescendTree(Report): for page in self.canvas.page_iter_gen(incblank): self.doc.start_page() - + #do we need to print a border? if inc_border: page.draw_border('CG2-line') - + #Do we need to print the page number? if prnnum: page_num_box.display(page) page.display() - + self.doc.end_page() @@ -1485,7 +1485,7 @@ class DescendTreeOptions(MenuReportOptions): self.box_Y_sf = None self.box_shadow_sf = None MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the descendant report. @@ -1571,7 +1571,7 @@ class DescendTreeOptions(MenuReportOptions): _("Whether to include a separate marital box in the report")) menu.add_option(category_name, "inc_marr", incmarr) - marrdisp = StringOption(_("Marriage\nDisplay Format"), "%s $m" % _MARR) + marrdisp = StringOption(_("Marriage\nDisplay Format"), "%s $m" % _MARR) marrdisp.set_help(_("Display format for the marital box.")) menu.add_option(category_name, "marr_disp", marrdisp) @@ -1601,7 +1601,7 @@ class DescendTreeOptions(MenuReportOptions): self.__onepage = BooleanOption(_("Resize Page to Fit Tree size\n" "\n" "Note: Overrides options in the 'Paper Option' tab" - ), + ), False) self.__onepage.set_help( _("Whether to resize the page to fit the size \n" @@ -1623,18 +1623,18 @@ class DescendTreeOptions(MenuReportOptions): self.__onepage.connect('value-changed', self.__check_blank) else: self.__onepage = None - + self.box_Y_sf = NumberOption(_("inter-box Y scale factor"), 1.00, 0.10, 2.00, 0.01) self.box_Y_sf.set_help(_("Make the inter-box Y bigger or smaller")) menu.add_option(category_name, "box_Yscale", self.box_Y_sf) - + self.box_shadow_sf = NumberOption(_("box shadow scale factor"), 1.00, 0.00, 2.00, 0.01) # down to 0 self.box_shadow_sf.set_help(_("Make the box shadow bigger or smaller")) menu.add_option(category_name, "shadowscale", self.box_shadow_sf) - - + + ################## category_name = _("Include") @@ -1662,7 +1662,7 @@ class DescendTreeOptions(MenuReportOptions): self.__blank = BooleanOption(_('Include Blank Pages'), True) self.__blank.set_help(_("Whether to include pages that are blank.")) menu.add_option(category_name, "inc_blank", self.__blank) - + #category_name = _("Notes") self.usenote = BooleanOption(_('Include a note'), False) @@ -1691,7 +1691,7 @@ class DescendTreeOptions(MenuReportOptions): value = True off = value and (self.scale.get_value() != 2) self.__blank.set_available( off ) - + def __Title_enum(self): item_list = [ [0, _("Do not include a title") ], diff --git a/gramps/plugins/drawreport/drawplugins.gpr.py b/gramps/plugins/drawreport/drawplugins.gpr.py index ca43ad8b5..2d84cdfdc 100644 --- a/gramps/plugins/drawreport/drawplugins.gpr.py +++ b/gramps/plugins/drawreport/drawplugins.gpr.py @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # diff --git a/gramps/plugins/drawreport/fanchart.py b/gramps/plugins/drawreport/fanchart.py index b077773fc..3449e7570 100644 --- a/gramps/plugins/drawreport/fanchart.py +++ b/gramps/plugins/drawreport/fanchart.py @@ -72,7 +72,7 @@ BACKGROUND_GEN = 1 RADIAL_UPRIGHT = 0 RADIAL_ROUNDABOUT = 1 -# minor offset just usefull for generation 11, +# minor offset just usefull for generation 11, # to not a bit offset between the text and the polygon # this can be considered as a bad hack WEDGE_TEXT_BARRE_OFFSET = 0.0016 @@ -85,7 +85,7 @@ cal = config.get('preferences.calendar-format-report') # private functions # #------------------------------------------------------------------------ -def draw_wedge(doc, style, centerx, centery, radius, start_angle, +def draw_wedge(doc, style, centerx, centery, radius, start_angle, end_angle, do_rendering, short_radius=0): """ Draw a wedge shape. @@ -94,7 +94,7 @@ def draw_wedge(doc, style, centerx, centery, radius, start_angle, end_angle += 360 p = [] - + degreestoradians = pi / 180.0 radiansdelta = degreestoradians / 2 sangle = start_angle * degreestoradians @@ -110,7 +110,7 @@ def draw_wedge(doc, style, centerx, centery, radius, start_angle, origx = (centerx + cos(angle) * short_radius) origy = (centery + sin(angle) * short_radius) p.append((origx, origy)) - + while angle < eangle: x = centerx + cos(angle) * radius y = centery + sin(angle) * radius @@ -137,7 +137,7 @@ def draw_wedge(doc, style, centerx, centery, radius, start_angle, delta = (eangle - sangle) / 2.0 rad = short_radius + (radius - short_radius) / 2.0 - return ( (centerx + cos(sangle + delta + WEDGE_TEXT_BARRE_OFFSET) * rad), + return ( (centerx + cos(sangle + delta + WEDGE_TEXT_BARRE_OFFSET) * rad), (centery + sin(sangle + delta + WEDGE_TEXT_BARRE_OFFSET) * rad)) #------------------------------------------------------------------------ @@ -150,7 +150,7 @@ class FanChart(Report): def __init__(self, database, options, user): """ Create the FanChart object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -159,7 +159,7 @@ class FanChart(Report): This report needs the following parameters (class variables) that come in the options class. - + maxgen - Maximum number of generations to include. circle - Draw a full circle, half circle, or quarter circle. background - Background color is generation dependent or white. @@ -191,7 +191,7 @@ class FanChart(Report): for i in range (0, self.max_generations): self.graphic_style.append('FC-Graphic' + '%02d' % i) self.text_style.append('FC-Text' + '%02d' % i) - + self.calendar = 0 self.height = 0 @@ -202,9 +202,9 @@ class FanChart(Report): def apply_filter(self,person_handle,index): """traverse the ancestors recursively until either the end - of a line is found, or until we reach the maximum number of + of a line is found, or until we reach the maximum number of generations that we want to deal with""" - + if (not person_handle) or (index >= 2**self.max_generations): return self.map[index-1] = person_handle @@ -219,7 +219,7 @@ class FanChart(Report): def write_report(self): self.doc.start_page() - + self.apply_filter(self.center_person.get_handle(),1) n = self.center_person.get_primary_name().get_regular_name() @@ -378,7 +378,7 @@ class FanChart(Report): return [ name, val ] else: return [ pn.get_first_name(), pn.get_surname(), val ] - + def get_max_width_for_circles(self, rad1, rad2, max_centering_proportion): """ __ @@ -388,14 +388,14 @@ class FanChart(Report): | | \ / \__/ - basically, max_centering_proportion is + basically, max_centering_proportion is max_centering_proportion/nb_lines """ # radius at the center of the 2 circles rmid = rad2 - (rad2-rad1)*max_centering_proportion return sin(acos(rmid/rad2)) * rad2 * 2 - - def get_max_width_for_circles_line(self, rad1, rad2, line, nb_lines, + + def get_max_width_for_circles_line(self, rad1, rad2, line, nb_lines, centering = False): """ __ @@ -409,10 +409,10 @@ class FanChart(Report): if centering: return self.get_max_width_for_circles(rad1, rad2, 1.0) else: - return self.get_max_width_for_circles(rad1, rad2, + return self.get_max_width_for_circles(rad1, rad2, line/float(nb_lines+1)) - def get_optimized_font_size_for_text(self, rad1, rad2, text, font, + def get_optimized_font_size_for_text(self, rad1, rad2, text, font, centering = False): """ a text can be several lines @@ -426,7 +426,7 @@ class FanChart(Report): nb_lines = len(text) for line in text: font_size = self.get_optimized_font_size(line, font, - self.get_max_width_for_circles_line(rad1, rad2, i, nb_lines, + self.get_max_width_for_circles_line(rad1, rad2, i, nb_lines, centering)) i += 1 if min_font_size > font_size: @@ -450,7 +450,7 @@ class FanChart(Report): map_paragraphs_colors_to_graphics, make_background_white): """ - returns an optimized (modified) style sheet which make fanchart + returns an optimized (modified) style sheet which make fanchart look nicer """ redefined_style_sheet = self.doc.get_style_sheet() @@ -465,12 +465,12 @@ class FanChart(Report): if title_font: title_width = pt2cm(self.doc.string_multiline_width(title_font, title)) - while (title_width > self.doc.get_usable_width() and + while (title_width > self.doc.get_usable_width() and title_font.get_size() > 1): title_font.set_size(title_font.get_size()-1) title_width = pt2cm(self.doc.string_multiline_width( title_font, title)) - redefined_style_sheet.add_paragraph_style(pstyle_name, + redefined_style_sheet.add_paragraph_style(pstyle_name, paragraph_style) # biggest font allowed is the one of the fist generation, after, @@ -481,12 +481,12 @@ class FanChart(Report): font = paragraph_style.get_font() if font: previous_generation_font_size = font.get_size() - + for generation in range (0, self.max_generations): gstyle_name = self.graphic_style[generation] pstyle_name = self.text_style [generation] g = redefined_style_sheet.get_draw_style(gstyle_name) - + # paragraph_style is a copy of 'FC-Text' - use different style # to be able to auto change some fonts for some generations if map_style_from_single: @@ -505,12 +505,12 @@ class FanChart(Report): if pstyle: g.set_fill_color(pstyle.get_background_color()) redefined_style_sheet.add_draw_style(gstyle_name, g) - + # adapt font size if too big segments = 2**generation if generation < min (max_circular, self.max_generations): # adpatation for circular fonts - rad1, rad2 = self.get_circular_radius(block_size, + rad1, rad2 = self.get_circular_radius(block_size, generation, self.circle) font = paragraph_style.get_font() if font: @@ -522,16 +522,16 @@ class FanChart(Report): self.get_optimized_font_size_for_text( rad1, rad2, self.text[index], paragraph_style.get_font(), - (self.circle == FULL_CIRCLE and + (self.circle == FULL_CIRCLE and generation == 0) ) if font_size < min_font_size: min_font_size = font_size - font.set_size(min(previous_generation_font_size, + font.set_size(min(previous_generation_font_size, min_font_size)) else: # adaptation for radial fonts - + # find the largest string for the generation longest_line = "" longest_width = 0 @@ -543,12 +543,12 @@ class FanChart(Report): if width > longest_width: longest_line = line longest_width = width - + # determine maximum width allowed for this generation - rad1, rad2 = self.get_radial_radius(block_size, + rad1, rad2 = self.get_radial_radius(block_size, generation, self.circle) max_width = rad2 - rad1 - + # reduce the font so that longest_width fit into max_width font = paragraph_style.get_font() if font: @@ -590,7 +590,7 @@ class FanChart(Report): self.doc.rotate_text(graphic_style, self.text[index], xc, yc, text_angle, mark) text_angle += delta - + def get_radial_radius(self, size, generation, circle): if circle == FULL_CIRCLE: rad1 = size * ((generation * 2) - 5) @@ -601,7 +601,7 @@ class FanChart(Report): else: # quarter circle rad1 = size * ((generation * 2) - 2) rad2 = size * (generation * 2) - return rad1, rad2 + return rad1, rad2 def get_circular_radius(self, size, generation, circle): return size * generation, size * (generation + 1) @@ -633,33 +633,33 @@ class FanChart(Report): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class FanChartOptions(MenuReportOptions): def __init__(self, name, dbase): self.MAX_GENERATIONS = 11 - + MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the fan chart. """ category_name = _("Report Options") - + pid = PersonOption(_("Center Person")) pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", pid) - + stdoptions.add_private_data_option(menu, category_name) max_gen = NumberOption(_("Generations"), 5, 1, self.MAX_GENERATIONS) max_gen.set_help(_("The number of generations " "to include in the report")) menu.add_option(category_name, "maxgen", max_gen) - + circle = EnumeratedListOption(_('Type of graph'), HALF_CIRCLE) circle.add_item(FULL_CIRCLE, _('full circle')) circle.add_item(HALF_CIRCLE, _('half circle')) @@ -667,14 +667,14 @@ class FanChartOptions(MenuReportOptions): circle.set_help( _("The form of the graph: full circle, half circle," " or quarter circle.")) menu.add_option(category_name, "circle", circle) - + background = EnumeratedListOption(_('Background color'), BACKGROUND_GEN) background.add_item(BACKGROUND_WHITE, _('white')) background.add_item(BACKGROUND_GEN, _('generation dependent')) background.set_help(_("Background color is either white or generation" " dependent")) menu.add_option(category_name, "background", background) - + radial = EnumeratedListOption( _('Orientation of radial texts'), RADIAL_UPRIGHT ) radial.add_item(RADIAL_UPRIGHT, _('upright')) @@ -697,17 +697,17 @@ class FanChartOptions(MenuReportOptions): def make_default_style(self,default_style): """Make the default output style for the Fan Chart report.""" BACKGROUND_COLORS = [ - (255, 63, 0), - (255,175, 15), - (255,223, 87), + (255, 63, 0), + (255,175, 15), + (255,223, 87), (255,255,111), - (159,255,159), - (111,215,255), - ( 79,151,255), + (159,255,159), + (111,215,255), + ( 79,151,255), (231, 23,255), (231, 23,221), (210,170,124), - (189,153,112) + (189,153,112) ] #Paragraph Styles @@ -739,7 +739,7 @@ class FanChartOptions(MenuReportOptions): p.set_alignment(PARA_ALIGN_CENTER) p.set_description(_('The style used for the text display of generation "%d"') % i) default_style.add_paragraph_style("FC-Text" + "%02d" % i, p) - + # GraphicsStyles g = GraphicsStyle() g.set_paragraph_style('FC-Title') diff --git a/gramps/plugins/drawreport/statisticschart.py b/gramps/plugins/drawreport/statisticschart.py index 81d8bc86a..ab965484c 100644 --- a/gramps/plugins/drawreport/statisticschart.py +++ b/gramps/plugins/drawreport/statisticschart.py @@ -65,15 +65,15 @@ from gramps.gen.display.place import displayer as place_displayer # Private Functions # #------------------------------------------------------------------------ -def draw_wedge(doc, style, centerx, centery, radius, start_angle, +def draw_wedge(doc, style, centerx, centery, radius, start_angle, end_angle, short_radius=0): from math import pi, cos, sin - + while end_angle < start_angle: end_angle += 360 p = [] - + degreestoradians = pi / 180.0 radiansdelta = degreestoradians / 2 sangle = start_angle * degreestoradians @@ -89,7 +89,7 @@ def draw_wedge(doc, style, centerx, centery, radius, start_angle, origx = (centerx + cos(angle) * short_radius) origy = (centery + sin(angle) * short_radius) p.append((origx, origy)) - + while angle < eangle: x = centerx + cos(angle) * radius y = centery + sin(angle) * radius @@ -115,7 +115,7 @@ def draw_wedge(doc, style, centerx, centery, radius, start_angle, delta = (eangle - sangle) / 2.0 rad = short_radius + (radius - short_radius) / 2.0 - return ( (centerx + cos(sangle + delta) * rad), + return ( (centerx + cos(sangle + delta) * rad), (centery + sin(sangle + delta) * rad)) @@ -172,7 +172,7 @@ def draw_legend(doc, start_x, start_y, data, title, label_style): @type start_y: float @param data: List of tuples containing the data to be used to create the legend. In order to be compatible with the graph plots, the first and - third values of the tuple used. The format is (graphics_format, value, + third values of the tuple used. The format is (graphics_format, value, legend_description). @type data: list """ @@ -184,7 +184,7 @@ def draw_legend(doc, start_x, start_y, data, title, label_style): size = ReportUtils.pt2cm(pstyle.get_font().get_size()) doc.draw_text(label_style, title, start_x + (3*size), start_y - (size*0.25)) start_y += size * 1.3 - + for (format, size, legend) in data: gstyle = style_sheet.get_draw_style(format) pstyle_name = gstyle.get_paragraph_style() @@ -203,7 +203,7 @@ def estimate_age(db, person, end_handle=None, start_handle=None, today=_TODAY): dates of the person. A tuple containing the estimated upper and lower bounds of the person's age is returned. If either the birth or death date is missing, a (-1, -1) is returned. - + @param db: GRAMPS database to which the Person object belongs @type db: DbBase @param person: Person object to calculate the age of @@ -373,7 +373,7 @@ class Extract(object): return [title] else: return [_T_("(Preferred) title missing")] - + def get_forename(self, person): "return forenames for given person" # TODO: return all forenames, not just primary ones... @@ -382,7 +382,7 @@ class Extract(object): return firstnames.split() else: return [_T_("(Preferred) forename missing")] - + def get_surname(self, person): "return surnames for given person" # TODO: return all surnames, not just primary ones... @@ -392,7 +392,7 @@ class Extract(object): return surnames.split() else: return [_T_("(Preferred) surname missing")] - + def get_gender(self, person): "return gender for given person" # TODO: why there's no Person.getGenderName? @@ -411,7 +411,7 @@ class Extract(object): if year: return [str(year)] return [_T_("Date(s) missing")] - + def get_month(self, event): "return month for given event" date = event.get_date_object() @@ -444,7 +444,7 @@ class Extract(object): else: places.append(_T_("Place missing")) return places - + def get_person_age(self, person): "return age for given person, if alive" death_ref = person.get_death_ref() @@ -500,7 +500,7 @@ class Extract(object): return ["%3d" % len(data[1])] # ------------------- utility methods ------------------------- - + def get_sorted_child_ages(self, data): "return (sorted_ages,errors) for given (person,child_handles)" ages = [] @@ -544,14 +544,14 @@ class Extract(object): if birth_ref: return self.db.get_event_from_handle(birth_ref.ref) return None - + def get_death(self, person): "return death event for given person or None" death_ref = person.get_death_ref() if death_ref: return self.db.get_event_from_handle(death_ref.ref) return None - + def get_child_handles(self, person): "return list of child handles for given person or None" children = [] @@ -576,7 +576,7 @@ class Extract(object): for event_ref in family.get_event_ref_list(): event = self.db.get_event_from_handle(event_ref.ref) if event.get_type() == EventType.MARRIAGE and \ - (event_ref.get_role() == EventRoleType.FAMILY or + (event_ref.get_role() == EventRoleType.FAMILY or event_ref.get_role() == EventRoleType.PRIMARY ): marriages.append(event_ref.ref) if marriages: @@ -621,7 +621,7 @@ class Extract(object): else: chart[1][key] = 1 - + def collect_data(self, db, filter_func, menu, genders, year_from, year_to, no_years, cb_progress, rlocale): """goes through the database and collects the selected personal @@ -636,7 +636,7 @@ class Extract(object): no_years - use also people without known birth year cb_progress - callback to indicate progress rlocale - a GrampsLocale instance - + Returns an array of tuple of: - Extraction method title - Dict of values with their counts @@ -655,7 +655,7 @@ class Extract(object): if option.get_value() == True: # localized data title, value dict, type and data method data.append((ext[name][1], {}, ext[name][2], ext[name][3])) - + # go through the people and collect data for person_handle in filter_func.apply(db, db.iter_person_handles(), cb_progress): cb_progress() @@ -663,7 +663,7 @@ class Extract(object): # check whether person has suitable gender if person.gender != genders and genders != Person.UNKNOWN: continue - + # check whether birth year is within required range birth = self.get_birth(person) if birth: @@ -766,17 +766,17 @@ class StatisticsChart(Report): "%(year_from)04d-%(year_to)04d") % mapping # extract requested items from the database and count them - self._user.begin_progress(_('Statistics Charts'), - _('Collecting data...'), + self._user.begin_progress(_('Statistics Charts'), + _('Collecting data...'), database.get_number_of_people()) tables = _Extract.collect_data(self.database, self.filter, menu, - gender, year_from, year_to, + gender, year_from, year_to, get_value('no_years'), self._user.step_progress, rlocale) self._user.end_progress() - self._user.begin_progress(_('Statistics Charts'), + self._user.begin_progress(_('Statistics Charts'), _('Sorting data...'), len(tables)) self.data = [] sortby = get_value('sortby') @@ -801,9 +801,9 @@ class StatisticsChart(Report): if sort == _options.SORT_VALUE: # set for the sorting function self.lookup_items = data - + # then sort by value - index.sort(key=lambda x: self.lookup_items[x], + index.sort(key=lambda x: self.lookup_items[x], reverse=True if reverse else False) return index @@ -812,7 +812,7 @@ class StatisticsChart(Report): "output the selected statistics..." mark = IndexMark(self._('Statistics Charts'), INDEX_TYPE_TOC, 1) - self._user.begin_progress(_('Statistics Charts'), + self._user.begin_progress(_('Statistics Charts'), _('Saving charts...'), len(self.data)) for data in sorted(self.data): self.doc.start_page() @@ -834,7 +834,7 @@ class StatisticsChart(Report): middle_w = self.doc.get_usable_width() / 2 middle_h = self.doc.get_usable_height() / 2 middle = min(middle_w,middle_h) - + # start output style_sheet = self.doc.get_style_sheet() pstyle = style_sheet.get_paragraph_style('SC-Title') @@ -842,7 +842,7 @@ class StatisticsChart(Report): self.doc.center_text('SC-title', title1, middle_w, 0, mark) yoffset = ReportUtils.pt2cm(pstyle.get_font().get_size()) self.doc.center_text('SC-title', title2, middle_w, yoffset) - + # collect data for output color = 0 chart_data = [] @@ -852,10 +852,10 @@ class StatisticsChart(Report): # graphics style, value, and it's label chart_data.append((style, data[key], text)) color = (color+1) % 7 # There are only 7 color styles defined - + margin = 1.0 legendx = 2.0 - + # output data... radius = middle - 2*margin yoffset += margin + radius @@ -864,7 +864,7 @@ class StatisticsChart(Report): if middle == middle_h: # Landscape legendx = 1.0 yoffset = margin - + text = self._("%s (persons):") % self._(typename) draw_legend(self.doc, legendx, yoffset, chart_data, text,'SC-legend') @@ -881,7 +881,7 @@ class StatisticsChart(Report): row_h = pt2cm(font.get_size()) max_y = self.doc.get_usable_height() - row_h pad = row_h * 0.5 - + # check maximum value max_value = max(data[k] for k in lookup) if lookup else 0 # horizontal area for the gfx bars @@ -919,7 +919,7 @@ class StatisticsChart(Report): # text after bar text = "%s (%d)" % (self._(key), data[key]) self.doc.draw_text('SC-text', text, textx, yoffset) - + return #------------------------------------------------------------------------ @@ -934,7 +934,7 @@ class StatisticsChartOptions(MenuReportOptions): self.__filter = None self.__db = dbase MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the statistics report. @@ -944,13 +944,13 @@ class StatisticsChartOptions(MenuReportOptions): category_name = _("Report Options") add_option = partial(menu.add_option, category_name) ################################ - + self.__filter = FilterOption(_("Filter"), 0) self.__filter.set_help( _("Determines what people are included in the report.")) add_option("filter", self.__filter) self.__filter.connect('value-changed', self.__filter_changed) - + self.__pid = PersonOption(_("Filter Person")) self.__pid.set_help(_("The center person for the filter.")) menu.add_option(category_name, "pid", self.__pid) @@ -960,7 +960,7 @@ class StatisticsChartOptions(MenuReportOptions): self._nf.connect('value-changed', self.__update_filters) self.__update_filters() - + stdoptions.add_private_data_option(menu, category_name) sortby = EnumeratedListOption(_('Sort chart items by'), @@ -976,17 +976,17 @@ class StatisticsChartOptions(MenuReportOptions): add_option("reverse", reverse) this_year = time.localtime()[0] - year_from = NumberOption(_("People Born After"), + year_from = NumberOption(_("People Born After"), 1700, 1, this_year) year_from.set_help(_("Birth year from which to include people.")) add_option("year_from", year_from) - - year_to = NumberOption(_("People Born Before"), + + year_to = NumberOption(_("People Born Before"), this_year, 1, this_year) year_to.set_help(_("Birth year until which to include people")) add_option("year_to", year_to) - - no_years = BooleanOption(_("Include people without known birth years"), + + no_years = BooleanOption(_("Include people without known birth years"), False) no_years.set_help(_("Whether to include people without " "known birth years.")) @@ -1025,12 +1025,12 @@ class StatisticsChartOptions(MenuReportOptions): opt.set_help(_("Include charts with indicated data.")) menu.add_option(category_name,opt_name,opt) idx += 1 - + # Enable a couple of charts by default menu.get_option_by_name("data_gender").set_value(True) menu.get_option_by_name("data_ccount").set_value(True) menu.get_option_by_name("data_bmonth").set_value(True) - + def __update_filters(self): """ Update the filter list based on the selected person @@ -1042,7 +1042,7 @@ class StatisticsChartOptions(MenuReportOptions): include_single=False, name_format=nfv) self.__filter.set_filters(filter_list) - + def __filter_changed(self): """ Handle filter change. If the filter is not specific to a person, @@ -1076,7 +1076,7 @@ class StatisticsChartOptions(MenuReportOptions): p.set_alignment(PARA_ALIGN_CENTER) p.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("SC-Title",p) - + """ Graphic Styles: SC-title - Contains the SC-Title paragraph style used for diff --git a/gramps/plugins/drawreport/timeline.py b/gramps/plugins/drawreport/timeline.py index 7ab04e020..2b8a54676 100644 --- a/gramps/plugins/drawreport/timeline.py +++ b/gramps/plugins/drawreport/timeline.py @@ -50,7 +50,7 @@ from gramps.gen.utils.db import get_birth_or_fallback, get_death_or_fallback # # private constants # -#------------------------------------------------------------------------ +#------------------------------------------------------------------------ cal = config.get('preferences.calendar-format-report') # _T_ is a gramps-defined keyword -- see po/update_po.py and po/genpot.sh @@ -78,7 +78,7 @@ class TimeLine(Report): def __init__(self, database, options, user): """ Create the Timeline object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -87,7 +87,7 @@ class TimeLine(Report): 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. @@ -117,16 +117,16 @@ class TimeLine(Report): def write_report(self): # Apply the filter - with self._user.progress(_('Timeline'), - _('Applying filter...'), + with self._user.progress(_('Timeline'), + _('Applying filter...'), self.database.get_number_of_people()) as step: - self.plist = self.filter.apply(self.database, + self.plist = self.filter.apply(self.database, self.database.iter_person_handles(), step) # Find the range of dates to include (low, high) = self.find_year_range() - + # Generate the actual timeline self.generate_timeline(low, high) @@ -141,11 +141,11 @@ class TimeLine(Report): stop = self.doc.get_usable_width() - 0.5 size = (stop - start) self.header = 2.0 - + # Sort the people as requested with self._user.progress(_('Timeline'), _('Sorting dates...'), 0) as step: self.plist.sort(key=self.sort_func) - + self.doc.start_page() self.build_grid(low, high, start, stop, True) @@ -153,8 +153,8 @@ class TimeLine(Report): current = 1; length = len(self.plist) - - with self._user.progress(_('Timeline'), + + with self._user.progress(_('Timeline'), _('Calculating timeline...'), length) as step: for p_id in self.plist: @@ -175,12 +175,12 @@ class TimeLine(Report): mark = ReportUtils.get_person_mark(self.database, p) self.doc.draw_text('TLG-text', n, incr+pad, self.header + (incr+pad)*index, mark) - + y1 = self.header + (pad+incr)*index y2 = self.header + ((pad+incr)*index)+incr y3 = (y1+y2)/2.0 w = 0.05 - + if b: start_offset = ((float(b-low)/float(high-low)) * (size)) x1 = start+start_offset @@ -245,7 +245,7 @@ class TimeLine(Report): for val in range(0,6): xpos = start_pos + (val * delta) self.doc.draw_line('TLG-grid', xpos, top_y, xpos, bottom_y) - + def draw_title(self, toc): """ Draws the title for the page. @@ -264,7 +264,7 @@ class TimeLine(Report): title_font = style_sheet.get_paragraph_style('TLG-Title').get_font() title_y = 1.2 - (pt2cm(title_font.get_size()) * 1.2) self.doc.center_text('TLG-title', title_two, width / 2.0, title_y) - + def draw_year_headings(self, year_low, year_high, start_pos, stop_pos): """ Draws the column headings (years) for the page. @@ -280,7 +280,7 @@ class TimeLine(Report): xpos = start_pos+(val*delta) year_str = str(int(year_low + (incr*val))) self.doc.center_text('TLG-label', year_str, xpos, label_y) - + def draw_no_date_heading(self): """ Draws a single heading that says "No Date Information" @@ -313,9 +313,9 @@ class TimeLine(Report): else: high = year return (low, high) - - with self._user.progress(_('Timeline'), - _('Finding date range...'), + + with self._user.progress(_('Timeline'), + _('Finding date range...'), len(self.plist)) as step: for p_id in self.plist: @@ -336,17 +336,17 @@ class TimeLine(Report): low = int((low/10))*10 else: low = high - + if high is not None: high = int(((high+9)/10))*10 else: high = low - + # Make sure the difference is a multiple of 50 so all year ranges land # on a decade. if low is not None and high is not None: low -= 50 - ((high-low) % 50) - + return (low, high) def name_size(self): @@ -358,7 +358,7 @@ class TimeLine(Report): pname = gstyle.get_paragraph_style() pstyle = style_sheet.get_paragraph_style(pname) font = pstyle.get_font() - + size = 0 for p_id in self.plist: p = self.database.get_person_from_handle(p_id) @@ -378,7 +378,7 @@ class TimeLineOptions(MenuReportOptions): self.__filter = None self.__db = dbase MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): category_name = _("Report Options") @@ -387,7 +387,7 @@ class TimeLineOptions(MenuReportOptions): _("Determines what people are included in the report")) menu.add_option(category_name, "filter", self.__filter) self.__filter.connect('value-changed', self.__filter_changed) - + self.__pid = PersonOption(_("Filter Person")) self.__pid.set_help(_("The center person for the filter")) menu.add_option(category_name, "pid", self.__pid) @@ -407,7 +407,7 @@ class TimeLineOptions(MenuReportOptions): idx += 1 sortby.set_help( _("Sorting method to use")) menu.add_option(category_name,"sortby",sortby) - + stdoptions.add_localization_option(menu, category_name) def __update_filters(self): @@ -421,7 +421,7 @@ class TimeLineOptions(MenuReportOptions): include_single=False, name_format=nfv) self.__filter.set_filters(filter_list) - + def __filter_changed(self): """ Handle filter change. If the filter is not specific to a person, @@ -434,7 +434,7 @@ class TimeLineOptions(MenuReportOptions): else: # The rest don't self.__pid.set_available(False) - + def make_default_style(self,default_style): """Make the default output style for the Timeline report.""" # Paragraph Styles @@ -463,16 +463,16 @@ class TimeLineOptions(MenuReportOptions): p.set_alignment(PARA_ALIGN_CENTER) p.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("TLG-Title",p) - + """ Graphic Styles - TLG-grid - 0.5pt wide line dashed line. Used for the lines that + TLG-grid - 0.5pt wide line dashed line. Used for the lines that make up the grid. - TLG-line - 0.5pt wide line. Used for the line connecting two + TLG-line - 0.5pt wide line. Used for the line connecting two endpoints and for the birth marker. TLG-solid - 0.5pt line with a black fill color. Used for the date of death marker. - TLG-text - Contains the TLG-Name paragraph style used for the + TLG-text - Contains the TLG-Name paragraph style used for the individual's name. TLG-title - Contains the TLG-Title paragraph style used for the title of the document. diff --git a/gramps/plugins/export/export.gpr.py b/gramps/plugins/export/export.gpr.py index 2e1c01109..668f52fb3 100644 --- a/gramps/plugins/export/export.gpr.py +++ b/gramps/plugins/export/export.gpr.py @@ -18,7 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # @@ -137,7 +137,7 @@ plg = newplugin() plg.id = 'ex_gramps' plg.name = _('Gramps XML (family tree)') plg.name_accell = _('Gramps _XML (family tree)') -plg.description = _('Gramps XML export is a complete archived XML backup of a' +plg.description = _('Gramps XML export is a complete archived XML backup of a' ' Gramps family tree without the media object files.' ' Suitable for backup purposes.') plg.version = '1.0' diff --git a/gramps/plugins/export/exportcsv.py b/gramps/plugins/export/exportcsv.py index f8650c604..4aa09641e 100644 --- a/gramps/plugins/export/exportcsv.py +++ b/gramps/plugins/export/exportcsv.py @@ -120,9 +120,9 @@ class UTF8Recoder(object): class UnicodeReader(object): """ - A CSV reader which will iterate over lines in the CSV file "f", which is + A CSV reader which will iterate over lines in the CSV file "f", which is encoded in the given encoding. - + """ def __init__(self, f, encoding="utf-8", **kwds): @@ -138,9 +138,9 @@ class UnicodeReader(object): class UnicodeWriter(object): """ - A CSV writer which will write rows to CSV file "f", which is encoded in + A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. - + """ def __init__(self, f, encoding="utf-8", **kwds): @@ -176,8 +176,8 @@ class UnicodeWriter(object): class CSVWriterOptionBox(WriterOptionBox): """ Create a VBox with the option widgets and define methods to retrieve - the options. - + the options. + """ def __init__(self, person, dbstate, uistate): WriterOptionBox.__init__(self, person, dbstate, uistate) @@ -203,11 +203,11 @@ class CSVWriterOptionBox(WriterOptionBox): self.include_places_check = Gtk.CheckButton(label=_("Include places")) self.translate_headers_check = Gtk.CheckButton(label=_("Translate headers")) - self.include_individuals_check.set_active(1) - self.include_marriages_check.set_active(1) - self.include_children_check.set_active(1) - self.include_places_check.set_active(1) - self.translate_headers_check.set_active(1) + self.include_individuals_check.set_active(1) + self.include_marriages_check.set_active(1) + self.include_children_check.set_active(1) + self.include_places_check.set_active(1) + self.translate_headers_check.set_active(1) option_box.pack_start(self.include_individuals_check, False, True, 0) option_box.pack_start(self.include_marriages_check, False, True, 0) @@ -245,11 +245,11 @@ class CSVWriter(object): self.plist = {} self.flist = {} self.place_list = {} - + self.persons_details_done = [] self.persons_notes_done = [] self.person_ids = {} - + if not option_box: self.include_individuals = 1 self.include_marriages = 1 @@ -265,7 +265,7 @@ class CSVWriter(object): self.include_children = self.option_box.include_children self.include_places = self.option_box.include_places self.translate_headers = self.option_box.translate_headers - + self.plist = [x for x in self.db.iter_person_handles()] # make place list so that dependencies are first: @@ -297,7 +297,7 @@ class CSVWriter(object): child_handle = child_ref.ref if child_handle in self.plist: self.flist[family_handle] = 1 - + def update_empty(self): pass @@ -339,7 +339,7 @@ class CSVWriter(object): self.total += len(self.flist) if self.include_places: self.total += len(self.place_list) - ######################## + ######################## LOG.debug("Possible people to export: %s", len(self.plist)) LOG.debug("Possible families to export: %s", len(self.flist)) LOG.debug("Possible places to export: %s", len(self.place_list)) @@ -366,7 +366,7 @@ class CSVWriter(object): "{count} dropped").format( count=len(dropped_surnames)) ) LOG.debug( - "Dropped surnames: " + + "Dropped surnames: " + ', '.join([("%s %s %s" % (surname.get_prefix(), surname.get_surname(), surname.get_connector())).strip() for surname in dropped_surnames])) @@ -376,22 +376,22 @@ class CSVWriter(object): if self.include_individuals: if self.translate_headers: self.write_csv( - _("Person"), _("Surname"), _("Given"), - _("Call"), _("Suffix"), _("Prefix"), - _("Person|Title"), _("Gender"), + _("Person"), _("Surname"), _("Given"), + _("Call"), _("Suffix"), _("Prefix"), + _("Person|Title"), _("Gender"), _("Birth date"), _("Birth place"), _("Birth source"), _("Baptism date"), _("Baptism place"), _("Baptism source"), - _("Death date"), _("Death place"), _("Death source"), + _("Death date"), _("Death place"), _("Death source"), _("Burial date"), _("Burial place"), _("Burial source"), _("Note")) else: self.write_csv( - "Person", "Surname", "Given", - "Call", "Suffix", "Prefix", - "Title", "Gender", + "Person", "Surname", "Given", + "Call", "Suffix", "Prefix", + "Title", "Gender", "Birth date", "Birth place", "Birth source", "Baptism date", "Baptism place", "Baptism source", - "Death date", "Death place", "Death source", + "Death date", "Death place", "Death source", "Burial date", "Burial place", "Burial source", "Note") for key in plist: @@ -492,13 +492,13 @@ class CSVWriter(object): ) sortorder.sort() # will sort on tuples flist = [data[1] for data in sortorder] - ########################### + ########################### if self.include_marriages: if self.translate_headers: - self.write_csv(_("Marriage"), _("Husband"), _("Wife"), + self.write_csv(_("Marriage"), _("Husband"), _("Wife"), _("Date"), _("Place"), _("Source"), _("Note")) else: - self.write_csv("Marriage", "Husband", "Wife", + self.write_csv("Marriage", "Husband", "Wife", "Date", "Place", "Source", "Note") for key in flist: family = self.db.get_family_from_handle(key) @@ -557,15 +557,15 @@ class CSVWriter(object): self.write_csv(family_id, grampsid_ref) self.update() self.writeln() - ########################### + ########################### if self.include_places: if self.translate_headers: - self.write_csv(_("Place"), _("Title"), _("Name"), - _("Type"), _("Latitude"), _("Longitude"), + self.write_csv(_("Place"), _("Title"), _("Name"), + _("Type"), _("Latitude"), _("Longitude"), _("Code"), _("Enclosed_by"), _("Date")) else: - self.write_csv("Place", "Title", "Name", - "Type", "Latitude", "Longitude", + self.write_csv("Place", "Title", "Name", + "Type", "Latitude", "Longitude", "Code", "Enclosed_by", "Date") for key in self.place_list: place = self.db.get_place_from_handle(key) @@ -595,7 +595,7 @@ class CSVWriter(object): "") self.writeln() self.g.close() - return True - + return True + def format_date(self, date): return get_date(date) diff --git a/gramps/plugins/export/exportftree.py b/gramps/plugins/export/exportftree.py index 51ee9e85d..66939bf8a 100644 --- a/gramps/plugins/export/exportftree.py +++ b/gramps/plugins/export/exportftree.py @@ -57,7 +57,7 @@ from gramps.gui.glade import Glade def writeData(database, filename, user, option_box=None): writer = FtreeWriter(database, filename, user, option_box) return writer.export_data() - + #------------------------------------------------------------------------- # # FtreeWriter @@ -159,7 +159,7 @@ class FtreeWriter(object): # alive = probably_alive(p, self.db) #else: # alive = 0 - + if birth: if death: dates = "%s-%s" % (fdate(birth), fdate(death)) @@ -170,10 +170,10 @@ class FtreeWriter(object): dates = fdate(death) else: dates = "" - - f.write('%s;%s;%s;%s;%s;%s\n' % (name, father, mother, email, web, + + f.write('%s;%s;%s;%s;%s;%s\n' % (name, father, mother, email, web, dates)) - + f.close() return True @@ -181,7 +181,7 @@ def fdate(val): if val.get_year_valid(): if val.get_month_valid(): if val.get_day_valid(): - return "%d/%d/%d" % (val.get_day(), val.get_month(), + return "%d/%d/%d" % (val.get_day(), val.get_month(), val.get_year()) else: return "%d/%d" % (val.get_month(), val.get_year()) @@ -193,7 +193,7 @@ def fdate(val): def get_name(name, surname, count): """returns a name string built from the components of the Name instance, in the form of Firstname Surname""" - + return (name.first_name + ' ' + surname + (str(count) if count != -1 else '') + diff --git a/gramps/plugins/export/exportgedcom.py b/gramps/plugins/export/exportgedcom.py index 668dc6d5e..e02793ffa 100644 --- a/gramps/plugins/export/exportgedcom.py +++ b/gramps/plugins/export/exportgedcom.py @@ -15,7 +15,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -43,9 +43,9 @@ import io #------------------------------------------------------------------------- from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext -from gramps.gen.lib import (AttributeType, ChildRefType, Citation, Date, - EventRoleType, EventType, LdsOrd, NameType, - PlaceType, NoteType, Person, UrlType, +from gramps.gen.lib import (AttributeType, ChildRefType, Citation, Date, + EventRoleType, EventType, LdsOrd, NameType, + PlaceType, NoteType, Person, UrlType, SrcAttributeType) from gramps.version import VERSION import gramps.plugins.lib.libgedcom as libgedcom @@ -64,31 +64,31 @@ from gramps.gen.display.place import displayer as place_displayer # #------------------------------------------------------------------------- NEEDS_PARAMETER = set( - ["CAST", "DSCR", "EDUC", "IDNO", "NATI", "NCHI", + ["CAST", "DSCR", "EDUC", "IDNO", "NATI", "NCHI", "NMR", "OCCU", "PROP", "RELI", "SSN", "TITL"]) LDS_ORD_NAME = { - LdsOrd.BAPTISM : 'BAPL', - LdsOrd.ENDOWMENT : 'ENDL', - LdsOrd.SEAL_TO_PARENTS : 'SLGC', - LdsOrd.SEAL_TO_SPOUSE : 'SLGS', - LdsOrd.CONFIRMATION : 'CONL', + LdsOrd.BAPTISM : 'BAPL', + LdsOrd.ENDOWMENT : 'ENDL', + LdsOrd.SEAL_TO_PARENTS : 'SLGC', + LdsOrd.SEAL_TO_SPOUSE : 'SLGS', + LdsOrd.CONFIRMATION : 'CONL', } LDS_STATUS = { - LdsOrd.STATUS_BIC : "BIC", - LdsOrd.STATUS_CANCELED : "CANCELED", - LdsOrd.STATUS_CHILD : "CHILD", - LdsOrd.STATUS_CLEARED : "CLEARED", - LdsOrd.STATUS_COMPLETED : "COMPLETED", - LdsOrd.STATUS_DNS : "DNS", - LdsOrd.STATUS_INFANT : "INFANT", - LdsOrd.STATUS_PRE_1970 : "PRE-1970", - LdsOrd.STATUS_QUALIFIED : "QUALIFIED", - LdsOrd.STATUS_DNS_CAN : "DNS/CAN", - LdsOrd.STATUS_STILLBORN : "STILLBORN", - LdsOrd.STATUS_SUBMITTED : "SUBMITTED" , - LdsOrd.STATUS_UNCLEARED : "UNCLEARED", + LdsOrd.STATUS_BIC : "BIC", + LdsOrd.STATUS_CANCELED : "CANCELED", + LdsOrd.STATUS_CHILD : "CHILD", + LdsOrd.STATUS_CLEARED : "CLEARED", + LdsOrd.STATUS_COMPLETED : "COMPLETED", + LdsOrd.STATUS_DNS : "DNS", + LdsOrd.STATUS_INFANT : "INFANT", + LdsOrd.STATUS_PRE_1970 : "PRE-1970", + LdsOrd.STATUS_QUALIFIED : "QUALIFIED", + LdsOrd.STATUS_DNS_CAN : "DNS/CAN", + LdsOrd.STATUS_STILLBORN : "STILLBORN", + LdsOrd.STATUS_SUBMITTED : "SUBMITTED" , + LdsOrd.STATUS_UNCLEARED : "UNCLEARED", } LANGUAGES = { @@ -98,7 +98,7 @@ LANGUAGES = { 'it' : 'Italian', 'lt' : 'Latvian', 'lv' : 'Lithuanian', 'no' : 'Norwegian', 'po' : 'Polish', 'pt' : 'Portuguese', 'ro' : 'Romanian', 'sk' : 'Slovak', 'es' : 'Spanish', - 'sv' : 'Swedish', 'ru' : 'Russian', + 'sv' : 'Swedish', 'ru' : 'Russian', } #------------------------------------------------------------------------- @@ -108,19 +108,19 @@ LANGUAGES = { #------------------------------------------------------------------------- MIME2GED = { - "image/bmp" : "bmp", - "image/gif" : "gif", - "image/jpeg" : "jpeg", - "image/x-pcx" : "pcx", - "image/tiff" : "tiff", + "image/bmp" : "bmp", + "image/gif" : "gif", + "image/jpeg" : "jpeg", + "image/x-pcx" : "pcx", + "image/tiff" : "tiff", "audio/x-wav" : "wav" } QUALITY_MAP = { - Citation.CONF_VERY_HIGH : "3", - Citation.CONF_HIGH : "2", - Citation.CONF_LOW : "1", - Citation.CONF_VERY_LOW : "0", + Citation.CONF_VERY_HIGH : "3", + Citation.CONF_HIGH : "2", + Citation.CONF_LOW : "1", + Citation.CONF_VERY_LOW : "0", } @@ -131,11 +131,11 @@ QUALITY_MAP = { #------------------------------------------------------------------------- def sort_handles_by_id(handle_list, handle_to_object): """ - Sort a list of handles by the Gramps ID. - - The function that returns the object from the handle needs to be supplied + Sort a list of handles by the Gramps ID. + + The function that returns the object from the handle needs to be supplied so that we get the right object. - + """ sorted_list = [] for handle in handle_list: @@ -153,7 +153,7 @@ def sort_handles_by_id(handle_list, handle_to_object): #------------------------------------------------------------------------- def breakup(txt, limit): """ - Break a line of text into a list of strings that conform to the + Break a line of text into a list of strings that conform to the maximum length specified, while breaking words in the middle of a word to avoid issues with spaces. """ @@ -205,7 +205,7 @@ def event_has_subordinate_data(event, event_ref): #------------------------------------------------------------------------- class GedcomWriter(UpdateCallback): """ - The GEDCOM writer creates a GEDCOM file that contains the exported + The GEDCOM writer creates a GEDCOM file that contains the exported information from the database. It derives from UpdateCallback so that it can provide visual feedback via a progress bar if needed. """ @@ -220,7 +220,7 @@ class GedcomWriter(UpdateCallback): # The number of different stages other than any of the optional filters # which the write_gedcom_file method will call. self.progress_cnt = 5 - + self.setup(option_box) def setup(self, option_box): @@ -261,7 +261,7 @@ class GedcomWriter(UpdateCallback): If the line contains newlines, it is broken into multiple lines using the CONT token. If any line is greater than the limit, it will broken into multiple lines using CONC. - + """ assert(token) if textlines: @@ -283,39 +283,39 @@ class GedcomWriter(UpdateCallback): token = "CONT" else: self.gedcom_file.write("%d %s\n" % (level, token)) - + def _header(self, filename): """ - Write the GEDCOM header. + Write the GEDCOM header. HEADER:= n HEAD {1:1} - +1 SOUR {1:1} - +2 VERS {0:1} - +2 NAME {0:1} + +1 SOUR {1:1} + +2 VERS {0:1} + +2 NAME {0:1} +2 CORP {0:1} # Not used +3 <> {0:1} # Not used +2 DATA {0:1} # Not used +3 DATE {0:1} # Not used +3 COPR {0:1} # Not used +1 DEST {0:1*} # Not used - +1 DATE {0:1} - +2 TIME {0:1} - +1 SUBM @XREF:SUBM@ {1:1} - +1 SUBN @XREF:SUBN@ {0:1} - +1 FILE {0:1} - +1 COPR {0:1} + +1 DATE {0:1} + +2 TIME {0:1} + +1 SUBM @XREF:SUBM@ {1:1} + +1 SUBN @XREF:SUBN@ {0:1} + +1 FILE {0:1} + +1 COPR {0:1} +1 GEDC {1:1} - +2 VERS {1:1} - +2 FORM {1:1} - +1 CHAR {1:1} - +2 VERS {0:1} - +1 LANG {0:1} + +2 VERS {1:1} + +2 FORM {1:1} + +1 CHAR {1:1} + +2 VERS {0:1} + +1 LANG {0:1} +1 PLAC {0:1} - +2 FORM {1:1} - +1 NOTE {0:1} + +2 FORM {1:1} + +1 NOTE {0:1} +2 [CONT|CONC] {0:M} - + """ local_time = time.localtime(time.time()) (year, mon, day, hour, minutes, sec) = local_time[0:6] @@ -336,8 +336,8 @@ class GedcomWriter(UpdateCallback): self._writeln(2, "VERS", "5.5.1") self._writeln(2, "FORM", 'LINEAGE-LINKED') self._writeln(1, "CHAR", "UTF-8") - - # write the language string if the current LANG variable + + # write the language string if the current LANG variable # matches something we know about. lang = glocale.language[0] @@ -349,7 +349,7 @@ class GedcomWriter(UpdateCallback): def _submitter(self): """ n @@ SUBM {1:1} - +1 NAME {1:1} + +1 NAME {1:1} +1 <> {0:1} +1 <> {0:M} # not used +1 LANG {0:3} # not used @@ -364,14 +364,14 @@ class GedcomWriter(UpdateCallback): self._writeln(0, "@SUBM@", "SUBM") self._writeln(1, "NAME", name) - + # Researcher is a sub-type of LocationBase, so get_city etc. which are # used in __write_addr work fine. However, the database owner street is # stored in address, so we need to temporarily copy it into street so # __write_addr works properly owner.set_street(owner.get_address()) self.__write_addr(1, owner) - + if phon: self._writeln(1, "PHON", phon) if mail: @@ -379,18 +379,18 @@ class GedcomWriter(UpdateCallback): def _individuals(self): """ - Write the individual people to the gedcom file. - - Since people like to have the list sorted by ID value, we need to go - through a sorting step. We need to reset the progress bar, otherwise, + Write the individual people to the gedcom file. + + Since people like to have the list sorted by ID value, we need to go + through a sorting step. We need to reset the progress bar, otherwise, people will be confused when the progress bar is idle. - + """ self.reset(_("Writing individuals")) self.progress_cnt += 1 self.update(self.progress_cnt) phandles = self.dbase.iter_person_handles() - + sorted_list = [] for handle in phandles: person = self.dbase.get_person_from_handle(handle) @@ -408,27 +408,27 @@ class GedcomWriter(UpdateCallback): n @XREF:INDI@ INDI {1:1} +1 RESN {0:1} # not used - +1 <> {0:M} - +1 SEX {0:1} - +1 <> {0:M} - +1 <> {0:M} - +1 <> {0:M} - +1 <> {0:M} - +1 <> {0:M} - +1 SUBM @@ {0:M} - +1 <> {0:M} - +1 ALIA @@ {0:M} - +1 ANCI @@ {0:M} - +1 DESI @@ {0:M} - +1 <> {0:M} + +1 <> {0:M} + +1 SEX {0:1} + +1 <> {0:M} + +1 <> {0:M} + +1 <> {0:M} + +1 <> {0:M} + +1 <> {0:M} + +1 SUBM @@ {0:M} + +1 <> {0:M} + +1 ALIA @@ {0:M} + +1 ANCI @@ {0:M} + +1 DESI @@ {0:M} + +1 <> {0:M} +1 <> {0:M} ,* - +1 <> {0:M} - +1 RFN {0:1} - +1 AFN {0:1} - +1 REFN {0:M} - +2 TYPE {0:1} - +1 RIN {0:1} - +1 <> {0:1} + +1 <> {0:M} + +1 RFN {0:1} + +1 AFN {0:1} + +1 REFN {0:M} + +2 TYPE {0:1} + +1 RIN {0:1} + +1 <> {0:1} """ if person is None: return @@ -453,10 +453,10 @@ class GedcomWriter(UpdateCallback): def _assoc(self, person, level): """ - n ASSO @@ {0:M} + n ASSO @@ {0:M} +1 RELA {1:1} - +1 <> {0:M} - +1 <> {0:M} + +1 <> {0:M} + +1 <> {0:M} """ for ref in person.get_person_ref_list(): person = self.dbase.get_person_from_handle(ref.ref) @@ -468,8 +468,8 @@ class GedcomWriter(UpdateCallback): def _note_references(self, notelist, level): """ - Write out the list of note handles to the current level. - + Write out the list of note handles to the current level. + We use the Gramps ID as the XREF for the GEDCOM file. """ @@ -481,10 +481,10 @@ class GedcomWriter(UpdateCallback): def _names(self, person): """ Write the names associated with the person to the current level. - + Since nicknames in version < 3.3 are separate from the name structure, - we search the attribute list to see if we can find a nickname. - Because we do not know the mappings, we just take the first nickname + we search the attribute list to see if we can find a nickname. + Because we do not know the mappings, we just take the first nickname we find, and add it to the primary name. If a nickname is present in the name structure, it has precedence @@ -502,12 +502,12 @@ class GedcomWriter(UpdateCallback): def _gender(self, person): """ - Write out the gender of the person to the file. - - If the gender is not male or female, simply do not output anything. - The only valid values are M (male) or F (female). So if the geneder is + Write out the gender of the person to the file. + + If the gender is not male or female, simply do not output anything. + The only valid values are M (male) or F (female). So if the geneder is unknown, we output nothing. - + """ if person.get_gender() == Person.MALE: self._writeln(1, "SEX", "M") @@ -516,7 +516,7 @@ class GedcomWriter(UpdateCallback): def _lds_ords(self, obj, level): """ - Simply loop through the list of LDS ordinances, and call the function + Simply loop through the list of LDS ordinances, and call the function that writes the LDS ordinance structure. """ for lds_ord in obj.get_lds_ord_list(): @@ -525,11 +525,11 @@ class GedcomWriter(UpdateCallback): def _remaining_events(self, person): """ Output all events associated with the person that are not BIRTH or - DEATH events. - + DEATH events. + Because all we have are event references, we have to extract the real event to discover the event type. - + """ global adop_written # adop_written is only shared between this function and @@ -600,12 +600,12 @@ class GedcomWriter(UpdateCallback): +1 <> +1 FAMC @@ +2 ADOP - + """ - + adoptions = [] - for family in [ self.dbase.get_family_from_handle(fh) + for family in [ self.dbase.get_family_from_handle(fh) for fh in person.get_parent_family_handle_list() ]: if family is None: continue @@ -628,16 +628,16 @@ class GedcomWriter(UpdateCallback): def _attributes(self, person): """ - Write out the attributes to the GEDCOM file. - - Since we have already looked at nicknames when we generated the names, + Write out the attributes to the GEDCOM file. + + Since we have already looked at nicknames when we generated the names, we filter them out here. We use the GEDCOM 5.5.1 FACT command to write out attributes not built in to GEDCOM. - + """ - + # filter out the nicknames attr_list = [ attr for attr in person.get_attribute_list() if attr.get_type() != AttributeType.NICKNAME ] @@ -648,7 +648,7 @@ class GedcomWriter(UpdateCallback): name = libgedcom.PERSONALCONSTANTATTRIBUTES.get(attr_type) key = str(attr.get_type()) value = attr.get_value().strip().replace('\r', ' ') - + if key in ("AFN", "RFN", "REFN", "_UID", "_FSFTID"): self._writeln(1, key, value) continue @@ -702,7 +702,7 @@ class GedcomWriter(UpdateCallback): Write the Gramps ID as the XREF for each family in which the person is listed as a child. """ - + # get the list of familes from the handle list family_list = [ self.dbase.get_family_from_handle(hndl) for hndl in person.get_parent_family_handle_list() ] @@ -736,8 +736,8 @@ class GedcomWriter(UpdateCallback): def _url_list(self, obj, level): """ n OBJE {1:1} - +1 FORM {1:1} - +1 TITL {0:1} + +1 FORM {1:1} + +1 TITL {0:1} +1 FILE {1:1} +1 <> {0:M} """ @@ -758,7 +758,7 @@ class GedcomWriter(UpdateCallback): self.update(self.progress_cnt) # generate a list of (GRAMPS_ID, HANDLE) pairs. This list # can then be sorted by the sort routine, which will use the - # first value of the tuple as the sort key. + # first value of the tuple as the sort key. sorted_list = sort_handles_by_id(self.dbase.get_family_handles(), self.dbase.get_family_from_handle) @@ -771,7 +771,7 @@ class GedcomWriter(UpdateCallback): """ n @@ FAM {1:1} +1 RESN {0:1) - +1 <> {0:M} + +1 <> {0:M} +1 HUSB @@ {0:1} +1 WIFE @@ {0:1} +1 CHIL @@ {0:M} @@ -800,9 +800,9 @@ class GedcomWriter(UpdateCallback): def _family_child_list(self, child_ref_list): """ - Write the child XREF values to the GEDCOM file. + Write the child XREF values to the GEDCOM file. """ - child_list = [ + child_list = [ self.dbase.get_person_from_handle(cref.ref).get_gramps_id() for cref in child_ref_list] @@ -812,11 +812,11 @@ class GedcomWriter(UpdateCallback): def _family_reference(self, token, person_handle): """ - Write the family reference to the file. - - This is either 'WIFE' or 'HUSB'. As usual, we use the Gramps ID as the + Write the family reference to the file. + + This is either 'WIFE' or 'HUSB'. As usual, we use the Gramps ID as the XREF value. - + """ if person_handle: person = self.dbase.get_person_from_handle(person_handle) @@ -825,11 +825,11 @@ class GedcomWriter(UpdateCallback): def _family_events(self, family): """ - Output the events associated with the family. - - Because all we have are event references, we have to extract the real + Output the events associated with the family. + + Because all we have are event references, we have to extract the real event to discover the event type. - + """ for event_ref in family.get_event_ref_list(): event = self.dbase.get_event_from_handle(event_ref.ref) @@ -851,7 +851,7 @@ class GedcomWriter(UpdateCallback): self._writeln(1, val, 'Y') if event.get_type() == EventType.MARRIAGE: - self._family_event_attrs(event.get_attribute_list(), 2) + self._family_event_attrs(event.get_attribute_list(), 2) if event.get_description().strip() != "": self._writeln(2, 'TYPE', event.get_description()) @@ -866,11 +866,11 @@ class GedcomWriter(UpdateCallback): def _family_event_attrs(self, attr_list, level): """ - Write the attributes associated with the family event. - - The only ones we really care about are FATHER_AGE and MOTHER_AGE which + Write the attributes associated with the family event. + + The only ones we really care about are FATHER_AGE and MOTHER_AGE which we translate to WIFE/HUSB AGE attributes. - + """ for attr in attr_list: if attr.get_type() == AttributeType.FATHER_AGE: @@ -883,17 +883,17 @@ class GedcomWriter(UpdateCallback): def _family_attributes(self, attr_list, level): """ Write out the attributes associated with a family to the GEDCOM file. - - Since we have already looked at nicknames when we generated the names, + + Since we have already looked at nicknames when we generated the names, we filter them out here. We use the GEDCOM 5.5.1 FACT command to write out attributes not built in to GEDCOM. - + """ for attr in attr_list: - + attr_type = int(attr.get_type()) name = libgedcom.FAMILYCONSTANTATTRIBUTES.get(attr_type) key = str(attr.get_type()) @@ -902,7 +902,7 @@ class GedcomWriter(UpdateCallback): if key in ("AFN", "RFN", "REFN", "_UID"): self._writeln(1, key, value) continue - + if name and name.strip(): self._writeln(1, name, value) continue @@ -911,7 +911,7 @@ class GedcomWriter(UpdateCallback): self._writeln(2, 'TYPE', key) self._note_references(attr.get_note_list(), level+1) - self._source_references(attr.get_citation_list(), + self._source_references(attr.get_citation_list(), level+1) def _sources(self): @@ -963,16 +963,16 @@ class GedcomWriter(UpdateCallback): note = self.dbase.get_note_from_handle(note_handle) if note is None: continue self._note_record(note) - + def _note_record(self, note): """ - n @@ NOTE {1:1} + n @@ NOTE {1:1} +1 [ CONC | CONT] {0:M} - +1 <> {0:M} - +1 REFN {0:M} - +2 TYPE {0:1} - +1 RIN {0:1} - +1 <> {0:1} + +1 <> {0:M} + +1 REFN {0:M} + +2 TYPE {0:1} + +1 RIN {0:1} + +1 <> {0:1} """ if note: self._writeln(0, '@%s@' % note.get_gramps_id(), 'NOTE ' + note.get()) @@ -1030,7 +1030,7 @@ class GedcomWriter(UpdateCallback): repo = self.dbase.get_repository_from_handle(reporef.ref) if repo is None: return - + repo_id = repo.get_gramps_id() self._writeln(level, 'REPO', '@%s@' % repo_id ) @@ -1073,11 +1073,11 @@ class GedcomWriter(UpdateCallback): def _dump_event_stats(self, event, event_ref): """ - Write the event details for the event, using the event and event - reference information. - + Write the event details for the event, using the event and event + reference information. + GEDCOM does not make a distinction between the two. - + """ dateobj = event.get_date_object() self._date(2, dateobj) @@ -1169,7 +1169,7 @@ class GedcomWriter(UpdateCallback): self._place(place, lds_ord.get_date_object(), 2) if lds_ord.get_status() != LdsOrd.STATUS_NONE: self._writeln(2, 'STAT', LDS_STATUS[lds_ord.get_status()]) - + self._note_references(lds_ord.get_note_list(), index+1) self._source_references(lds_ord.get_citation_list(), index+1) @@ -1191,14 +1191,14 @@ class GedcomWriter(UpdateCallback): if mod == Date.MOD_SPAN: val = "%sFROM %s TO %s" % ( qual_text, - libgedcom.make_gedcom_date(start, cal, mod, None), - libgedcom.make_gedcom_date(date.get_stop_date(), + libgedcom.make_gedcom_date(start, cal, mod, None), + libgedcom.make_gedcom_date(date.get_stop_date(), cal, mod, None)) elif mod == Date.MOD_RANGE: val = "%sBET %s AND %s" % ( qual_text, - libgedcom.make_gedcom_date(start, cal, mod, None), - libgedcom.make_gedcom_date(date.get_stop_date(), + libgedcom.make_gedcom_date(start, cal, mod, None), + libgedcom.make_gedcom_date(date.get_stop_date(), cal, mod, None)) else: val = libgedcom.make_gedcom_date(start, cal, mod, quality) @@ -1210,15 +1210,15 @@ class GedcomWriter(UpdateCallback): def _person_name(self, name, attr_nick): """ - n NAME {1:1} - +1 NPFX {0:1} - +1 GIVN {0:1} - +1 NICK {0:1} - +1 SPFX {0:1} - +1 NSFX {0:1} - +1 <> {0:M} - +1 <> {0:M} + n NAME {1:1} + +1 NPFX {0:1} + +1 GIVN {0:1} + +1 NICK {0:1} + +1 SPFX {0:1} + +1 NSFX {0:1} + +1 <> {0:M} + +1 <> {0:M} """ gedcom_name = name.get_gedcom_name() @@ -1267,21 +1267,21 @@ class GedcomWriter(UpdateCallback): def _source_ref_record(self, level, citation_handle): """ - n SOUR @@ /* pointer to source record */ {1:1} - +1 PAGE {0:1} - +1 EVEN {0:1} - +2 ROLE {0:1} + n SOUR @@ /* pointer to source record */ {1:1} + +1 PAGE {0:1} + +1 EVEN {0:1} + +2 ROLE {0:1} +1 DATA {0:1} - +2 DATE {0:1} - +2 TEXT {0:M} + +2 DATE {0:1} + +2 TEXT {0:M} +3 [ CONC | CONT ] {0:M} - +1 QUAY {0:1} + +1 QUAY {0:1} +1 <> {0:M} ,* - +1 <> {0:M} + +1 <> {0:M} """ citation = self.dbase.get_citation_from_handle(citation_handle) - + src_handle = citation.get_reference_handle() if src_handle is None: return @@ -1296,11 +1296,11 @@ class GedcomWriter(UpdateCallback): # PAGE can not have CONC lines. # WHERE_WITHIN_SOURCE:= {Size=1:248} # Maximize line to 248 and set limit to 248, for no line split - self._writeln(level+1, 'PAGE', citation.get_page()[0:248], + self._writeln(level+1, 'PAGE', citation.get_page()[0:248], limit=248) - conf = min(citation.get_confidence_level(), + conf = min(citation.get_confidence_level(), Citation.CONF_VERY_HIGH) if conf != Citation.CONF_NORMAL and conf != -1: self._writeln(level+1, "QUAY", QUALITY_MAP[conf]) @@ -1311,9 +1311,9 @@ class GedcomWriter(UpdateCallback): if len(citation.get_note_list()) > 0: - note_list = [ self.dbase.get_note_from_handle(h) + note_list = [ self.dbase.get_note_from_handle(h) for h in citation.get_note_list() ] - note_list = [ n for n in note_list + note_list = [ n for n in note_list if n.get_type() == NoteType.SOURCE_TEXT] if note_list: @@ -1326,14 +1326,14 @@ class GedcomWriter(UpdateCallback): if ref_text != "": self._writeln(level+2, "TEXT", ref_text) - note_list = [ self.dbase.get_note_from_handle(h) + note_list = [ self.dbase.get_note_from_handle(h) for h in citation.get_note_list() ] - note_list = [ n.handle for n in note_list + note_list = [ n.handle for n in note_list if n and n.get_type() != NoteType.SOURCE_TEXT] self._note_references(note_list, level+1) - + self._photos(citation.get_media_list(), level+1) - + even = None for srcattr in citation.get_attribute_list(): if str(srcattr.type) == "EVEN": @@ -1349,8 +1349,8 @@ class GedcomWriter(UpdateCallback): def _photo(self, photo, level): """ n OBJE {1:1} - +1 FORM {1:1} - +1 TITL {0:1} + +1 FORM {1:1} + +1 TITL {0:1} +1 FILE {1:1} +1 <> {0:M} """ @@ -1382,7 +1382,7 @@ class GedcomWriter(UpdateCallback): +1 MAP {0:1} +2 LATI {1:1} +2 LONG {1:1} - +1 <> {0:M} + +1 <> {0:M} """ if place is None: return place_name = place_displayer.display(self.dbase, place, dateobj) @@ -1406,7 +1406,7 @@ class GedcomWriter(UpdateCallback): state = location.get(PlaceType.STATE) country = location.get(PlaceType.COUNTRY) postal_code = place.get_code() - + if (street or locality or city or state or postal_code or country): self._writeln(level, "ADDR", street) if street: @@ -1426,7 +1426,7 @@ class GedcomWriter(UpdateCallback): def __write_addr(self, level, addr): """ - n ADDR {0:1} + n ADDR {0:1} +1 CONT {0:M} +1 ADR1 {0:1} (Street) +1 ADR2 {0:1} (Locality) @@ -1462,7 +1462,7 @@ class GedcomWriter(UpdateCallback): self._writeln(level + 1, 'CONT', addr.get_postal_code()) if addr.get_country(): self._writeln(level + 1, 'CONT', addr.get_country()) - + if addr.get_street(): self._writeln(level + 1, 'ADR1', addr.get_street()) if addr.get_locality(): diff --git a/gramps/plugins/export/exportgeneweb.py b/gramps/plugins/export/exportgeneweb.py index 31b62d673..aace7dde4 100644 --- a/gramps/plugins/export/exportgeneweb.py +++ b/gramps/plugins/export/exportgeneweb.py @@ -68,7 +68,7 @@ class GeneWebWriter(object): self.persons_details_done = [] self.persons_notes_done = [] self.person_ids = {} - + if option_box: self.option_box.parse_options() self.db = option_box.get_filtered_database(self.db) @@ -103,17 +103,17 @@ class GeneWebWriter(object): if len(self.flist) < 1: self.user.notify_error(_("No families matched by selected filter")) return False - + self.count = 0 self.oldval = 0 self.total = len(self.flist) for key in self.flist: self.write_family(key) self.writeln("") - + self.g.close() return True - + def write_family(self, family_handle): family = self.db.get_family_from_handle(family_handle) if family: @@ -125,9 +125,9 @@ class GeneWebWriter(object): if mother_handle: mother = self.db.get_person_from_handle(mother_handle) self.writeln("fam %s %s+%s %s %s" % - (self.get_ref_name(father), - self.get_full_person_info_fam(father), - self.get_wedding_data(family), + (self.get_ref_name(father), + self.get_full_person_info_fam(father), + self.get_wedding_data(family), self.get_ref_name(mother), self.get_full_person_info_fam(mother) ) @@ -148,11 +148,11 @@ class GeneWebWriter(object): note = note.replace('\n',' ') note = note.replace('\r',' ') self.writeln("comm %s" % note) - + def write_witness(self, family): # FIXME: witnesses are not in events anymore return - + if self.restrict: return event_ref_list = family.get_event_ref_list() @@ -171,9 +171,9 @@ class GeneWebWriter(object): gender = "h" elif person.get_gender() == Person.FEMALE: gender = "f" - self.writeln("wit %s %s %s" % - (gender, - self.get_ref_name(person), + self.writeln("wit %s %s %s" % + (gender, + self.get_ref_name(person), self.get_full_person_info_fam(person) ) ) @@ -182,14 +182,14 @@ class GeneWebWriter(object): # FIXME #if self.restrict and self.exclnotes: # return - + if reflist: for handle in reflist: citation = self.db.get_citation_from_handle(handle) src_handle = citation.get_reference_handle() source = self.db.get_source_from_handle(src_handle) if source: - self.writeln( "src %s" % + self.writeln( "src %s" % (self.rem_spaces(source.get_title())) ) @@ -206,9 +206,9 @@ class GeneWebWriter(object): gender = "h" elif child.get_gender() == Person.FEMALE: gender = "f" - self.writeln("- %s %s %s" % - (gender, - self.get_child_ref_name(child, father_lastname), + self.writeln("- %s %s %s" % + (gender, + self.get_child_ref_name(child, father_lastname), self.get_full_person_info_child(child) ) ) @@ -218,7 +218,7 @@ class GeneWebWriter(object): # FIXME: #if self.restrict and self.exclnotes: # return - + self.write_note_of_person(father) self.write_note_of_person(mother) child_ref_list = family.get_child_ref_list() @@ -243,7 +243,7 @@ class GeneWebWriter(object): def write_note_of_person(self,person): if self.persons_notes_done.count(person.get_handle()) == 0: self.persons_notes_done.append(person.get_handle()) - + notelist = person.get_note_list() note = "" for notehandle in notelist: @@ -257,12 +257,12 @@ class GeneWebWriter(object): self.writeln("beg") self.writeln(note) self.writeln("end notes") - + def get_full_person_info(self, person): # FIXME: #if self.restrict: # return "0 " - + retval = "" b_date = "0" @@ -275,7 +275,7 @@ class GeneWebWriter(object): place_handle = birth.get_place_handle() if place_handle: b_place = _pd.display_event(self.db, birth) - + if probably_alive(person,self.db): d_date = "" else: @@ -289,7 +289,7 @@ class GeneWebWriter(object): place_handle = death.get_place_handle() if place_handle: d_place = _pd.display_event(self.db, death) - + retval = retval + "%s " % b_date if b_place != "": retval = retval + "#bp %s " % self.rem_spaces(b_place) @@ -300,9 +300,9 @@ class GeneWebWriter(object): def get_full_person_info_fam(self, person): """Output full person data of a family member. - + This is only done if the person is not listed as a child. - + """ retval = "" if self.persons_details_done.count(person.get_handle()) == 0: @@ -316,7 +316,7 @@ class GeneWebWriter(object): self.persons_details_done.append(person.get_handle()) retval = self.get_full_person_info(person) return retval - + def get_full_person_info_child(self, person): """Output full person data for a child, if not printed somewhere else.""" @@ -328,17 +328,17 @@ class GeneWebWriter(object): def rem_spaces(self,str): return str.replace(' ','_') - + def get_ref_name(self,person): #missing_surname = config.get("preferences.no-surname-text") surname = self.rem_spaces( person.get_primary_name().get_surname()) - #firstname = config.get('preferences.private-given-text') + #firstname = config.get('preferences.private-given-text') #if not (probably_alive(person,self.db) and \ # self.restrict and self.living): firstname = self.rem_spaces( person.get_primary_name().get_first_name()) if person.get_handle() not in self.person_ids: self.person_ids[person.get_handle()] = len(self.person_ids) - return "%s %s.%d" % (surname, firstname, + return "%s %s.%d" % (surname, firstname, self.person_ids[person.get_handle()]) def get_child_ref_name(self,person,father_lastname): @@ -430,11 +430,11 @@ class GeneWebWriter(object): ret = ret + ", " ret = ret + source.get_title() return ret - + def format_single_date(self, subdate, cal, mode): retval = "" (day, month, year, sl) = subdate - + cal_type = "" if cal == Date.CAL_HEBREW: cal_type = "H" @@ -442,7 +442,7 @@ class GeneWebWriter(object): cal_type = "F" elif cal == Date.CAL_JULIAN: cal_type = "J" - + mode_prefix = "" if mode == Date.MOD_ABOUT: mode_prefix = "~" @@ -450,7 +450,7 @@ class GeneWebWriter(object): mode_prefix = "<" elif mode == Date.MOD_AFTER: mode_prefix = ">" - + if year > 0: if month > 0: if day > 0: @@ -461,7 +461,7 @@ class GeneWebWriter(object): retval = "%s%s%s" % (mode_prefix,year,cal_type) return retval - + def format_date(self,date): retval = "" if date.get_modifier() == Date.MOD_TEXTONLY: diff --git a/gramps/plugins/export/exportpkg.py b/gramps/plugins/export/exportpkg.py index 75b5a2381..28d65c423 100644 --- a/gramps/plugins/export/exportpkg.py +++ b/gramps/plugins/export/exportpkg.py @@ -85,7 +85,7 @@ def writeData(database, filename, user, option_box=None): writer = PackageWriter(database, filename, user) return writer.export() - + #------------------------------------------------------------------------- # # PackageWriter @@ -97,7 +97,7 @@ class PackageWriter(object): self.db = database self.user = user self.filename = filename - + def export(self): # missmedia_action = 0 #-------------------------------------------------------------- @@ -108,7 +108,7 @@ class PackageWriter(object): # nl = p.get_media_list() # for o in nl: # if o.get_reference_handle() == m_id: - # nl.remove(o) + # nl.remove(o) # p.set_media_list(nl) # self.db.commit_family(p,None) # for key in self.db.iter_person_handles(): @@ -116,7 +116,7 @@ class PackageWriter(object): # nl = p.get_media_list() # for o in nl: # if o.get_reference_handle() == m_id: - # nl.remove(o) + # nl.remove(o) # p.set_media_list(nl) # self.db.commit_person(p,None) # for key in self.db.get_source_handles(): @@ -124,7 +124,7 @@ class PackageWriter(object): # nl = p.get_media_list() # for o in nl: # if o.get_reference_handle() == m_id: - # nl.remove(o) + # nl.remove(o) # p.set_media_list(nl) # self.db.commit_source(p,None) # for key in self.db.get_place_handles(): @@ -132,7 +132,7 @@ class PackageWriter(object): # nl = p.get_media_list() # for o in nl: # if o.get_reference_handle() == m_id: - # nl.remove(o) + # nl.remove(o) # p.set_media_list(nl) # self.db.commit_place(p,None) # for key in self.db.get_event_handles(): @@ -140,7 +140,7 @@ class PackageWriter(object): # nl = p.get_media_list() # for o in nl: # if o.get_reference_handle() == m_id: - # nl.remove(o) + # nl.remove(o) # p.set_media_list(nl) # self.db.commit_event(p,None) # self.db.remove_object(m_id,None) @@ -158,7 +158,7 @@ class PackageWriter(object): # name = conv_to_unicode(fs_top.get_filename()) # if os.path.isfile(name): # archive.add(name) - + # fs_top = gtk.FileChooserDialog("%s - GRAMPS" % _("Select file"), # buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, # gtk.STOCK_OK, Gtk.ResponseType.OK) @@ -178,8 +178,8 @@ class PackageWriter(object): log.warn(str(msg)) self.user.notify_error(_('Failure writing %s') % self.filename, str(msg)) return 0 - - # Write media files first, since the database may be modified + + # Write media files first, since the database may be modified # during the process (i.e. when removing object) for m_id in self.db.get_media_object_handles(sort_handles=True): mobject = self.db.get_object_from_handle(m_id) @@ -194,7 +194,7 @@ class PackageWriter(object): # _("Media object could not be found"), # _("%(file_name)s is referenced in the database, " # "but no longer exists. The file may have been " -# "deleted or moved to a different location. " +# "deleted or moved to a different location. " # "You may choose to either remove the reference " # "from the database, keep the reference to the " # "missing file, or select a new file." @@ -207,7 +207,7 @@ class PackageWriter(object): # leave_clicked() # elif missmedia_action == 3: # select_clicked() - + # Write XML now g = BytesIO() gfile = XmlWriter(self.db, self.user, 2) diff --git a/gramps/plugins/export/exportvcalendar.py b/gramps/plugins/export/exportvcalendar.py index 337ee6c9a..2b78523ec 100644 --- a/gramps/plugins/export/exportvcalendar.py +++ b/gramps/plugins/export/exportvcalendar.py @@ -67,18 +67,18 @@ class CalendarWriter(object): self.plist = {} self.flist = {} - + self.count = 0 self.oldval = 0 - + self.persons_details_done = [] self.persons_notes_done = [] self.person_ids = {} - + if option_box: self.option_box.parse_options() self.db = option_box.get_filtered_database(self.db) - + def update_empty(self): pass @@ -109,7 +109,7 @@ class CalendarWriter(object): self.writeln("PRODID:-//GNU//Gramps//EN") self.writeln("VERSION:1.0") - self.total = (len([x for x in self.db.iter_person_handles()]) + + self.total = (len([x for x in self.db.iter_person_handles()]) + len([x for x in self.db.iter_family_handles()])) for key in self.db.iter_person_handles(): self.write_person(key) @@ -121,10 +121,10 @@ class CalendarWriter(object): self.writeln("") self.writeln("END:VCALENDAR") - + self.g.close() return True - + def write_family(self, family_handle): family = self.db.get_family_from_handle(family_handle) if family: @@ -140,7 +140,7 @@ class CalendarWriter(object): self.write_vevent( text, m_date, place_title) else: self.write_vevent( text, m_date) - + def write_person(self, person_handle): person = self.db.get_person_from_handle(person_handle) if person: @@ -153,15 +153,15 @@ class CalendarWriter(object): if place_handle: # feature requests 2356, 1657: avoid genitive form place_title = _pd.display_event(self.db, birth) - self.write_vevent(_("Birth of %s") % - person.get_primary_name().get_name(), + self.write_vevent(_("Birth of %s") % + person.get_primary_name().get_name(), b_date, place_title) else: # feature requests 2356, 1657: avoid genitive form self.write_vevent(_("Birth of %s") % - person.get_primary_name().get_name(), + person.get_primary_name().get_name(), b_date) - + death_ref = person.get_death_ref() if death_ref: death = self.db.get_event_from_handle(death_ref.ref) @@ -171,24 +171,24 @@ class CalendarWriter(object): if place_handle: # feature requests 2356, 1657: avoid genitive form place_title = _pd.display_event(self.db, death) - self.write_vevent(_("Death of %s") % - person.get_primary_name().get_name(), - d_date, + self.write_vevent(_("Death of %s") % + person.get_primary_name().get_name(), + d_date, place_title) else: # feature requests 2356, 1657: avoid genitive form - self.write_vevent(_("Death of %s") % - person.get_primary_name().get_name(), + self.write_vevent(_("Death of %s") % + person.get_primary_name().get_name(), d_date) - + def format_single_date(self, subdate, thisyear, cal): retval = "" (day, month, year, sl) = subdate if thisyear: year = localtime().tm_year - + if not cal == Date.CAL_GREGORIAN: return "" @@ -198,7 +198,7 @@ class CalendarWriter(object): retval = "%s%02d%02d" % (year, month, day) return retval - + def format_date(self, date, thisyear=0): retval = "" if date.get_modifier() == Date.MOD_TEXTONLY: @@ -207,18 +207,18 @@ class CalendarWriter(object): mod = date.get_modifier() cal = cal = date.get_calendar() if mod == Date.MOD_SPAN or mod == Date.MOD_RANGE: - start = self.format_single_date(date.get_start_date(), + start = self.format_single_date(date.get_start_date(), thisyear, cal) - end = self.format_single_date(date.get_stop_date(), + end = self.format_single_date(date.get_stop_date(), thisyear, cal) if start and end: - retval = "DTSTART:%sT000001\nDTEND:%sT235959" % (start, + retval = "DTSTART:%sT000001\nDTEND:%sT235959" % (start, end) elif mod == Date.MOD_NONE: - start = self.format_single_date(date.get_start_date(), + start = self.format_single_date(date.get_start_date(), thisyear, cal) if start: - retval = "DTSTART:%sT000001\nDTEND:%sT235959" % (start, + retval = "DTSTART:%sT000001\nDTEND:%sT235959" % (start, start) return retval diff --git a/gramps/plugins/export/exportvcard.py b/gramps/plugins/export/exportvcard.py index 9b703e5ad..6a248dd15 100644 --- a/gramps/plugins/export/exportvcard.py +++ b/gramps/plugins/export/exportvcard.py @@ -156,8 +156,8 @@ class VCardWriter(object): for key in self.db.iter_person_handles(): self.write_person(key) self.update() - return True - + return True + def write_person(self, person_handle): """Create a VCard for the specified person.""" person = self.db.get_person_from_handle(person_handle) @@ -179,7 +179,7 @@ class VCardWriter(object): """Write the opening lines of a VCard.""" self.writeln("BEGIN:VCARD") self.writeln("VERSION:3.0") - self.writeln("PRODID:-//Gramps//NONSGML %s %s//EN" % + self.writeln("PRODID:-//Gramps//NONSGML %s %s//EN" % (PROGRAM_NAME, VERSION)) def write_footer(self): @@ -226,7 +226,7 @@ class VCardWriter(object): if len(name_list) > 1: additional_names = ','.join(self.esc(name_list[1:])) # Alternate names are ignored because names just don't add up: - # if one name is Jean and an alternate is Paul then you can't + # if one name is Jean and an alternate is Paul then you can't # conclude the Jean Paul is also an alternate name of that person. # Assume all titles/suffixes that apply are present in primary name. @@ -270,9 +270,9 @@ class VCardWriter(object): if birth: b_date = birth.get_date_object() mod = b_date.get_modifier() - if (mod != Date.MOD_TEXTONLY and - not b_date.is_empty() and - not mod == Date.MOD_SPAN and + if (mod != Date.MOD_TEXTONLY and + not b_date.is_empty() and + not mod == Date.MOD_SPAN and not mod == Date.MOD_RANGE): (day, month, year, slash) = b_date.get_start_date() if day > 0 and month > 0 and year > 0: @@ -296,7 +296,7 @@ class VCardWriter(object): phone = address.get_phone() if phone: self.writeln("TEL:%s" % phone) - + def write_urls(self, person): """Write URL and EMAIL properties of a VCard.""" url_list = person.get_url_list() diff --git a/gramps/plugins/export/exportxml.py b/gramps/plugins/export/exportxml.py index 01451d589..62ecd2ba8 100644 --- a/gramps/plugins/export/exportxml.py +++ b/gramps/plugins/export/exportxml.py @@ -81,7 +81,7 @@ except: strip_dict = dict.fromkeys(list(range(9))+list(range(11,13))+list(range(14, 32))) def escxml(d): - return escape(d, + return escape(d, {'"' : '"', '<' : '<', '>' : '>', @@ -145,7 +145,7 @@ class GrampsXmlWriter(UpdateCallback): 'Please select another directory ' 'or create it.') % base ) return 0 - + if os.path.exists(filename): if not os.access(filename, os.W_OK): raise DbWriteFailure( @@ -155,7 +155,7 @@ class GrampsXmlWriter(UpdateCallback): "Please make sure you have write access to the " "file and try again.")) return 0 - + self.fileroot = os.path.dirname(filename) try: if self.compress and _gzip_ok: @@ -196,7 +196,7 @@ class GrampsXmlWriter(UpdateCallback): self.write_xml_data() g.close() return 1 - + def write_xml_data(self): date = time.localtime(time.time()) @@ -210,16 +210,16 @@ class GrampsXmlWriter(UpdateCallback): place_len = self.db.get_number_of_places() repo_len = self.db.get_number_of_repositories() obj_len = self.db.get_number_of_media_objects() - note_len = self.db.get_number_of_notes() - tag_len = self.db.get_number_of_tags() - + note_len = self.db.get_number_of_notes() + tag_len = self.db.get_number_of_tags() + total_steps = (person_len + family_len + event_len + citation_len + source_len + place_len + repo_len + obj_len + note_len + tag_len ) self.set_total(total_steps) - + self.g.write('\n') self.g.write('\n") - + # self.status.end() # self.status = None @@ -357,7 +357,7 @@ class GrampsXmlWriter(UpdateCallback): def write_namemaps(self): group_map = self.db.get_name_group_keys() name_len = len(group_map) - + if name_len > 0: self.g.write(" \n") for key in group_map: @@ -381,7 +381,7 @@ class GrampsXmlWriter(UpdateCallback): bm_source_len + bm_place_len + bm_repo_len + bm_citation_len + bm_obj_len + bm_note_len ) - + if bm_len > 0: self.g.write(" \n") @@ -421,7 +421,7 @@ class GrampsXmlWriter(UpdateCallback): for number, name,fmt_str,active in self.db.name_formats: self.g.write('%s\n' - % (' ', number, + % (' ', number, escxml(name), escxml(fmt_str), int(active)) ) self.g.write(" \n") @@ -437,7 +437,7 @@ class GrampsXmlWriter(UpdateCallback): self.g.write(' color="%s"' % tag.get_color()) self.g.write(' priority="%d"' % tag.get_priority()) self.g.write('/>\n') - + def fix(self,line): try: l = str(line) @@ -466,7 +466,7 @@ class GrampsXmlWriter(UpdateCallback): if format != note.FLOWED: self.g.write(' format="%d"' % format) self.g.write('>\n') - + self.write_text('text', text, index + 1) if styles: @@ -476,30 +476,30 @@ class GrampsXmlWriter(UpdateCallback): self.write_ref("tagref", tag_handle, index+1) self.g.write(' ' * index + '\n') - + def write_styles(self, styles, index=3): for style in styles: name = style.name.xml_str() value = style.value - + self.g.write(' ' * index + '\n') - + def write_text(self, val, text, indent=0): if not text: return - + if indent: self.g.write(' ' * indent) - + self.g.write('<%s>' % val) self.g.write(self.fix(text.rstrip())) self.g.write("\n" % val) @@ -697,7 +697,7 @@ class GrampsXmlWriter(UpdateCallback): self.write_ref("citationref", citation_handle, index+1) self.write_note_list(nreflist,index+1) self.g.write('%s\n' % sp) - + def dump_event_ref(self,eventref,index=1): if not eventref or not eventref.ref: return @@ -760,7 +760,7 @@ class GrampsXmlWriter(UpdateCallback): self.write_line("description",event.get_description(),index+1) self.write_attribute_list(event.get_attribute_list(),index+1) self.write_note_list(event.get_note_list(),index+1) - + for citation_handle in event.get_citation_list(): self.write_ref("citationref", citation_handle, index+1) self.write_media_list(event.get_media_list(),index+1) @@ -789,7 +789,7 @@ class GrampsXmlWriter(UpdateCallback): if ord.get_status() != 0: self.g.write('%s\n' % (sp2, ord.status2xml())) if ord.get_family_handle(): - self.g.write('%s\n' % + self.g.write('%s\n' % (sp2,"_"+ord.get_family_handle())) self.write_note_list(ord.get_note_list(),index+1) for citation_handle in ord.get_citation_list(): @@ -831,9 +831,9 @@ class GrampsXmlWriter(UpdateCallback): change_text = ' change="%d"' % obj.get_change_time() except: change_text = ' change="%d"' % 0 - + handle_text = ' handle="_%s"' % obj.get_handle() - + obj_text = '%s<%s' % (sp, tagname) self.g.write(obj_text + handle_text + change_text) if close: @@ -865,7 +865,7 @@ class GrampsXmlWriter(UpdateCallback): self.g.write(' connector="%s"' % escxml(con)) if der: self.g.write(' derivation="%s"' % escxml(der)) - + self.g.write('>%s\n' % self.fix(nam)) def write_line(self,tagname,value,indent=1): @@ -874,7 +874,7 @@ class GrampsXmlWriter(UpdateCallback): (' '*indent,tagname,self.fix(value),tagname)) def write_line_nofix(self,tagname,value,indent=1): - """Writes a line, but does not escape characters. + """Writes a line, but does not escape characters. Use this instead of write_line if the value is already fixed, this avoids & becoming &amp; """ @@ -892,7 +892,7 @@ class GrampsXmlWriter(UpdateCallback): y = "????" else: y = "%04d" % date[2] - + if date[1] == 0: if date[0] == 0: m = "" @@ -927,7 +927,7 @@ class GrampsXmlWriter(UpdateCallback): qual_str = ' quality="calculated"' else: qual_str = "" - + dualdated = date.get_slash() if dualdated: dualdated_str = ' dualdated="1"' @@ -941,12 +941,12 @@ class GrampsXmlWriter(UpdateCallback): newyear_str = '' mode = date.get_modifier() - + if date.is_compound(): if mode == Date.MOD_RANGE: tagname = 'daterange' else: - tagname = 'datespan' + tagname = 'datespan' d1 = self.get_iso_date(date.get_start_date()) d2 = self.get_iso_date(date.get_stop_date()) @@ -958,7 +958,7 @@ class GrampsXmlWriter(UpdateCallback): date_str = self.get_iso_date(date.get_start_date()) if date_str == "": return - + if mode == Date.MOD_BEFORE: mode_str = ' type="before"' elif mode == Date.MOD_AFTER: @@ -1008,7 +1008,7 @@ class GrampsXmlWriter(UpdateCallback): self.write_note_list(name.get_note_list(),index+1) for citation_handle in name.get_citation_list(): self.write_ref("citationref", citation_handle, index+1) - + self.g.write('%s\n' % sp) def append_value(self, orig,val): @@ -1058,7 +1058,7 @@ class GrampsXmlWriter(UpdateCallback): country = self.fix(loc.get_country()) zip_code = self.fix(loc.get_postal_code()) phone = self.fix(loc.get_phone()) - + self.g.write(' \n' % sp) - + self.g.write('%s\n' % sp) + def write_url_list(self, list, index=1): sp = " "*index for url in list: @@ -1265,10 +1265,10 @@ class GrampsXmlWriter(UpdateCallback): path = path[1:] if win(): # Always export path with \ replaced with /. Otherwise import - # from Windows to Linux of gpkg's path to images does not work. + # from Windows to Linux of gpkg's path to images does not work. path = path.replace('\\','/') self.g.write('%s\n' - % (" "*(index+1), self.fix(path), self.fix(mime_type), + % (" "*(index+1), self.fix(path), self.fix(mime_type), checksum_text, desc_text)) self.write_attribute_list(obj.get_attribute_list()) self.write_note_list(obj.get_note_list(), index+1) diff --git a/gramps/plugins/export/test/exportvcard_test.py b/gramps/plugins/export/test/exportvcard_test.py index f952e42d4..5363bbd0b 100644 --- a/gramps/plugins/export/test/exportvcard_test.py +++ b/gramps/plugins/export/test/exportvcard_test.py @@ -25,7 +25,7 @@ import unittest import time import subprocess import os -import xml.etree.ElementTree as ET +import xml.etree.ElementTree as ET from ...lib.libgrampsxml import GRAMPS_XML_VERSION from gramps.version import VERSION @@ -33,12 +33,12 @@ from ..exportvcard import VCardWriter class VCardCheck(unittest.TestCase): def setUp(self): - self.expect = ["BEGIN:VCARD", "VERSION:3.0", - "PRODID:-//Gramps//NONSGML Gramps %s//EN" % VERSION, - "FN:Lastname", "N:Lastname;;;;", + self.expect = ["BEGIN:VCARD", "VERSION:3.0", + "PRODID:-//Gramps//NONSGML Gramps %s//EN" % VERSION, + "FN:Lastname", "N:Lastname;;;;", "SORT-STRING:" + "Lastname".ljust(55), "END:VCARD"] date = time.localtime(time.time()) - self.input_list = ["BEGIN:VCARD", "VERSION:3.0", "FN:Lastname", + self.input_list = ["BEGIN:VCARD", "VERSION:3.0", "FN:Lastname", "N:Lastname;;;;", "END:VCARD"] self.header = """ 0) - + def display_report(self, treeview): """ Display the quick report for matching attribute key. @@ -62,16 +62,16 @@ class Attributes(Gramplet): model, iter_ = treeview.get_selection().get_selected() if iter_: key = model.get_value(iter_, 0) - run_quick_report_by_name(self.dbstate, - self.uistate, - 'attribute_match', + run_quick_report_by_name(self.dbstate, + self.uistate, + 'attribute_match', key) def get_has_data(self, obj): """ Return True if the gramplet has data, else return False. """ - if obj is None: + if obj is None: return False if obj.get_attribute_list(): return True @@ -94,7 +94,7 @@ class PersonAttributes(Attributes): self.set_has_data(self.get_has_data(active)) else: self.set_has_data(False) - + def main(self): self.model.clear() active_handle = self.get_active('Person') @@ -122,7 +122,7 @@ class EventAttributes(Attributes): self.set_has_data(self.get_has_data(active)) else: self.set_has_data(False) - + def main(self): self.model.clear() active_handle = self.get_active('Event') @@ -150,7 +150,7 @@ class FamilyAttributes(Attributes): self.set_has_data(self.get_has_data(active)) else: self.set_has_data(False) - + def main(self): self.model.clear() active_handle = self.get_active('Family') @@ -178,7 +178,7 @@ class MediaAttributes(Attributes): self.set_has_data(self.get_has_data(active)) else: self.set_has_data(False) - + def main(self): self.model.clear() active_handle = self.get_active('Media') diff --git a/gramps/plugins/gramplet/backlinks.py b/gramps/plugins/gramplet/backlinks.py index 81c1f207e..0fdb26786 100644 --- a/gramps/plugins/gramplet/backlinks.py +++ b/gramps/plugins/gramplet/backlinks.py @@ -44,10 +44,10 @@ class Backlinks(Gramplet): titles = [(_('Type'), 1, 100), (_('Name'), 2, 100), ('', 3, 1), #hidden column for the handle - ('', 4, 1)] #hidden column for non-localized object type + ('', 4, 1)] #hidden column for non-localized object type self.model = ListModel(top, titles, event_func=self.cb_double_click) return top - + def display_backlinks(self, active_handle): """ Display the back references for an object. @@ -67,7 +67,7 @@ class Backlinks(Gramplet): for handle in self.dbstate.db.find_backlink_handles(active_handle): return True return False - + def cb_double_click(self, treeview): """ Handle double click on treeview. @@ -76,7 +76,7 @@ class Backlinks(Gramplet): if not iter_: return - (objclass, handle) = (model.get_value(iter_, 3), + (objclass, handle) = (model.get_value(iter_, 3), model.get_value(iter_, 2)) edit_object(self.dbstate, self.uistate, objclass, handle) @@ -94,7 +94,7 @@ class PersonBacklinks(Backlinks): def update_has_data(self): active_handle = self.get_active('Person') self.set_has_data(self.get_has_data(active_handle)) - + def main(self): active_handle = self.get_active('Person') self.model.clear() @@ -114,7 +114,7 @@ class EventBacklinks(Backlinks): def update_has_data(self): active_handle = self.get_active('Event') self.set_has_data(self.get_has_data(active_handle)) - + def main(self): active_handle = self.get_active('Event') self.model.clear() @@ -134,7 +134,7 @@ class FamilyBacklinks(Backlinks): def update_has_data(self): active_handle = self.get_active('Family') self.set_has_data(self.get_has_data(active_handle)) - + def main(self): active_handle = self.get_active('Family') self.model.clear() @@ -154,7 +154,7 @@ class PlaceBacklinks(Backlinks): def update_has_data(self): active_handle = self.get_active('Place') self.set_has_data(self.get_has_data(active_handle)) - + def main(self): active_handle = self.get_active('Place') self.model.clear() @@ -174,7 +174,7 @@ class SourceBacklinks(Backlinks): def update_has_data(self): active_handle = self.get_active('Source') self.set_has_data(self.get_has_data(active_handle)) - + def main(self): active_handle = self.get_active('Source') self.model.clear() @@ -194,7 +194,7 @@ class CitationBacklinks(Backlinks): def update_has_data(self): active_handle = self.get_active('Citation') self.set_has_data(self.get_has_data(active_handle)) - + def main(self): active_handle = self.get_active('Citation') self.model.clear() @@ -214,7 +214,7 @@ class RepositoryBacklinks(Backlinks): def update_has_data(self): active_handle = self.get_active('Repository') self.set_has_data(self.get_has_data(active_handle)) - + def main(self): active_handle = self.get_active('Repository') self.model.clear() @@ -234,7 +234,7 @@ class MediaBacklinks(Backlinks): def update_has_data(self): active_handle = self.get_active('Media') self.set_has_data(self.get_has_data(active_handle)) - + def main(self): active_handle = self.get_active('Media') self.model.clear() @@ -254,7 +254,7 @@ class NoteBacklinks(Backlinks): def update_has_data(self): active_handle = self.get_active('Note') self.set_has_data(self.get_has_data(active_handle)) - + def main(self): active_handle = self.get_active('Note') self.model.clear() diff --git a/gramps/plugins/gramplet/calendargramplet.py b/gramps/plugins/gramplet/calendargramplet.py index 1cedd4deb..917f2effb 100644 --- a/gramps/plugins/gramplet/calendargramplet.py +++ b/gramps/plugins/gramplet/calendargramplet.py @@ -55,7 +55,7 @@ class CalendarGramplet(Gramplet): year, month, day = self.gui.calendar.get_date() date = Date() date.set_yr_mon_day(year, month + 1, day) - run_quick_report_by_name(self.gui.dbstate, - self.gui.uistate, - 'onthisday', + run_quick_report_by_name(self.gui.dbstate, + self.gui.uistate, + 'onthisday', date) diff --git a/gramps/plugins/gramplet/citations.py b/gramps/plugins/gramplet/citations.py index b40087d85..f7d870cae 100644 --- a/gramps/plugins/gramplet/citations.py +++ b/gramps/plugins/gramplet/citations.py @@ -48,7 +48,7 @@ class Citations(Gramplet, DbGUIElement): """ self.callman.register_callbacks({'citation-update': self.changed}) self.callman.connect_all(keys=['citation']) - + def changed(self, handle): """ Called when a registered citation is updated. @@ -66,14 +66,14 @@ class Citations(Gramplet, DbGUIElement): (_('Source/Citation'), 1, 350), (_('Author'), 2, 200), (_('Publisher'), 3, 150)] - self.model = ListModel(top, titles, list_mode="tree", + self.model = ListModel(top, titles, list_mode="tree", event_func=self.invoke_editor) return top - + def add_citations(self, obj): for citation_handle in obj.get_citation_list(): self.add_citation_ref(citation_handle) - + def add_name_citations(self, obj): names = [obj.get_primary_name()] + obj.get_alternate_names() for name in names: @@ -147,13 +147,13 @@ class Citations(Gramplet, DbGUIElement): if source_handle not in self.source_nodes: node = self.model.add([source_handle, title, author, publisher]) self.source_nodes[source_handle] = node - - self.model.add([citation_handle, page, '', ''], + + self.model.add([citation_handle, page, '', ''], node=self.source_nodes[source_handle]) def check_citations(self, obj): return True if obj.get_citation_list() else False - + def check_name_citations(self, obj): names = [obj.get_primary_name()] + obj.get_alternate_names() for name in names: diff --git a/gramps/plugins/gramplet/descendant.py b/gramps/plugins/gramplet/descendant.py index 78530645f..b0e941630 100644 --- a/gramps/plugins/gramplet/descendant.py +++ b/gramps/plugins/gramplet/descendant.py @@ -69,7 +69,7 @@ class Descendant(Gramplet): ('', NOSORT, 1), ('', NOSORT, 1), # tooltip ('', NOSORT, 100)] # handle - self.model = ListModel(self.view, titles, list_mode="tree", + self.model = ListModel(self.view, titles, list_mode="tree", event_func=self.cb_double_click, right_click=self.cb_right_click) return self.view @@ -87,7 +87,7 @@ class Descendant(Gramplet): for child_ref in family.get_child_ref_list(): return True return False - + def cb_double_click(self, treeview): """ Handle double click on treeview. @@ -143,7 +143,7 @@ class Descendant(Gramplet): self.set_has_data(self.get_has_data(active_handle)) else: self.set_has_data(False) - + def main(self): active_handle = self.get_active('Person') self.model.clear() @@ -166,7 +166,7 @@ class Descendant(Gramplet): birth_date = get_date(birth) birth_sort = '%012d' % birth.get_date_object().get_sort_value() birth_text = _('%(abbr)s %(date)s') % \ - {'abbr': birth.type.get_abbreviation(), + {'abbr': birth.type.get_abbreviation(), 'date': birth_date} death_date = death_sort = death_text = '' @@ -174,12 +174,12 @@ class Descendant(Gramplet): death_date = get_date(death) death_sort = '%012d' % death.get_date_object().get_sort_value() death_text = _('%(abbr)s %(date)s') % \ - {'abbr': death.type.get_abbreviation(), + {'abbr': death.type.get_abbreviation(), 'date': death_date} tooltip = name + '\n' + birth_text + '\n' + death_text - item_id = self.model.add([name, birth_date, birth_sort, + item_id = self.model.add([name, birth_date, birth_sort, tooltip, person_handle], node=parent_id) for family_handle in person.get_family_handle_list(): diff --git a/gramps/plugins/gramplet/eval.py b/gramps/plugins/gramplet/eval.py index f52cdc9f7..366f663ff 100644 --- a/gramps/plugins/gramplet/eval.py +++ b/gramps/plugins/gramplet/eval.py @@ -72,7 +72,7 @@ class PythonEvaluation(Gramplet): self.ebuf = self.__add_text_view(_("Evaluation")) self.dbuf = self.__add_text_view(_("Output")) self.error = self.__add_text_view(_("Error")) - + bbox = Gtk.ButtonBox() apply_button = Gtk.Button(label=_("Apply")) apply_button.connect('clicked', self.apply_clicked) @@ -81,7 +81,7 @@ class PythonEvaluation(Gramplet): clear_button.connect('clicked', self.clear_clicked) bbox.pack_start(clear_button, False, False, 6) self.top.pack_start(bbox, False, False, 6) - + self.top.show_all() return self.top diff --git a/gramps/plugins/gramplet/events.py b/gramps/plugins/gramplet/events.py index ad20f2556..398e9d84f 100644 --- a/gramps/plugins/gramplet/events.py +++ b/gramps/plugins/gramplet/events.py @@ -83,7 +83,7 @@ class Events(Gramplet, DbGUIElement): (_('Role'), 7, 100)] self.model = ListModel(top, titles, event_func=self.edit_event) return top - + def add_event_ref(self, event_ref, spouse=None): """ Add an event to the model. @@ -181,7 +181,7 @@ class PersonEvents(Events): def main(self): # return false finishes active_handle = self.get_active('Person') - + self.model.clear() self.callman.unregister_all() if active_handle: @@ -246,7 +246,7 @@ class FamilyEvents(Events): def main(self): # return false finishes active_handle = self.get_active('Family') - + self.model.clear() self.callman.unregister_all() if active_handle: diff --git a/gramps/plugins/gramplet/fanchartdescgramplet.py b/gramps/plugins/gramplet/fanchartdescgramplet.py index f5bee81d0..b5b0c003d 100644 --- a/gramps/plugins/gramplet/fanchartdescgramplet.py +++ b/gramps/plugins/gramplet/fanchartdescgramplet.py @@ -51,7 +51,7 @@ from gramps.gui.widgets.fanchart import FORM_HALFCIRCLE, BACKGROUND_SCHEME1 class FanChartDescGramplet(FanChartDescGrampsGUI, Gramplet): """ - The Gramplet code that realizes the FanChartWidget. + The Gramplet code that realizes the FanChartWidget. """ def __init__(self, gui, nav_group=0): diff --git a/gramps/plugins/gramplet/fanchartgramplet.py b/gramps/plugins/gramplet/fanchartgramplet.py index 855073e1f..1c82dcabb 100644 --- a/gramps/plugins/gramplet/fanchartgramplet.py +++ b/gramps/plugins/gramplet/fanchartgramplet.py @@ -56,7 +56,7 @@ from gramps.gui.widgets.fanchart import (FanChartWidget, FanChartGrampsGUI, class FanChartGramplet(FanChartGrampsGUI, Gramplet): """ - The Gramplet code that realizes the FanChartWidget. + The Gramplet code that realizes the FanChartWidget. """ def __init__(self, gui, nav_group=0): diff --git a/gramps/plugins/gramplet/filter.py b/gramps/plugins/gramplet/filter.py index 8a7f9d76e..f03264d3a 100644 --- a/gramps/plugins/gramplet/filter.py +++ b/gramps/plugins/gramplet/filter.py @@ -41,11 +41,11 @@ class Filter(Gramplet): The base class for all filter gramplets. """ FILTER_CLASS = None - + def init(self): self.filter = self.FILTER_CLASS(self.dbstate, self.uistate, self.__filter_clicked) - self.widget = self.filter.get_widget() + self.widget = self.filter.get_widget() self.gui.get_container_widget().remove(self.gui.textview) self.gui.get_container_widget().add(self.widget) self.widget.show_all() @@ -144,7 +144,7 @@ class RepositoryFilter(Filter): A gramplet providing a Repository Filter. """ FILTER_CLASS = RepoSidebarFilter - + #------------------------------------------------------------------------- # # NoteFilter class diff --git a/gramps/plugins/gramplet/gallery.py b/gramps/plugins/gramplet/gallery.py index dd6eb43ad..5db89da15 100644 --- a/gramps/plugins/gramplet/gallery.py +++ b/gramps/plugins/gramplet/gallery.py @@ -39,7 +39,7 @@ class Gallery(Gramplet): self.image_list = [] self.top = Gtk.Box(spacing=3) return self.top - + def clear_images(self): """ Remove all images from the Gramplet. @@ -73,7 +73,7 @@ class Gallery(Gramplet): """ Return True if the gramplet has data, else return False. """ - if obj is None: + if obj is None: return False media_list = obj.get_media_list() for media_ref in media_list: diff --git a/gramps/plugins/gramplet/givennamegramplet.py b/gramps/plugins/gramplet/givennamegramplet.py index 9e5fee9a0..f9605b411 100644 --- a/gramps/plugins/gramplet/givennamegramplet.py +++ b/gramps/plugins/gramplet/givennamegramplet.py @@ -1,6 +1,6 @@ # Gramps - a GTK+/GNOME based genealogy program # -# Copyright (C) 2009 Pander Musubi +# Copyright (C) 2009 Pander Musubi # Copyright (C) 2009 Douglas S. Blank # # This program is free software; you can redistribute it and/or modify @@ -81,7 +81,7 @@ class GivenNameCloudGramplet(Gramplet): total_people = cnt givensubname_sort = [] - + total = cnt = 0 for givensubname in givensubnames: givensubname_sort.append( (givensubnames[givensubname], givensubname) ) @@ -128,14 +128,14 @@ class GivenNameCloudGramplet(Gramplet): text = givensubname size = make_tag_size(count, counts) self.link(text, 'Given', text, size, - "%s, %.2f%% (%d)" % - (text, - (float(count)/total_people) * 100, + "%s, %.2f%% (%d)" % + (text, + (float(count)/total_people) * 100, count)) self.append_text(" ") showing += 1 - self.append_text(("\n\n" + _("Total unique given names") + ": %d\n") % + self.append_text(("\n\n" + _("Total unique given names") + ": %d\n") % total_givensubnames) self.append_text((_("Total given names showing") + ": %d\n") % showing) self.append_text((_("Total people") + ": %d") % total_people, "begin") diff --git a/gramps/plugins/gramplet/gramplet.gpr.py b/gramps/plugins/gramplet/gramplet.gpr.py index 3ffc62306..4f10e3d24 100644 --- a/gramps/plugins/gramplet/gramplet.gpr.py +++ b/gramps/plugins/gramplet/gramplet.gpr.py @@ -21,7 +21,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # @@ -37,9 +37,9 @@ _ = glocale.translation.sgettext # Register Gramplet # #------------------------------------------------------------------------ -register(GRAMPLET, - id="Age on Date", - name=_("Age on Date"), +register(GRAMPLET, + id="Age on Date", + name=_("Age on Date"), description = _("Gramplet showing ages of living people on a specific date"), version="2.0.0", gramps_target_version=MODULE_VERSION, @@ -50,7 +50,7 @@ register(GRAMPLET, gramplet_title=_("Age on Date"), ) -register(GRAMPLET, +register(GRAMPLET, id = "Age Stats", name = _("Age Stats"), description = _("Gramplet showing graphs of various ages"), @@ -66,9 +66,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id="Calendar", - name=_("Calendar"), +register(GRAMPLET, + id="Calendar", + name=_("Calendar"), description = _("Gramplet showing calendar and events on specific dates in history"), status = STABLE, fname="calendargramplet.py", @@ -79,9 +79,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id = "Descendant", - name=_("Descendant"), +register(GRAMPLET, + id = "Descendant", + name=_("Descendant"), description = _("Gramplet showing active person's descendants"), status = STABLE, fname="descendant.py", @@ -96,9 +96,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id = "Ancestor", - name=_("Ancestor"), +register(GRAMPLET, + id = "Ancestor", + name=_("Ancestor"), description = _("Gramplet showing active person's ancestors"), status = STABLE, fname="ancestor.py", @@ -113,9 +113,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id= "Fan Chart", - name=_("Fan Chart"), +register(GRAMPLET, + id= "Fan Chart", + name=_("Fan Chart"), description = _("Gramplet showing active person's direct ancestors as a fanchart"), status = STABLE, fname="fanchartgramplet.py", @@ -130,9 +130,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id= "Descendant Fan Chart", - name=_("Descendant Fan Chart"), +register(GRAMPLET, + id= "Descendant Fan Chart", + name=_("Descendant Fan Chart"), description = _("Gramplet showing active person's direct descendants as a fanchart"), status = STABLE, fname="fanchartdescgramplet.py", @@ -147,9 +147,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="FAQ", - name=_("FAQ"), +register(GRAMPLET, + id="FAQ", + name=_("FAQ"), description = _("Gramplet showing frequently asked questions"), status = STABLE, fname="faqgramplet.py", @@ -160,9 +160,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id= "Given Name Cloud", - name=_("Given Name Cloud"), +register(GRAMPLET, + id= "Given Name Cloud", + name=_("Given Name Cloud"), description = _("Gramplet showing all given names as a text cloud"), status = STABLE, fname="givennamegramplet.py", @@ -174,9 +174,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id="Pedigree", - name=_("Pedigree"), +register(GRAMPLET, + id="Pedigree", + name=_("Pedigree"), description = _("Gramplet showing active person's ancestors"), status = STABLE, fname="pedigreegramplet.py", @@ -191,9 +191,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Quick View", - name=_("Quick View"), +register(GRAMPLET, + id="Quick View", + name=_("Quick View"), description = _("Gramplet showing an active item Quick View"), status = STABLE, fname="quickviewgramplet.py", @@ -207,9 +207,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id="Relatives", - name=_("Relatives"), +register(GRAMPLET, + id="Relatives", + name=_("Relatives"), description = _("Gramplet showing active person's relatives"), status = STABLE, fname="relativegramplet.py", @@ -223,9 +223,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Session Log", - name=_("Session Log"), +register(GRAMPLET, + id="Session Log", + name=_("Session Log"), description = _("Gramplet showing all activity for this session"), status = STABLE, fname="sessionloggramplet.py", @@ -237,9 +237,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id="Statistics", - name=_("Statistics"), +register(GRAMPLET, + id="Statistics", + name=_("Statistics"), description = _("Gramplet showing summary data of the Family Tree"), status = STABLE, fname="statsgramplet.py", @@ -251,9 +251,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id= "Surname Cloud", - name=_("Surname Cloud"), +register(GRAMPLET, + id= "Surname Cloud", + name=_("Surname Cloud"), description = _("Gramplet showing all surnames as a text cloud"), status = STABLE, fname="surnamecloudgramplet.py", @@ -265,9 +265,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id="To Do", - name=_("gramplet|To Do"), +register(GRAMPLET, + id="To Do", + name=_("gramplet|To Do"), description = _("Gramplet for displaying a To Do list"), status = STABLE, fname="todogramplet.py", @@ -280,9 +280,9 @@ register(GRAMPLET, navtypes=["Dashboard"], ) -register(GRAMPLET, - id= "Top Surnames", - name=_("Top Surnames"), +register(GRAMPLET, + id= "Top Surnames", + name=_("Top Surnames"), description = _("Gramplet showing most frequent surnames in this tree"), status = STABLE, fname="topsurnamesgramplet.py", @@ -293,9 +293,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id="Welcome", - name=_("Welcome"), +register(GRAMPLET, + id="Welcome", + name=_("Welcome"), description = _("Gramplet showing a welcome message"), status = STABLE, fname="welcomegramplet.py", @@ -307,9 +307,9 @@ register(GRAMPLET, gramps_target_version=MODULE_VERSION, ) -register(GRAMPLET, - id = "What's Next", - name =_("What's Next"), +register(GRAMPLET, + id = "What's Next", + name =_("What's Next"), description = _("Gramplet suggesting items to research"), status = STABLE, fname="whatsnext.py", @@ -324,9 +324,9 @@ register(GRAMPLET, #------------------------------------------------------------------------ # Bottombar #------------------------------------------------------------------------ -register(GRAMPLET, - id="Person Details", - name=_("Person Details"), +register(GRAMPLET, + id="Person Details", + name=_("Person Details"), description = _("Gramplet showing details of a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -338,9 +338,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Repository Details", - name=_("Repository Details"), +register(GRAMPLET, + id="Repository Details", + name=_("Repository Details"), description = _("Gramplet showing details of a repository"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -352,9 +352,9 @@ register(GRAMPLET, navtypes=["Repository"], ) -register(GRAMPLET, - id="Place Details", - name=_("Place Details"), +register(GRAMPLET, + id="Place Details", + name=_("Place Details"), description = _("Gramplet showing details of a place"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -366,9 +366,9 @@ register(GRAMPLET, navtypes=["Place"], ) -register(GRAMPLET, - id="Media Preview", - name=_("Media Preview"), +register(GRAMPLET, + id="Media Preview", + name=_("Media Preview"), description = _("Gramplet showing a preview of a media object"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -392,9 +392,9 @@ except ImportError: available = False if available: - register(GRAMPLET, - id = "Metadata Viewer", - name = _("Metadata Viewer"), + register(GRAMPLET, + id = "Metadata Viewer", + name = _("Metadata Viewer"), description = _("Gramplet showing metadata for a media object"), version = "1.0.0", gramps_target_version=MODULE_VERSION, @@ -413,7 +413,7 @@ else: from gramps.gui.dialog import MessageHideDialog from gramps.gen.const import URL_WIKISTRING gexiv2_dict = { 'gramps_wiki_build_gexiv2_url' : - URL_WIKISTRING + + URL_WIKISTRING + "GEPS_029:_GTK3-GObject_introspection" "_Conversion#GExiv2_for_Image_metadata" } title = _("GExiv2 module not loaded.") @@ -422,9 +422,9 @@ else: "%(gramps_wiki_build_gexiv2_url)s" % gexiv2_dict ) MessageHideDialog(title, message, 'interface.ignore-gexiv2') -register(GRAMPLET, - id="Person Residence", - name=_("Person Residence"), +register(GRAMPLET, + id="Person Residence", + name=_("Person Residence"), description = _("Gramplet showing residence events for a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -436,9 +436,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Person Events", - name=_("Person Events"), +register(GRAMPLET, + id="Person Events", + name=_("Person Events"), description = _("Gramplet showing the events for a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -450,9 +450,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Family Events", - name=_("Family Events"), +register(GRAMPLET, + id="Family Events", + name=_("Family Events"), description = _("Gramplet showing the events for a family"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -464,9 +464,9 @@ register(GRAMPLET, navtypes=["Family"], ) -register(GRAMPLET, - id="Person Gallery", - name=_("Person Gallery"), +register(GRAMPLET, + id="Person Gallery", + name=_("Person Gallery"), description = _("Gramplet showing media objects for a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -478,9 +478,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Family Gallery", - name=_("Family Gallery"), +register(GRAMPLET, + id="Family Gallery", + name=_("Family Gallery"), description = _("Gramplet showing media objects for a family"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -492,9 +492,9 @@ register(GRAMPLET, navtypes=["Family"], ) -register(GRAMPLET, - id="Event Gallery", - name=_("Event Gallery"), +register(GRAMPLET, + id="Event Gallery", + name=_("Event Gallery"), description = _("Gramplet showing media objects for an event"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -506,9 +506,9 @@ register(GRAMPLET, navtypes=["Event"], ) -register(GRAMPLET, - id="Place Gallery", - name=_("Place Gallery"), +register(GRAMPLET, + id="Place Gallery", + name=_("Place Gallery"), description = _("Gramplet showing media objects for a place"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -520,9 +520,9 @@ register(GRAMPLET, navtypes=["Place"], ) -register(GRAMPLET, - id="Source Gallery", - name=_("Source Gallery"), +register(GRAMPLET, + id="Source Gallery", + name=_("Source Gallery"), description = _("Gramplet showing media objects for a source"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -534,9 +534,9 @@ register(GRAMPLET, navtypes=["Source"], ) -register(GRAMPLET, - id="Citation Gallery", - name=_("Citation Gallery"), +register(GRAMPLET, + id="Citation Gallery", + name=_("Citation Gallery"), description = _("Gramplet showing media objects for a citation"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -548,9 +548,9 @@ register(GRAMPLET, navtypes=["Citation"], ) -register(GRAMPLET, - id="Person Attributes", - name=_("Person Attributes"), +register(GRAMPLET, + id="Person Attributes", + name=_("Person Attributes"), description = _("Gramplet showing the attributes of a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -562,9 +562,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Event Attributes", - name=_("Event Attributes"), +register(GRAMPLET, + id="Event Attributes", + name=_("Event Attributes"), description = _("Gramplet showing the attributes of an event"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -576,9 +576,9 @@ register(GRAMPLET, navtypes=["Event"], ) -register(GRAMPLET, - id="Family Attributes", - name=_("Family Attributes"), +register(GRAMPLET, + id="Family Attributes", + name=_("Family Attributes"), description = _("Gramplet showing the attributes of a family"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -590,9 +590,9 @@ register(GRAMPLET, navtypes=["Family"], ) -register(GRAMPLET, - id="Media Attributes", - name=_("Media Attributes"), +register(GRAMPLET, + id="Media Attributes", + name=_("Media Attributes"), description = _("Gramplet showing the attributes of a media object"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -632,9 +632,9 @@ register(GRAMPLET, navtypes=["Citation"], ) -register(GRAMPLET, - id="Person Notes", - name=_("Person Notes"), +register(GRAMPLET, + id="Person Notes", + name=_("Person Notes"), description = _("Gramplet showing the notes for a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -646,9 +646,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Event Notes", - name=_("Event Notes"), +register(GRAMPLET, + id="Event Notes", + name=_("Event Notes"), description = _("Gramplet showing the notes for an event"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -660,9 +660,9 @@ register(GRAMPLET, navtypes=["Event"], ) -register(GRAMPLET, - id="Family Notes", - name=_("Family Notes"), +register(GRAMPLET, + id="Family Notes", + name=_("Family Notes"), description = _("Gramplet showing the notes for a family"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -674,9 +674,9 @@ register(GRAMPLET, navtypes=["Family"], ) -register(GRAMPLET, - id="Place Notes", - name=_("Place Notes"), +register(GRAMPLET, + id="Place Notes", + name=_("Place Notes"), description = _("Gramplet showing the notes for a place"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -688,9 +688,9 @@ register(GRAMPLET, navtypes=["Place"], ) -register(GRAMPLET, - id="Source Notes", - name=_("Source Notes"), +register(GRAMPLET, + id="Source Notes", + name=_("Source Notes"), description = _("Gramplet showing the notes for a source"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -702,9 +702,9 @@ register(GRAMPLET, navtypes=["Source"], ) -register(GRAMPLET, - id="Citation Notes", - name=_("Citation Notes"), +register(GRAMPLET, + id="Citation Notes", + name=_("Citation Notes"), description = _("Gramplet showing the notes for a citation"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -716,9 +716,9 @@ register(GRAMPLET, navtypes=["Citation"], ) -register(GRAMPLET, - id="Repository Notes", - name=_("Repository Notes"), +register(GRAMPLET, + id="Repository Notes", + name=_("Repository Notes"), description = _("Gramplet showing the notes for a repository"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -730,9 +730,9 @@ register(GRAMPLET, navtypes=["Repository"], ) -register(GRAMPLET, - id="Media Notes", - name=_("Media Notes"), +register(GRAMPLET, + id="Media Notes", + name=_("Media Notes"), description = _("Gramplet showing the notes for a media object"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -744,9 +744,9 @@ register(GRAMPLET, navtypes=["Media"], ) -register(GRAMPLET, - id="Person Citations", - name=_("Person Citations"), +register(GRAMPLET, + id="Person Citations", + name=_("Person Citations"), description = _("Gramplet showing the citations for a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -758,9 +758,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Event Citations", - name=_("Event Citations"), +register(GRAMPLET, + id="Event Citations", + name=_("Event Citations"), description = _("Gramplet showing the citations for an event"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -772,9 +772,9 @@ register(GRAMPLET, navtypes=["Event"], ) -register(GRAMPLET, - id="Family Citations", - name=_("Family Citations"), +register(GRAMPLET, + id="Family Citations", + name=_("Family Citations"), description = _("Gramplet showing the citations for a family"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -786,9 +786,9 @@ register(GRAMPLET, navtypes=["Family"], ) -register(GRAMPLET, - id="Place Citations", - name=_("Place Citations"), +register(GRAMPLET, + id="Place Citations", + name=_("Place Citations"), description = _("Gramplet showing the citations for a place"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -800,9 +800,9 @@ register(GRAMPLET, navtypes=["Place"], ) -register(GRAMPLET, - id="Media Citations", - name=_("Media Citations"), +register(GRAMPLET, + id="Media Citations", + name=_("Media Citations"), description = _("Gramplet showing the citations for a media object"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -814,9 +814,9 @@ register(GRAMPLET, navtypes=["Media"], ) -register(GRAMPLET, - id="Person Children", - name=_("Person Children"), +register(GRAMPLET, + id="Person Children", + name=_("Person Children"), description = _("Gramplet showing the children of a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -828,9 +828,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Family Children", - name=_("Family Children"), +register(GRAMPLET, + id="Family Children", + name=_("Family Children"), description = _("Gramplet showing the children of a family"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -842,9 +842,9 @@ register(GRAMPLET, navtypes=["Family"], ) -register(GRAMPLET, - id="Person Backlinks", - name=_("Person Backlinks"), +register(GRAMPLET, + id="Person Backlinks", + name=_("Person Backlinks"), description = _("Gramplet showing the backlinks for a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -856,9 +856,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Event Backlinks", - name=_("Event Backlinks"), +register(GRAMPLET, + id="Event Backlinks", + name=_("Event Backlinks"), description = _("Gramplet showing the backlinks for an event"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -870,9 +870,9 @@ register(GRAMPLET, navtypes=["Event"], ) -register(GRAMPLET, - id="Family Backlinks", - name=_("Family Backlinks"), +register(GRAMPLET, + id="Family Backlinks", + name=_("Family Backlinks"), description = _("Gramplet showing the backlinks for a family"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -884,9 +884,9 @@ register(GRAMPLET, navtypes=["Family"], ) -register(GRAMPLET, - id="Place Backlinks", - name=_("Place Backlinks"), +register(GRAMPLET, + id="Place Backlinks", + name=_("Place Backlinks"), description = _("Gramplet showing the backlinks for a place"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -898,9 +898,9 @@ register(GRAMPLET, navtypes=["Place"], ) -register(GRAMPLET, - id="Source Backlinks", - name=_("Source Backlinks"), +register(GRAMPLET, + id="Source Backlinks", + name=_("Source Backlinks"), description = _("Gramplet showing the backlinks for a source"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -912,9 +912,9 @@ register(GRAMPLET, navtypes=["Source"], ) -register(GRAMPLET, - id="Citation Backlinks", - name=_("Citation Backlinks"), +register(GRAMPLET, + id="Citation Backlinks", + name=_("Citation Backlinks"), description = _("Gramplet showing the backlinks for a citation"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -926,9 +926,9 @@ register(GRAMPLET, navtypes=["Citation"], ) -register(GRAMPLET, - id="Repository Backlinks", - name=_("Repository Backlinks"), +register(GRAMPLET, + id="Repository Backlinks", + name=_("Repository Backlinks"), description = _("Gramplet showing the backlinks for a repository"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -940,9 +940,9 @@ register(GRAMPLET, navtypes=["Repository"], ) -register(GRAMPLET, - id="Media Backlinks", - name=_("Media Backlinks"), +register(GRAMPLET, + id="Media Backlinks", + name=_("Media Backlinks"), description = _("Gramplet showing the backlinks for a media object"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -954,9 +954,9 @@ register(GRAMPLET, navtypes=["Media"], ) -register(GRAMPLET, - id="Note Backlinks", - name=_("Note Backlinks"), +register(GRAMPLET, + id="Note Backlinks", + name=_("Note Backlinks"), description = _("Gramplet showing the backlinks for a note"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -968,9 +968,9 @@ register(GRAMPLET, navtypes=["Note"], ) -register(GRAMPLET, - id="Person Filter", - name=_("Person Filter"), +register(GRAMPLET, + id="Person Filter", + name=_("Person Filter"), description = _("Gramplet providing a person filter"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -982,9 +982,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Family Filter", - name=_("Family Filter"), +register(GRAMPLET, + id="Family Filter", + name=_("Family Filter"), description = _("Gramplet providing a family filter"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -996,9 +996,9 @@ register(GRAMPLET, navtypes=["Family"], ) -register(GRAMPLET, - id="Event Filter", - name=_("Event Filter"), +register(GRAMPLET, + id="Event Filter", + name=_("Event Filter"), description = _("Gramplet providing an event filter"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1010,9 +1010,9 @@ register(GRAMPLET, navtypes=["Event"], ) -register(GRAMPLET, - id="Source Filter", - name=_("Source Filter"), +register(GRAMPLET, + id="Source Filter", + name=_("Source Filter"), description = _("Gramplet providing a source filter"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1024,9 +1024,9 @@ register(GRAMPLET, navtypes=["Source"], ) -register(GRAMPLET, - id="Citation Filter", - name=_("Citation Filter"), +register(GRAMPLET, + id="Citation Filter", + name=_("Citation Filter"), description = _("Gramplet providing a citation filter"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1038,9 +1038,9 @@ register(GRAMPLET, navtypes=["Citation"], ) -register(GRAMPLET, - id="Place Filter", - name=_("Place Filter"), +register(GRAMPLET, + id="Place Filter", + name=_("Place Filter"), description = _("Gramplet providing a place filter"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1052,9 +1052,9 @@ register(GRAMPLET, navtypes=["Place"], ) -register(GRAMPLET, - id="Media Filter", - name=_("Media Filter"), +register(GRAMPLET, + id="Media Filter", + name=_("Media Filter"), description = _("Gramplet providing a media filter"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1066,9 +1066,9 @@ register(GRAMPLET, navtypes=["Media"], ) -register(GRAMPLET, - id="Repository Filter", - name=_("Repository Filter"), +register(GRAMPLET, + id="Repository Filter", + name=_("Repository Filter"), description = _("Gramplet providing a repository filter"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1080,9 +1080,9 @@ register(GRAMPLET, navtypes=["Repository"], ) -register(GRAMPLET, - id="Note Filter", - name=_("Note Filter"), +register(GRAMPLET, + id="Note Filter", + name=_("Note Filter"), description = _("Gramplet providing a note filter"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1094,7 +1094,7 @@ register(GRAMPLET, navtypes=["Note"], ) -register(GRAMPLET, +register(GRAMPLET, id='Records Gramplet', name=_("Records Gramplet"), description=_("Shows some interesting records about people and families"), @@ -1110,9 +1110,9 @@ register(GRAMPLET, gramplet_title=_("Records") ) -register(GRAMPLET, - id="Person To Do", - name=_("Person To Do"), +register(GRAMPLET, + id="Person To Do", + name=_("Person To Do"), description = _("Gramplet showing the To Do notes for a person"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1124,9 +1124,9 @@ register(GRAMPLET, navtypes=["Person"], ) -register(GRAMPLET, - id="Event To Do", - name=_("Event To Do"), +register(GRAMPLET, + id="Event To Do", + name=_("Event To Do"), description = _("Gramplet showing the To Do notes for an event"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1138,9 +1138,9 @@ register(GRAMPLET, navtypes=["Event"], ) -register(GRAMPLET, - id="Family To Do", - name=_("Family To Do"), +register(GRAMPLET, + id="Family To Do", + name=_("Family To Do"), description = _("Gramplet showing the To Do notes for a family"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1152,9 +1152,9 @@ register(GRAMPLET, navtypes=["Family"], ) -register(GRAMPLET, - id="Place To Do", - name=_("Place To Do"), +register(GRAMPLET, + id="Place To Do", + name=_("Place To Do"), description = _("Gramplet showing the To Do notes for a place"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1166,9 +1166,9 @@ register(GRAMPLET, navtypes=["Place"], ) -register(GRAMPLET, - id="Source To Do", - name=_("Source To Do"), +register(GRAMPLET, + id="Source To Do", + name=_("Source To Do"), description = _("Gramplet showing the To Do notes for a source"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1180,9 +1180,9 @@ register(GRAMPLET, navtypes=["Source"], ) -register(GRAMPLET, - id="Citation To Do", - name=_("Citation To Do"), +register(GRAMPLET, + id="Citation To Do", + name=_("Citation To Do"), description = _("Gramplet showing the To Do notes for a citation"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1194,9 +1194,9 @@ register(GRAMPLET, navtypes=["Citation"], ) -register(GRAMPLET, - id="Repository To Do", - name=_("Repository To Do"), +register(GRAMPLET, + id="Repository To Do", + name=_("Repository To Do"), description = _("Gramplet showing the To Do notes for a repository"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1208,9 +1208,9 @@ register(GRAMPLET, navtypes=["Repository"], ) -register(GRAMPLET, - id="Media To Do", - name=_("Media To Do"), +register(GRAMPLET, + id="Media To Do", + name=_("Media To Do"), description = _("Gramplet showing the To Do notes for a media object"), version="1.0.0", gramps_target_version=MODULE_VERSION, @@ -1222,8 +1222,8 @@ register(GRAMPLET, navtypes=["Media"], ) -register(GRAMPLET, - id="Python Evaluation", +register(GRAMPLET, + id="Python Evaluation", name="Python Evaluation", description = "Gramplet allowing the evaluation of python code", version="1.0.0", @@ -1235,8 +1235,8 @@ register(GRAMPLET, gramplet_title="Python Evaluation", ) -register(GRAMPLET, - id="Uncollected Objects", +register(GRAMPLET, + id="Uncollected Objects", name="Uncollected Objects", description = "Gramplet showing uncollected objects", version="1.0.0", @@ -1248,9 +1248,9 @@ register(GRAMPLET, gramplet_title="Uncollected Objects", ) -register(GRAMPLET, - id="SoundEx Generator", - name=_("SoundEx Generator"), +register(GRAMPLET, + id="SoundEx Generator", + name=_("SoundEx Generator"), description = _("Gramplet to generate SoundEx codes"), version="1.0.0", gramps_target_version=MODULE_VERSION, diff --git a/gramps/plugins/gramplet/leak.py b/gramps/plugins/gramplet/leak.py index 3c10a1681..185608e5e 100644 --- a/gramps/plugins/gramplet/leak.py +++ b/gramps/plugins/gramplet/leak.py @@ -89,7 +89,7 @@ class Leak(Gramplet): self.modeldata = [] self.model = Gtk.ListStore(int, str) self.list.set_model(self.model) - + #set the columns self.renderer = Gtk.CellRendererText() column = Gtk.TreeViewColumn(_('Number'), self.renderer, text=0) @@ -103,7 +103,7 @@ class Leak(Gramplet): self.list.append_column(column) self.selection = self.list.get_selection() self.top.pack_start(self.scroll, True, True, 6) - + bbox = Gtk.ButtonBox() apply_button = Gtk.Button(label=_("Refresh")) apply_button.connect('clicked', self.apply_clicked) @@ -136,7 +136,7 @@ class Leak(Gramplet): text += str(referrer) + '\n' except ReferenceError: pass - InfoDialog(_('Referrers of %d') % count, text, + InfoDialog(_('Referrers of %d') % count, text, parent=self.uistate.window) def refers_to(self): @@ -150,7 +150,7 @@ class Leak(Gramplet): text += str(referent) + '\n' except ReferenceError: pass - InfoDialog(_('%d refers to') % count, text, + InfoDialog(_('%d refers to') % count, text, parent=self.uistate.window) def display(self): diff --git a/gramps/plugins/gramplet/mediapreview.py b/gramps/plugins/gramplet/mediapreview.py index 0da4e781e..bd2f9ba4e 100644 --- a/gramps/plugins/gramplet/mediapreview.py +++ b/gramps/plugins/gramplet/mediapreview.py @@ -45,7 +45,7 @@ class MediaPreview(Gramplet): self.dbstate.db.connect('media-update', self.update) self.connect_signal('Media', self.update) - def update_has_data(self): + def update_has_data(self): active_handle = self.get_active('Media') if active_handle: active_media = self.dbstate.db.get_object_from_handle(active_handle) diff --git a/gramps/plugins/gramplet/metadataviewer.py b/gramps/plugins/gramplet/metadataviewer.py index 1bdd6bf1f..b0eeaf0d8 100644 --- a/gramps/plugins/gramplet/metadataviewer.py +++ b/gramps/plugins/gramplet/metadataviewer.py @@ -41,7 +41,7 @@ class MetadataViewer(Gramplet): """ self.view = MetadataView() return self.view - + def main(self): active_handle = self.get_active('Media') if active_handle: diff --git a/gramps/plugins/gramplet/notes.py b/gramps/plugins/gramplet/notes.py index 1cbda184b..9c27ea230 100644 --- a/gramps/plugins/gramplet/notes.py +++ b/gramps/plugins/gramplet/notes.py @@ -41,7 +41,7 @@ class Notes(Gramplet): Build the GUI interface. """ top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) - + hbox = Gtk.Box() self.left = SimpleButton('go-previous', self.left_clicked) self.left.set_sensitive(False) @@ -51,7 +51,7 @@ class Notes(Gramplet): hbox.pack_start(self.right, False, False, 0) self.page = Gtk.Label() hbox.pack_end(self.page, False, False, 10) - + scrolledwindow = Gtk.ScrolledWindow() scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.texteditor = StyledTextEditor() @@ -63,7 +63,7 @@ class Notes(Gramplet): top.pack_start(scrolledwindow, True, True, 0) top.show_all() return top - + def get_notes(self, obj): """ Get the note list for the current object. @@ -125,7 +125,7 @@ class Notes(Gramplet): """ Return True if the gramplet has data, else return False. """ - if obj is None: + if obj is None: return False if obj.get_note_list(): return True diff --git a/gramps/plugins/gramplet/pedigreegramplet.py b/gramps/plugins/gramplet/pedigreegramplet.py index e61b06f71..f380d0984 100644 --- a/gramps/plugins/gramplet/pedigreegramplet.py +++ b/gramps/plugins/gramplet/pedigreegramplet.py @@ -54,7 +54,7 @@ class PedigreeGramplet(Gramplet): def build_options(self): from gramps.gen.plug.menu import NumberOption, BooleanOption, EnumeratedListOption - self.add_option(NumberOption(_("Max generations"), + self.add_option(NumberOption(_("Max generations"), self.max_generations, 1, 100)) self.add_option(BooleanOption(_("Show dates"), bool(self.show_dates))) elist = EnumeratedListOption(_("Line type"), self.box_mode) @@ -158,7 +158,7 @@ class PedigreeGramplet(Gramplet): boxes = boxes.replace("+", "\\") self.append_text(boxes) self.link(name_displayer.display_name(person.get_primary_name()), - 'Person', person.handle, + 'Person', person.handle, tooltip=_("Click to make active\n") + \ _("Right-click to edit")) if self.show_dates: @@ -218,7 +218,7 @@ class PedigreeGramplet(Gramplet): if bdate and ddate: value = _("(b. %(birthdate)s, d. %(deathdate)s)") % { - 'birthdate' : bdate, + 'birthdate' : bdate, 'deathdate' : ddate } elif bdate: @@ -257,7 +257,7 @@ class PedigreeGramplet(Gramplet): handles = self._generations[g] self.append_text(" ") if g == 0: - self.link(_("Generation 1"), 'PersonList', handles, + self.link(_("Generation 1"), 'PersonList', handles, tooltip=_("Double-click to see people in generation")) percent = glocale.format( '%.2f', 100) + percent_sign self.append_text(_(" has 1 of 1 individual (%(percent)s complete)\n") % {'percent': percent}) diff --git a/gramps/plugins/gramplet/persondetails.py b/gramps/plugins/gramplet/persondetails.py index dca7fa1f6..e56fc4e99 100644 --- a/gramps/plugins/gramplet/persondetails.py +++ b/gramps/plugins/gramplet/persondetails.py @@ -70,20 +70,20 @@ class PersonDetails(Gramplet): value.show() self.grid.add(label) self.grid.attach_next_to(value, label, Gtk.PositionType.RIGHT, 1, 1) - + def clear_grid(self): """ Remove all the rows from the grid. """ list(map(self.grid.remove, self.grid.get_children())) - + def db_changed(self): self.dbstate.db.connect('person-update', self.update) def active_changed(self, handle): self.update() - def update_has_data(self): + def update_has_data(self): """ Determine if a person has_data by checking: @@ -251,7 +251,7 @@ class PersonDetails(Gramplet): else: retval = _('%(date)s.') % dict(date = date) return retval - + def load_person_image(self, person): """ Load the primary image if it exists. diff --git a/gramps/plugins/gramplet/personresidence.py b/gramps/plugins/gramplet/personresidence.py index 6a6bf90c3..ae416f39a 100644 --- a/gramps/plugins/gramplet/personresidence.py +++ b/gramps/plugins/gramplet/personresidence.py @@ -50,7 +50,7 @@ class PersonResidence(Gramplet): (_('Place'), 2, 200)] self.model = ListModel(top, titles, event_func=self.edit_event) return top - + def db_changed(self): self.dbstate.db.connect('person-update', self.update) diff --git a/gramps/plugins/gramplet/placedetails.py b/gramps/plugins/gramplet/placedetails.py index 24fd2438d..7a819a886 100644 --- a/gramps/plugins/gramplet/placedetails.py +++ b/gramps/plugins/gramplet/placedetails.py @@ -65,7 +65,7 @@ class PlaceDetails(Gramplet): value.show() self.grid.add(label) self.grid.attach_next_to(value, label, Gtk.PositionType.RIGHT, 1, 1) - + def clear_grid(self): """ Remove all the rows from the grid. @@ -76,7 +76,7 @@ class PlaceDetails(Gramplet): self.dbstate.db.connect('place-update', self.update) self.connect_signal('Place', self.update) - def update_has_data(self): + def update_has_data(self): active_handle = self.get_active('Person') if active_handle: active_person = self.dbstate.db.get_person_from_handle(active_handle) diff --git a/gramps/plugins/gramplet/quickviewgramplet.py b/gramps/plugins/gramplet/quickviewgramplet.py index ce5045e8d..779c46394 100644 --- a/gramps/plugins/gramplet/quickviewgramplet.py +++ b/gramps/plugins/gramplet/quickviewgramplet.py @@ -36,7 +36,7 @@ from gramps.gui.plug.quick import run_quick_report_by_name, get_quick_report_lis from gramps.gen.plug import (CATEGORY_QR_PERSON, CATEGORY_QR_FAMILY, CATEGORY_QR_EVENT, CATEGORY_QR_SOURCE, CATEGORY_QR_NOTE, CATEGORY_QR_MISC, CATEGORY_QR_PLACE, CATEGORY_QR_MEDIA, - CATEGORY_QR_REPOSITORY, CATEGORY_QR_CITATION, + CATEGORY_QR_REPOSITORY, CATEGORY_QR_CITATION, CATEGORY_QR_SOURCE_OR_CITATION) #------------------------------------------------------------------------ @@ -82,8 +82,8 @@ class QuickViewGramplet(Gramplet): except: active_handle = None if active_handle: - docman = run_quick_report_by_name(self.gui.dbstate, - self.gui.uistate, + docman = run_quick_report_by_name(self.gui.dbstate, + self.gui.uistate, quick_view, active_handle, container=self.gui.textview) @@ -103,22 +103,22 @@ class QuickViewGramplet(Gramplet): from gramps.gen.plug.menu import EnumeratedListOption # Add types: type_list = EnumeratedListOption(_("View Type"), self.gui.data[0]) - for item in [("Person", _("Person")), - ("Event", _("Event")), - ("Family", _("Family")), - ("Media", _("Media")), - ("Note", _("Note")), - ("Place", _("Place")), + for item in [("Person", _("Person")), + ("Event", _("Event")), + ("Family", _("Family")), + ("Media", _("Media")), + ("Note", _("Note")), + ("Place", _("Place")), ("Repository", _("Repository")), - ("Source", _("Source")), - ("Citation", _("Citation")), + ("Source", _("Source")), + ("Citation", _("Citation")), ]: type_list.add_item(item[0], item[1]) # Add particular lists: qv_list = get_quick_report_list(CATEGORY_QR_PERSON) if self.gui.data[1] is None: self.gui.data[1] = qv_list[0].id - list_option = EnumeratedListOption(_("Quick Views"), + list_option = EnumeratedListOption(_("Quick Views"), self.gui.data[1]) for pdata in qv_list: list_option.add_item(pdata.id, pdata.name) @@ -129,13 +129,13 @@ class QuickViewGramplet(Gramplet): self.rebuild_option_list() # call for initial setting def rebuild_option_list(self): - code_map = {"Person": CATEGORY_QR_PERSON, + code_map = {"Person": CATEGORY_QR_PERSON, "Family": CATEGORY_QR_FAMILY, - "Event": CATEGORY_QR_EVENT, - "Source": CATEGORY_QR_SOURCE, - "Citation": CATEGORY_QR_CITATION, + "Event": CATEGORY_QR_EVENT, + "Source": CATEGORY_QR_SOURCE, + "Citation": CATEGORY_QR_CITATION, "Source or Citation": CATEGORY_QR_SOURCE_OR_CITATION, - "Place": CATEGORY_QR_PLACE, + "Place": CATEGORY_QR_PLACE, "Media": CATEGORY_QR_MEDIA, "Note": CATEGORY_QR_NOTE, "Repository": CATEGORY_QR_REPOSITORY} diff --git a/gramps/plugins/gramplet/repositorydetails.py b/gramps/plugins/gramplet/repositorydetails.py index 906ba060a..298248e8e 100644 --- a/gramps/plugins/gramplet/repositorydetails.py +++ b/gramps/plugins/gramplet/repositorydetails.py @@ -60,7 +60,7 @@ class RepositoryDetails(Gramplet): value.show() self.grid.add(label) self.grid.attach_next_to(value, label, Gtk.PositionType.RIGHT, 1, 1) - + def clear_grid(self): """ Remove all the rows from the grid. @@ -71,7 +71,7 @@ class RepositoryDetails(Gramplet): self.dbstate.db.connect('repository-update', self.update) self.connect_signal('Repository', self.update) - def update_has_data(self): + def update_has_data(self): active_handle = self.get_active('Repository') if active_handle: repo = self.dbstate.db.get_repository_from_handle(active_handle) diff --git a/gramps/plugins/gramplet/sessionloggramplet.py b/gramps/plugins/gramplet/sessionloggramplet.py index 22e2bcb5e..58f9510c4 100644 --- a/gramps/plugins/gramplet/sessionloggramplet.py +++ b/gramps/plugins/gramplet/sessionloggramplet.py @@ -42,7 +42,7 @@ class LogGramplet(Gramplet): self.set_text(_("Log for this Session") + "\n") self.gui.force_update = True # will always update, even if minimized self.last_log = None - + def timestamp(self): self.append_text(time.strftime("%Y-%m-%d %H:%M:%S ")) @@ -51,19 +51,19 @@ class LogGramplet(Gramplet): self.append_text(_("Opened data base -----------\n")) # List of translated strings used here (translated in self.log ). _('Added'), _('Deleted'), _('Edited'), _('Selected') # Dead code for l10n - self.dbstate.db.connect('person-add', + self.dbstate.db.connect('person-add', lambda handles: self.log('Person', 'Added', handles)) - self.dbstate.db.connect('person-delete', + self.dbstate.db.connect('person-delete', lambda handles: self.log('Person', 'Deleted', handles)) - self.dbstate.db.connect('person-update', + self.dbstate.db.connect('person-update', lambda handles: self.log('Person', 'Edited', handles)) - self.dbstate.db.connect('family-add', + self.dbstate.db.connect('family-add', lambda handles: self.log('Family', 'Added', handles)) - self.dbstate.db.connect('family-delete', + self.dbstate.db.connect('family-delete', lambda handles: self.log('Family', 'Deleted', handles)) - self.dbstate.db.connect('family-update', + self.dbstate.db.connect('family-update', lambda handles: self.log('Family', 'Edited', handles)) - + def active_changed(self, handle): if handle: self.log('Person', 'Selected', [handle]) diff --git a/gramps/plugins/gramplet/statsgramplet.py b/gramps/plugins/gramplet/statsgramplet.py index b210cdfc6..b39044ef0 100644 --- a/gramps/plugins/gramplet/statsgramplet.py +++ b/gramps/plugins/gramplet/statsgramplet.py @@ -118,11 +118,11 @@ class StatsGramplet(Gramplet): incomp_names += 1 else: incomp_names += 1 - - if (not person.get_main_parents_family_handle() and + + if (not person.get_main_parents_family_handle() and not len(person.get_family_handle_list())): disconnected += 1 - + birth_ref = person.get_birth_ref() if birth_ref: birth = database.get_event_from_handle(birth_ref.ref) @@ -130,7 +130,7 @@ class StatsGramplet(Gramplet): missing_bday += 1 else: missing_bday += 1 - + if person.get_gender() == Person.FEMALE: females += 1 elif person.get_gender() == Person.MALE: @@ -175,7 +175,7 @@ class StatsGramplet(Gramplet): 'Filter', 'all families') self.append_text(" %s" % database.get_number_of_families()) self.append_text("\n") - self.link("%s:" % _("Unique surnames"), + self.link("%s:" % _("Unique surnames"), 'Filter', 'unique surnames') self.append_text(" %s" % len(namelist)) self.append_text("\n") diff --git a/gramps/plugins/gramplet/surnamecloudgramplet.py b/gramps/plugins/gramplet/surnamecloudgramplet.py index 632eee0bb..6a56c13d0 100644 --- a/gramps/plugins/gramplet/surnamecloudgramplet.py +++ b/gramps/plugins/gramplet/surnamecloudgramplet.py @@ -141,7 +141,7 @@ class SurnameCloudGramplet(Gramplet): include_greater_than = s break # now, limit counts to only include those that we can display: - + mins = self.min_font maxs = self.max_font # Ok, now we can show those counts > include_greater_than: @@ -161,12 +161,12 @@ class SurnameCloudGramplet(Gramplet): text = surname size = make_tag_size(count, counts, mins=mins, maxs=maxs) self.link(text, 'Surname', representative_handle[surname], size, - "%s, %d%% (%d)" % (text, - int((float(count)/total_people) * 100), + "%s, %d%% (%d)" % (text, + int((float(count)/total_people) * 100), count)) self.append_text(" ") showing += 1 - self.append_text(("\n\n" + _("Total unique surnames") + ": %d\n") % + self.append_text(("\n\n" + _("Total unique surnames") + ": %d\n") % len(namelist)) self.append_text((_("Total surnames showing") + ": %d\n") % showing) self.append_text((_("Total people") + ": %d") % total_people, "begin") diff --git a/gramps/plugins/gramplet/todo.py b/gramps/plugins/gramplet/todo.py index 826099321..d42bbc7b4 100644 --- a/gramps/plugins/gramplet/todo.py +++ b/gramps/plugins/gramplet/todo.py @@ -41,7 +41,7 @@ class ToDo(Gramplet): Build the GUI interface. """ top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) - + hbox = Gtk.Box() self.left = SimpleButton('go-previous', self.left_clicked) self.left.set_tooltip_text(_('Previous To Do note')) @@ -60,9 +60,9 @@ class ToDo(Gramplet): hbox.pack_start(self.new, False, False, 0) self.page = Gtk.Label() hbox.pack_end(self.page, False, False, 10) - + scrolledwindow = Gtk.ScrolledWindow() - scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, + scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.texteditor = StyledTextEditor() self.texteditor.set_editable(False) @@ -121,7 +121,7 @@ class ToDo(Gramplet): note_handle = self.note_list[self.current] note = self.dbstate.db.get_note_from_handle(note_handle) self.texteditor.set_text(note.get_styledtext()) - self.page.set_text(_('%(current)d of %(total)d') % + self.page.set_text(_('%(current)d of %(total)d') % {'current': self.current + 1, 'total': len(self.note_list)}) @@ -151,7 +151,7 @@ class ToDo(Gramplet): """ Return True if the gramplet has data, else return False. """ - if obj is None: + if obj is None: return False if self.get_note_list(obj): return True diff --git a/gramps/plugins/gramplet/todogramplet.py b/gramps/plugins/gramplet/todogramplet.py index f9cc5ca6b..fcb8d7bac 100644 --- a/gramps/plugins/gramplet/todogramplet.py +++ b/gramps/plugins/gramplet/todogramplet.py @@ -44,7 +44,7 @@ class ToDoGramplet(Gramplet): Build the GUI interface. """ top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) - + hbox = Gtk.Box() self.left = SimpleButton('go-previous', self.left_clicked) self.left.set_tooltip_text(_('Previous To Do note')) @@ -63,12 +63,12 @@ class ToDoGramplet(Gramplet): hbox.pack_start(self.new, False, False, 0) self.page = Gtk.Label() hbox.pack_end(self.page, False, False, 10) - + self.title = Gtk.Label(halign=Gtk.Align.START) self.title.set_line_wrap(True) - + scrolledwindow = Gtk.ScrolledWindow() - scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, + scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.texteditor = StyledTextEditor() self.texteditor.set_editable(False) @@ -138,7 +138,7 @@ class ToDoGramplet(Gramplet): else: self.title.set_text(_("Unattached")) self.texteditor.set_text(note.get_styledtext()) - self.page.set_text(_('%(current)d of %(total)d') % + self.page.set_text(_('%(current)d of %(total)d') % {'current': self.current + 1, 'total': len(self.note_list)}) diff --git a/gramps/plugins/gramplet/topsurnamesgramplet.py b/gramps/plugins/gramplet/topsurnamesgramplet.py index b8f7df538..c4610a290 100644 --- a/gramps/plugins/gramplet/topsurnamesgramplet.py +++ b/gramps/plugins/gramplet/topsurnamesgramplet.py @@ -103,6 +103,6 @@ class TopSurnamesGramplet(Gramplet): line += 1 if line >= self.top_size: break - self.append_text(("\n" + _("Total unique surnames") + ": %d\n") % + self.append_text(("\n" + _("Total unique surnames") + ": %d\n") % total_surnames) self.append_text((_("Total people") + ": %d") % total_people, "begin") diff --git a/gramps/plugins/gramplet/welcomegramplet.py b/gramps/plugins/gramplet/welcomegramplet.py index 67b032e76..ba7e586a8 100644 --- a/gramps/plugins/gramplet/welcomegramplet.py +++ b/gramps/plugins/gramplet/welcomegramplet.py @@ -83,7 +83,7 @@ class WelcomeGramplet(Gramplet): Build the GUI interface. """ top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) - + scrolledwindow = Gtk.ScrolledWindow() scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.texteditor = StyledTextEditor() @@ -92,7 +92,7 @@ class WelcomeGramplet(Gramplet): scrolledwindow.add(self.texteditor) self.set_text() - + top.pack_start(scrolledwindow, True, True, 0) top.show_all() return top @@ -108,15 +108,15 @@ class WelcomeGramplet(Gramplet): 'some unique and powerful features.\n\n') welcome += boldst(_('Links')) + '\n\n' welcome += linkst(_('Home Page'), URL_HOMEPAGE) + '\n' - welcome += linkst(_('Start with Genealogy and Gramps'), + welcome += linkst(_('Start with Genealogy and Gramps'), '%(gramps_wiki_url)sStart_with_Genealogy' % {'gramps_wiki_url': URL_WIKISTRING} ) + '\n' - welcome += linkst(_('Gramps online manual'), + welcome += linkst(_('Gramps online manual'), URL_WIKISTRING + URL_MANUAL_PAGE + _('locale_suffix|')) + '\n' welcome += linkst(_('Ask questions on gramps-users mailing list'), '%(gramps_home_url)scontact/' % {'gramps_home_url': URL_HOMEPAGE} ) + '\n\n' - + welcome += boldst(_('Who makes Gramps?')) + '\n\n' + _( 'Gramps is created by genealogists for genealogists, organized in the' ' Gramps Project.' @@ -148,4 +148,4 @@ class WelcomeGramplet(Gramplet): Return True if the gramplet has data, else return False. """ return True - + diff --git a/gramps/plugins/gramplet/whatsnext.py b/gramps/plugins/gramplet/whatsnext.py index d7880b6d2..f6e80d9ff 100644 --- a/gramps/plugins/gramplet/whatsnext.py +++ b/gramps/plugins/gramplet/whatsnext.py @@ -57,7 +57,7 @@ class WhatNextGramplet(Gramplet): name = _("Minimum number of items to display") opt = NumberOption(name, self.__todos_wanted, 1, 300) self.opts.append(opt) - + # How many generations of descendants to process before we go up to the # next level of ancestors. name = _("Descendant generations per ancestor generation") diff --git a/gramps/plugins/graph/graphplugins.gpr.py b/gramps/plugins/graph/graphplugins.gpr.py index df62cab02..7f4644f52 100644 --- a/gramps/plugins/graph/graphplugins.gpr.py +++ b/gramps/plugins/graph/graphplugins.gpr.py @@ -18,7 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # diff --git a/gramps/plugins/graph/gvfamilylines.py b/gramps/plugins/graph/gvfamilylines.py index c5a5d50c6..194a1c267 100644 --- a/gramps/plugins/graph/gvfamilylines.py +++ b/gramps/plugins/graph/gvfamilylines.py @@ -3,7 +3,7 @@ # # Copyright (C) 2007-2008 Stephane Charette # Copyright (C) 2007-2008 Brian G. Matherly -# Copyright (C) 2009-2010 Gary Burton +# Copyright (C) 2009-2010 Gary Burton # Contribution 2009 by Bob Ham # Copyright (C) 2010 Jakim Friant # Copyright (C) 2011-2014 Paul Franklin @@ -109,7 +109,7 @@ class FamilyLinesOptions(MenuReportOptions): stdoptions.add_name_format_option(menu, category_name) stdoptions.add_private_data_option(menu, category_name, default=False) - + followpar = BooleanOption(_('Follow parents to determine ' '"family lines"'), True) followpar.set_help(_('Parents and their ancestors will be ' @@ -155,7 +155,7 @@ class FamilyLinesOptions(MenuReportOptions): 'point when determining "family lines".')) add_option('gidlist', person_list) - self.limit_parents = BooleanOption(_('Limit the number of ancestors'), + self.limit_parents = BooleanOption(_('Limit the number of ancestors'), False) self.limit_parents.set_help(_('Whether to ' 'limit the number of ancestors.')) @@ -168,7 +168,7 @@ class FamilyLinesOptions(MenuReportOptions): add_option('maxparents', self.max_parents) self.limit_children = BooleanOption(_('Limit the number ' - 'of descendants'), + 'of descendants'), False) self.limit_children.set_help(_('Whether to ' 'limit the number of descendants.')) @@ -293,7 +293,7 @@ class FamilyLinesReport(Report): def __init__(self, database, options, user): """ Create FamilyLinesReport object that eventually produces the report. - + The arguments are: database - the GRAMPS database instance @@ -308,7 +308,7 @@ class FamilyLinesReport(Report): 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 @@ -318,7 +318,7 @@ class FamilyLinesReport(Report): self._deleted_people = 0 self._deleted_families = 0 self._user = user - + self._followpar = get_value('followpar') self._followchild = get_value('followchild') self._removeextra = get_value('removeextra') @@ -377,7 +377,7 @@ class FamilyLinesReport(Report): def begin_report(self): """ Inherited method; called by report() in _ReportDialog.py - + This is where we'll do all of the work of figuring out who from the database is going to be output into the report """ @@ -402,22 +402,22 @@ class FamilyLinesReport(Report): """ Inherited method; called by report() in _ReportDialog.py """ - + # now that begin_report() has done the work, output what we've # obtained into whatever file or format the user expects to use - self.doc.add_comment('# Number of people in database: %d' + self.doc.add_comment('# Number of people in database: %d' % self._db.get_number_of_people()) - self.doc.add_comment('# Number of people of interest: %d' + self.doc.add_comment('# Number of people of interest: %d' % len(self._people)) - self.doc.add_comment('# Number of families in database: %d' + self.doc.add_comment('# Number of families in database: %d' % self._db.get_number_of_families()) - self.doc.add_comment('# Number of families of interest: %d' + self.doc.add_comment('# Number of families of interest: %d' % len(self._families)) if self._removeextra: - self.doc.add_comment('# Additional people removed: %d' + self.doc.add_comment('# Additional people removed: %d' % self._deleted_people) - self.doc.add_comment('# Additional families removed: %d' + self.doc.add_comment('# Additional families removed: %d' % self._deleted_families) self.doc.add_comment('# Initial list of people of interest:') for handle in self._interest_set: @@ -440,15 +440,15 @@ class FamilyLinesReport(Report): handle = ancestorsNotYetProcessed.pop() # One of 2 things can happen here: - # 1) we already know about this person and he/she is already + # 1) we already know about this person and he/she is already # in our list # 2) this is someone new, and we need to remember him/her # - # In the first case, there isn't anything else to do, so we simply + # In the first case, there isn't anything else to do, so we simply # go back to the top and pop the next person off the list. # - # In the second case, we need to add this person to our list, and - # then go through all of the parents this person has to find more + # In the second case, we need to add this person to our list, and + # then go through all of the parents this person has to find more # people of interest. if handle not in self._people: @@ -475,10 +475,10 @@ class FamilyLinesReport(Report): # if we have a limit on the number of people, and we've # reached that limit, then don't attempt to find any # more ancestors - if self._limitparents and (self._maxparents < + if self._limitparents and (self._maxparents < len(ancestorsNotYetProcessed) + len(self._people)): # get back to the top of the while loop so we can finish - # processing the people queued up in the "not yet + # processing the people queued up in the "not yet # processed" list continue @@ -705,7 +705,7 @@ class FamilyLinesReport(Report): self.doc.add_comment('') - # If we're going to attempt to include images, then use the HTML style + # If we're going to attempt to include images, then use the HTML style # of .gv file. bUseHtmlOutput = False if self._incimages: @@ -794,7 +794,7 @@ class FamilyLinesReport(Report): mediaMimeType = media.get_mime_type() if mediaMimeType[0:5] == "image": imagePath = get_thumbnail_path( - media_path_full(self._db, + media_path_full(self._db, media.get_path()), rectangle=mediaList[0].get_rectangle()) @@ -891,7 +891,7 @@ class FamilyLinesReport(Report): for event_ref in family.get_event_ref_list(): event = self._db.get_event_from_handle(event_ref.ref) if event.get_type() == EventType.MARRIAGE and \ - (event_ref.get_role() == EventRoleType.FAMILY or + (event_ref.get_role() == EventRoleType.FAMILY or event_ref.get_role() == EventRoleType.PRIMARY ): # get the wedding date if self._incdates: diff --git a/gramps/plugins/graph/gvhourglass.py b/gramps/plugins/graph/gvhourglass.py index 9d377fb46..5f725eb6d 100644 --- a/gramps/plugins/graph/gvhourglass.py +++ b/gramps/plugins/graph/gvhourglass.py @@ -39,7 +39,7 @@ Generate an hourglass graph using the Graphviz generator. from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gen.errors import ReportError -from gramps.gen.plug.menu import (PersonOption, BooleanOption, NumberOption, +from gramps.gen.plug.menu import (PersonOption, BooleanOption, NumberOption, EnumeratedListOption) from gramps.gen.plug.report import Report from gramps.gen.plug.report import utils as ReportUtils @@ -77,12 +77,12 @@ class HourGlassReport(Report): """ Report.__init__(self, database, options, user) menu = options.menu - + stdoptions.run_private_data_option(self, menu) self.__db = self.database self.__used_people = [] - + self.max_descend = menu.get_option_by_name('maxdescend').get_value() self.max_ascend = menu.get_option_by_name('maxascend').get_value() pid = menu.get_option_by_name('pid').get_value() @@ -127,7 +127,7 @@ class HourGlassReport(Report): self.add_person(self.center_person) self.traverse_up(self.center_person, 1) self.traverse_down(self.center_person, 1) - + def traverse_down(self, person, gen): """ Recursively find the descendants of the given person. @@ -145,10 +145,10 @@ class HourGlassReport(Report): self.__used_people.append(child_handle) child = self.__db.get_person_from_handle(child_handle) self.add_person(child) - self.doc.add_link(family.get_gramps_id(), + self.doc.add_link(family.get_gramps_id(), child.get_gramps_id() ) self.traverse_down(child, gen+1) - + def traverse_up(self, person, gen): """ Recursively find the ancestors of the given person. @@ -160,14 +160,14 @@ class HourGlassReport(Report): family = self.__db.get_family_from_handle(family_handle) family_id = family.get_gramps_id() self.add_family(family) - self.doc.add_link( family_id, person.get_gramps_id(), + self.doc.add_link( family_id, person.get_gramps_id(), head='none', tail='normal' ) father_handle = family.get_father_handle() if father_handle and father_handle not in self.__used_people: self.__used_people.append(father_handle) father = self.__db.get_person_from_handle(father_handle) self.add_person(father) - self.doc.add_link( father.get_gramps_id(), family_id, + self.doc.add_link( father.get_gramps_id(), family_id, head='none', tail='normal' ) self.traverse_up(father, gen+1) mother_handle = family.get_mother_handle() @@ -175,7 +175,7 @@ class HourGlassReport(Report): self.__used_people.append(mother_handle) mother = self.__db.get_person_from_handle( mother_handle ) self.add_person( mother ) - self.doc.add_link( mother.get_gramps_id(), family_id, + self.doc.add_link( mother.get_gramps_id(), family_id, head='none', tail='normal' ) self.traverse_up( mother, gen+1 ) @@ -185,13 +185,13 @@ class HourGlassReport(Report): """ p_id = person.get_gramps_id() name = self._name_display.display(person) - + birth_evt = get_birth_or_fallback(self.__db, person) if birth_evt: birth = self._get_date(birth_evt.get_date_object()) else: birth = "" - + death_evt = get_death_or_fallback(self.__db, person) if death_evt: death = self._get_date(death_evt.get_date_object()) @@ -206,10 +206,10 @@ class HourGlassReport(Report): label = "%s \\n(%s - %s)\\n(%s)" % (name, birth, death, p_id) label = label.replace('"', '\\\"') - + (shape, style, color, fill) = self.get_gender_style(person) self.doc.add_node(p_id, label, shape, color, style, fill) - + def add_family(self, family): """ Add a family to the Graph. The node id will be the family's gramps id. @@ -279,17 +279,17 @@ class HourGlassOptions(MenuReportOptions): """ def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Create all the menu options for this report. """ category_name = _("Report Options") - + pid = PersonOption(_("Center Person")) pid.set_help(_("The Center person for the graph")) menu.add_option(category_name, "pid", pid) - + stdoptions.add_name_format_option(menu, category_name) stdoptions.add_private_data_option(menu, category_name) @@ -298,7 +298,7 @@ class HourGlassOptions(MenuReportOptions): max_gen.set_help(_("The number of generations of descendants to " "include in the graph")) menu.add_option(category_name, "maxdescend", max_gen) - + max_gen = NumberOption(_('Max Ancestor Generations'), 10, 1, 15) max_gen.set_help(_("The number of generations of ancestors to " "include in the graph")) diff --git a/gramps/plugins/graph/gvrelgraph.py b/gramps/plugins/graph/gvrelgraph.py index c9d7dc7c7..6fc6cd6a4 100644 --- a/gramps/plugins/graph/gvrelgraph.py +++ b/gramps/plugins/graph/gvrelgraph.py @@ -85,7 +85,7 @@ class RelGraphReport(Report): def __init__(self, database, options, user): """ Create RelGraphReport object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -94,7 +94,7 @@ class RelGraphReport(Report): 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. @@ -179,7 +179,7 @@ class RelGraphReport(Report): def write_report(self): self.person_handles = self._filter.apply(self.database, self.database.iter_person_handles()) - + if len(self.person_handles) > 1: self.add_persons_and_families() self.add_child_links_to_families() @@ -192,7 +192,7 @@ class RelGraphReport(Report): # Hash people in a dictionary for faster inclusion checking person_dict = dict([conv_to_unicode(handle, 'utf-8'), 1] for handle in self.person_handles) - + for person_handle in self.person_handles: person = self.database.get_person_from_handle(person_handle) p_id = person.get_gramps_id() @@ -229,9 +229,9 @@ class RelGraphReport(Report): adopted = False if adopted and self.adoptionsdashed: style = 'dotted' - self.doc.add_link( family.get_gramps_id(), p_id, style, + self.doc.add_link( family.get_gramps_id(), p_id, style, self.arrowheadstyle, self.arrowtailstyle ) - + def add_parent_link(self, p_id, parent_handle, rel): "Links the child to a parent" style = 'solid' @@ -240,12 +240,12 @@ class RelGraphReport(Report): parent = self.database.get_person_from_handle(parent_handle) self.doc.add_link( parent.get_gramps_id(), p_id, style, self.arrowheadstyle, self.arrowtailstyle ) - + def add_persons_and_families(self): "adds nodes for persons and their families" # variable to communicate with get_person_label self.bUseHtmlOutput = False - + # The list of families for which we have output the node, # so we don't do it twice families_done = {} @@ -266,9 +266,9 @@ class RelGraphReport(Report): dirpath = "ppl/%s/%s" % (h[-1], h[-2]) dirpath = dirpath.lower() url = "%s/%s.html" % (dirpath, h) - + self.doc.add_node(p_id, label, shape, color, style, fill, url) - + # Output families where person is a parent if self.show_families: family_list = person.get_family_handle_list() @@ -279,7 +279,7 @@ class RelGraphReport(Report): if fam_handle not in families_done: families_done[fam_handle] = 1 self.__add_family(fam_handle) - # If subgraphs are not chosen then each parent is linked + # If subgraphs are not chosen then each parent is linked # separately to the family. This gives Graphviz greater # control over the layout of the whole graph but # may leave spouses not positioned together. @@ -287,7 +287,7 @@ class RelGraphReport(Report): self.doc.add_link(p_id, family.get_gramps_id(), "", self.arrowheadstyle, self.arrowtailstyle) - + def __add_family(self, fam_handle): """Add a node for a family and optionally link the spouses to it""" fam = self.database.get_family_from_handle(fam_handle) @@ -301,7 +301,7 @@ class RelGraphReport(Report): if event is None: continue if (event.type == EventType.MARRIAGE and - (event_ref.get_role() == EventRoleType.FAMILY or + (event_ref.get_role() == EventRoleType.FAMILY or event_ref.get_role() == EventRoleType.PRIMARY) ): date_label = self.get_date_string(event) @@ -341,7 +341,7 @@ class RelGraphReport(Report): fill = self.colors['family'] style = "filled" self.doc.add_node(fam_id, label, "ellipse", color, style, fill) - + # If subgraphs are used then we add both spouses here and Graphviz # will attempt to position both spouses closely together. # TODO: A person who is a parent in more than one family may only be @@ -354,13 +354,13 @@ class RelGraphReport(Report): if f_handle: father = self.database.get_person_from_handle(f_handle) self.doc.add_link(father.get_gramps_id(), - fam_id, "", + fam_id, "", self.arrowheadstyle, self.arrowtailstyle) if m_handle: mother = self.database.get_person_from_handle(m_handle) self.doc.add_link(mother.get_gramps_id(), - fam_id, "", + fam_id, "", self.arrowheadstyle, self.arrowtailstyle) self.doc.end_subgraph() @@ -410,7 +410,7 @@ class RelGraphReport(Report): mediaMimeType = media.get_mime_type() if mediaMimeType[0:5] == "image": imagePath = get_thumbnail_path( - media_path_full(self.database, + media_path_full(self.database, media.get_path()), rectangle=mediaList[0].get_rectangle()) # test if thumbnail actually exists in thumbs @@ -500,7 +500,7 @@ class RelGraphReport(Report): else : # non html label is enclosed by "" so escape other " return label.replace('"', '\\\"') - + def get_event_strings(self, person): "returns tuple of birth/christening and death/burying date strings" @@ -521,7 +521,7 @@ class RelGraphReport(Report): def get_date_string(self, event): """ return date string for an event label. - + Based on the data availability and preferences, we select one of the following for a given event: year only @@ -540,7 +540,7 @@ class RelGraphReport(Report): def get_place_string(self, event): """ return place string for an event label. - + Based on the data availability and preferences, we select one of the following for a given event: place name @@ -552,7 +552,7 @@ class RelGraphReport(Report): #------------------------------------------------------------------------ # -# RelGraphOptions class +# RelGraphOptions class # #------------------------------------------------------------------------ class RelGraphOptions(MenuReportOptions): @@ -568,7 +568,7 @@ class RelGraphOptions(MenuReportOptions): self.__image_on_side = None self.__db = dbase MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): ################################ category_name = _("Report Options") @@ -580,7 +580,7 @@ class RelGraphOptions(MenuReportOptions): _("Determines what people are included in the graph")) add_option("filter", self.__filter) self.__filter.connect('value-changed', self.__filter_changed) - + self.__pid = PersonOption(_("Center Person")) self.__pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", self.__pid) @@ -623,14 +623,14 @@ class RelGraphOptions(MenuReportOptions): "to the files generated by the 'Narrated " "Web Site' report.")) add_option("url", url) - + include_id = EnumeratedListOption(_('Include Gramps ID'), 0) include_id.add_item(0, _('Do not include')) include_id.add_item(1, _('Share an existing line')) include_id.add_item(2, _('On a line of its own')) include_id.set_help(_("Whether (and where) to include Gramps IDs")) add_option("incid", include_id) - + self.__show_relships = BooleanOption( _("Include relationship to center person"), False) self.__show_relships.set_help(_("Whether to show every " @@ -645,7 +645,7 @@ class RelGraphOptions(MenuReportOptions): _("Whether to include thumbnails of people.")) add_option("includeImages", self.__include_images) self.__include_images.connect('value-changed', self.__image_changed) - + self.__image_on_side = EnumeratedListOption(_("Thumbnail Location"), 0) self.__image_on_side.add_item(0, _('Above the name')) self.__image_on_side.add_item(1, _('Beside the name')) @@ -653,7 +653,7 @@ class RelGraphOptions(MenuReportOptions): _("Where the thumbnail image should appear " "relative to the name")) add_option("imageOnTheSide", self.__image_on_side) - + if __debug__: self.__show_GaGb = BooleanOption(_("Include relationship " "debugging numbers also"), @@ -691,7 +691,7 @@ class RelGraphOptions(MenuReportOptions): color_family = ColorOption(_('Families'), '#ffffe0') color_family.set_help(_('The color to use to display families.')) add_option('colorfamilies', color_family) - + arrow = EnumeratedListOption(_("Arrowhead direction"), 'd') for i in range( 0, len(_ARROWS) ): arrow.add_item(_ARROWS[i]["value"], _ARROWS[i]["name"]) @@ -704,18 +704,18 @@ class RelGraphOptions(MenuReportOptions): _("Use rounded corners to differentiate " "between women and men.")) add_option("useroundedcorners", roundedcorners) - + dashed = BooleanOption( _("Indicate non-birth relationships with dotted lines"), True) dashed.set_help(_("Non-birth relationships will show up " "as dotted lines in the graph.")) add_option("dashed", dashed) - + showfamily = BooleanOption(_("Show family nodes"), True) showfamily.set_help(_("Families will show up as ellipses, linked " "to parents and children.")) add_option("showfamily", showfamily) - + def __update_filters(self): """ Update the filter list based on the selected person @@ -727,7 +727,7 @@ class RelGraphOptions(MenuReportOptions): include_single=False, name_format=nfv) self.__filter.set_filters(filter_list) - + def __filter_changed(self): """ Handle filter change. If the filter is not specific to a person, @@ -749,7 +749,7 @@ class RelGraphOptions(MenuReportOptions): image location option unavailable. """ self.__image_on_side.set_available(self.__include_images.get_value()) - + def __show_relships_changed(self): """ Enable/disable menu items if relationships are required diff --git a/gramps/plugins/importer/import.gpr.py b/gramps/plugins/importer/import.gpr.py index e66aa78bf..8412eed1a 100644 --- a/gramps/plugins/importer/import.gpr.py +++ b/gramps/plugins/importer/import.gpr.py @@ -18,7 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # diff --git a/gramps/plugins/importer/importcsv.py b/gramps/plugins/importer/importcsv.py index 328115a13..e8c0fac33 100644 --- a/gramps/plugins/importer/importcsv.py +++ b/gramps/plugins/importer/importcsv.py @@ -49,9 +49,9 @@ LOG = logging.getLogger(".ImportCSV") from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext ngettext = glocale.translation.ngettext # else "nearby" comments are ignored -from gramps.gen.lib import (ChildRef, Citation, Event, EventRef, EventType, - Family, FamilyRelType, Name, NameType, Note, - NoteType, Person, Place, Source, Surname, Tag, +from gramps.gen.lib import (ChildRef, Citation, Event, EventRef, EventType, + Family, FamilyRelType, Name, NameType, Note, + NoteType, Person, Place, Source, Surname, Tag, PlaceName, PlaceType, PlaceRef) from gramps.gen.db import DbTxn from gramps.gen.datehandler import parser as _dp @@ -104,7 +104,7 @@ def importData(dbase, filename, user): if dbase.get_feature("skip-import-additions"): # don't add source or tags parser = CSVParser(dbase, user, None) else: - parser = CSVParser(dbase, user, (config.get('preferences.tag-on-import-format') if + parser = CSVParser(dbase, user, (config.get('preferences.tag-on-import-format') if config.get('preferences.tag-on-import') else None)) try: with open(filename, 'r') as filehandle: @@ -116,7 +116,7 @@ def importData(dbase, filename, user): #------------------------------------------------------------------------- # -# CSV Parser +# CSV Parser # #------------------------------------------------------------------------- class CSVParser(object): @@ -131,7 +131,7 @@ class CSVParser(object): self.indi_count = 0 self.place_count = 0 self.pref = {} # person ref, internal to this sheet - self.fref = {} # family ref, internal to this sheet + self.fref = {} # family ref, internal to this sheet self.placeref = {} self.place_types = {} # Build reverse dictionary, name to type number @@ -225,7 +225,7 @@ class CSVParser(object): "latitude": ("Latitude", _("latitude"), "latitude", _("latitude")), "longitude": ("Longitude", _("Longitude"), "longitude", _("longitude")), "code": ("Code", _("Code"), "code", _("code")), - "enclosed_by": ("Enclosed by", _("Enclosed by"), "enclosed by", _("enclosed by"), + "enclosed_by": ("Enclosed by", _("Enclosed by"), "enclosed by", _("enclosed by"), "enclosed_by", _("enclosed_by"), "Enclosed_by", _("Enclosed_by"), "enclosedby") } @@ -330,11 +330,11 @@ class CSVParser(object): :param filehandle: open file handle positioned at start of the file """ progress_title = _('CSV Import') - with self.user.progress(progress_title, + with self.user.progress(progress_title, _('Reading data...'), 1) as step: data = self.read_csv(filehandle) - with self.user.progress(progress_title, + with self.user.progress(progress_title, _('Importing data...'), len(data)) as step: tym = time.time() self.db.disable_signals() @@ -361,7 +361,7 @@ class CSVParser(object): self.indi_count = 0 self.place_count = 0 self.pref = {} # person ref, internal to this sheet - self.fref = {} # family ref, internal to this sheet + self.fref = {} # family ref, internal to this sheet self.placeref = {} header = None line_number = 0 @@ -672,8 +672,8 @@ class CSVParser(object): if birthsource is not None: new, birthsource = self.get_or_create_source(birthsource) if birthdate or birthplace or birthsource: - new, birth = self.get_or_create_event(person, - EventType.BIRTH, birthdate, + new, birth = self.get_or_create_event(person, + EventType.BIRTH, birthdate, birthplace, birthsource) birth_ref = person.get_birth_ref() if birth_ref is None: @@ -694,8 +694,8 @@ class CSVParser(object): if baptismsource is not None: new, baptismsource = self.get_or_create_source(baptismsource) if baptismdate or baptismplace or baptismsource: - new, baptism = self.get_or_create_event(person, - EventType.BAPTISM, baptismdate, + new, baptism = self.get_or_create_event(person, + EventType.BAPTISM, baptismdate, baptismplace, baptismsource) baptism_ref = get_primary_event_ref_from_type(self.db, person, "Baptism") @@ -742,8 +742,8 @@ class CSVParser(object): if burialsource is not None: new, burialsource = self.get_or_create_source(burialsource) if burialdate or burialplace or burialsource: - new, burial = self.get_or_create_event(person, - EventType.BURIAL, burialdate, + new, burial = self.get_or_create_event(person, + EventType.BURIAL, burialdate, burialplace, burialsource) burial_ref = get_primary_event_ref_from_type(self.db, person, "Burial") @@ -854,7 +854,7 @@ class CSVParser(object): self.db.commit_person(wife, self.trans) self.fam_count += 1 return family - + def get_or_create_event(self, object_, type_, date=None, place=None, source=None): """ Add or find a type event on object """ @@ -891,7 +891,7 @@ class CSVParser(object): self.find_and_set_citation(event, source) self.db.add_event(event, self.trans) return (1, event) - + def create_person(self): """ Used to create a new person we know doesn't exist """ person = Person() @@ -961,6 +961,6 @@ class CSVParser(object): LOG.debug(" creating citation") citation.set_reference_handle(source.get_handle()) self.db.add_citation(citation, self.trans) - LOG.debug(" created citation, citation %s %s" % + LOG.debug(" created citation, citation %s %s" % (citation, citation.get_gramps_id())) obj.add_citation(citation.get_handle()) diff --git a/gramps/plugins/importer/importgedcom.py b/gramps/plugins/importer/importgedcom.py index 5f095674a..542850823 100644 --- a/gramps/plugins/importer/importgedcom.py +++ b/gramps/plugins/importer/importgedcom.py @@ -51,7 +51,7 @@ import imp imp.reload(module) from gramps.gen.config import config - + #------------------------------------------------------------------------- # # importData @@ -116,15 +116,15 @@ def importData(database, filename, user): database, ifile, filename, user, stage_one, None, None) else: gedparse = libgedcom.GedcomParser( - database, ifile, filename, user, stage_one, + database, ifile, filename, user, stage_one, config.get('preferences.default-source'), - (config.get('preferences.tag-on-import-format') if + (config.get('preferences.tag-on-import-format') if config.get('preferences.tag-on-import') else None)) except IOError as msg: user.notify_error(_("%s could not be opened\n") % filename, str(msg)) return except GedcomError as msg: - user.notify_error(_("Invalid GEDCOM file"), + user.notify_error(_("Invalid GEDCOM file"), _("%s could not be imported") % filename + "\n" + str(msg)) return diff --git a/gramps/plugins/importer/importgeneweb.py b/gramps/plugins/importer/importgeneweb.py index 334cfac7c..c5ef46d8b 100644 --- a/gramps/plugins/importer/importgeneweb.py +++ b/gramps/plugins/importer/importgeneweb.py @@ -48,9 +48,9 @@ from gramps.gen.utils.libformatting import ImportInfo _ = glocale.translation.gettext ngettext = glocale.translation.ngettext # else "nearby" comments are ignored from gramps.gen.errors import GedcomError, GrampsImportError -from gramps.gen.lib import (Attribute, AttributeType, ChildRef, Citation, - Date, DateError, Event, EventRef, EventRoleType, EventType, - Family, FamilyRelType, Name, NameType, Note, Person, PersonRef, +from gramps.gen.lib import (Attribute, AttributeType, ChildRef, Citation, + Date, DateError, Event, EventRef, EventRoleType, EventType, + Family, FamilyRelType, Name, NameType, Note, Person, PersonRef, Place, Source, LdsOrd) from gramps.gen.db import DbTxn from gramps.gen.constfunc import conv_to_unicode @@ -192,7 +192,7 @@ class GeneWebParser(object): else: line = None return line - + def parse_geneweb_file(self): with DbTxn(_("GeneWeb import"), self.db, batch=True) as self.trans: self.db.disable_signals() @@ -201,12 +201,12 @@ class GeneWebParser(object): self.index = 0 self.fam_count = 0 self.indi_count = 0 - + self.fkeys = [] self.ikeys = {} self.pkeys = {} self.skeys = {} - + self.current_mode = None self.current_family = None self.current_husband_handle = None @@ -219,9 +219,9 @@ class GeneWebParser(object): break if line == "": continue - + fields = line.split(" ") - + LOG.debug("LINE: %s" %line) if fields[0] == "gwplus": @@ -264,20 +264,20 @@ class GeneWebParser(object): elif fields[0] == "end": self.current_mode = None else: - LOG.warning("parse_geneweb_file(): Token >%s< unknown. line %d skipped: %s" % + LOG.warning("parse_geneweb_file(): Token >%s< unknown. line %d skipped: %s" % (fields[0],self.lineno,line)) except GedcomError as err: self.errmsg(str(err)) - + t = time.time() - t # translators: leave all/any {...} untranslated msg = ngettext('Import Complete: {number_of} second', 'Import Complete: {number_of} seconds', t ).format(number_of=t) - + self.db.enable_signals() self.db.request_rebuild() - + LOG.debug(msg) LOG.debug("Families: %d" % len(self.fkeys)) LOG.debug("Individuals: %d" % len(self.ikeys)) @@ -292,7 +292,7 @@ class GeneWebParser(object): #self.db.commit_family(self.current_family,self.trans) self.fkeys.append(self.current_family.get_handle()) idx = 1; - + LOG.debug("\nHusband:") (idx, husband) = self.parse_person(fields,idx,Person.MALE,None) if husband: @@ -360,7 +360,7 @@ class GeneWebParser(object): self.current_family.add_citation(source.get_handle()) self.db.commit_family(self.current_family,self.trans) return None - + def read_witness_line(self,line,fields): LOG.debug("Witness:") if fields[1] == "m:": @@ -441,7 +441,7 @@ class GeneWebParser(object): break self.current_mode = None return None - + def read_children_birthplace_line(self,line,fields): cbp = self.get_or_create_place(self.decode(fields[1])) @@ -508,7 +508,7 @@ class GeneWebParser(object): sep_date = None div_date = None - + married = 1 engaged = 0 @@ -585,12 +585,12 @@ class GeneWebParser(object): if not married: self.current_family.set_relationship( FamilyRelType(FamilyRelType.UNMARRIED)) - + self.db.commit_family(self.current_family,self.trans) return idx def parse_person(self,fields,idx,gender,father_surname): - + if not father_surname: if not idx < len(fields): LOG.warning("Missing surname of person in line %d!" % self.lineno) @@ -600,7 +600,7 @@ class GeneWebParser(object): idx += 1 else: surname = father_surname - + if not idx < len(fields): LOG.warning("Missing firstname of person in line %d!" % self.lineno) firstname = "" @@ -626,7 +626,7 @@ class GeneWebParser(object): self.db.commit_person(person,self.trans) personDataRe = re.compile("^[kmes0-9<>~#\[({!].*$") dateRe = re.compile("^[kmes0-9~<>?]+.*$") - + source = None birth_parsed = False birth_date = None @@ -646,13 +646,13 @@ class GeneWebParser(object): bur_date = None bur_place = None bur_source = None - + public_name = None firstname_aliases = [] nick_names = [] name_aliases = [] surname_aliases = [] - + while idx < len(fields) and personDataRe.match(fields[idx]): field = fields[idx] idx += 1 @@ -793,7 +793,7 @@ class GeneWebParser(object): else: LOG.warning(("parse_person(): Unknown field " + "'%s' for person in line %d!") % (field, self.lineno)) - + if public_name: name = person.get_primary_name() name.set_type(NameType(NameType.BIRTH)) @@ -804,7 +804,7 @@ class GeneWebParser(object): surname_obj = name.get_primary_surname() surname_obj.set_surname(surname) person.set_primary_name(name) - + for aka in nick_names: name = Attribute() name.set_type(AttributeType(AttributeType.NICKNAME)) @@ -877,7 +877,7 @@ class GeneWebParser(object): self.db.commit_person(person,self.trans) return (idx,person) - + def parse_date(self,field): if field == "0": return None @@ -905,7 +905,7 @@ class GeneWebParser(object): date.set(Date.QUAL_NONE,mod, cal1, (sub1[0],sub1[1],sub1[2],0,sub2[0],sub2[1],sub2[2],0)) except DateError as e: - # TRANSLATORS: leave the {date} and {gw_snippet} untranslated + # TRANSLATORS: leave the {date} and {gw_snippet} untranslated # in the format string, but you may re-order them if needed. LOG.warning(_( "Invalid date {date} in {gw_snippet}, " @@ -924,7 +924,7 @@ class GeneWebParser(object): return (0,int(vals[0]),int(vals[1])) else: return (int(vals[0]),int(vals[1]),int(vals[2])) - + def create_event(self,type,desc=None,date=None,place=None,source=None): event = Event() if type: @@ -1142,7 +1142,7 @@ class GeneWebParser(object): s = s.replace(match.group(0), nchar) except UnicodeDecodeError: pass - + # replace named entities entref_re = re.compile('(&)([a-zA-Z]+)(;)') for match in entref_re.finditer(s): @@ -1152,7 +1152,7 @@ class GeneWebParser(object): s = s.replace(match.group(0), nchar) except UnicodeDecodeError: pass - + return( s) def debug( self, txt): diff --git a/gramps/plugins/importer/importgpkg.py b/gramps/plugins/importer/importgpkg.py index 3c7f1b4c7..330b609fe 100644 --- a/gramps/plugins/importer/importgpkg.py +++ b/gramps/plugins/importer/importgpkg.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -# Written by Alex Roitman, largely based on ReadNative.py by Don Allingham +# Written by Alex Roitman, largely based on ReadNative.py by Don Allingham "Import from Gramps package" @@ -69,13 +69,13 @@ def impData(database, name, user): try: os.mkdir(tmpdir_path, 0o700) except: - user.notify_error( _("Could not create media directory %s") % + user.notify_error( _("Could not create media directory %s") % tmpdir_path ) return elif not os.access(tmpdir_path, os.W_OK): user.notify_error(_("Media directory %s is not writable") % tmpdir_path) return - else: + else: # mediadir exists and writable -- User could have valuable stuff in # it, have him remove it! user.notify_error(_("Media directory %s exists. Delete it first, then" @@ -90,7 +90,7 @@ def impData(database, name, user): user.notify_error(_("Error extracting into %s") % tmpdir_path) return - imp_db_name = os.path.join(tmpdir_path, XMLFILE) + imp_db_name = os.path.join(tmpdir_path, XMLFILE) importer = importData info = importer(database, imp_db_name, user) @@ -126,8 +126,8 @@ def impData(database, name, user): " correct paths in your media objects." ) % {'orig_path': oldmediapath, 'path': tmpdir_path} ) - + # Remove xml file extracted to media dir we imported from os.remove(imp_db_name) - + return info diff --git a/gramps/plugins/importer/importgrdb.py b/gramps/plugins/importer/importgrdb.py index 56b1920f8..796cb9ea1 100644 --- a/gramps/plugins/importer/importgrdb.py +++ b/gramps/plugins/importer/importgrdb.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -39,7 +39,7 @@ from gramps.gen.const import URL_WIKISTRING #------------------------------------------------------------------------- # -# Constants +# Constants # #------------------------------------------------------------------------- _MINVERSION = 9 @@ -50,15 +50,15 @@ _DBVERSION = 14 # # Importing data into the currently open database. # Ability to import .grdb files removed in accordance with -# http://gramps.1791082.n4.nabble.com/Status-of-GEPS-023-tp4329141p4329746.html +# http://gramps.1791082.n4.nabble.com/Status-of-GEPS-023-tp4329141p4329746.html # #------------------------------------------------------------------------- def importData(database, filename, user): migrate_dict = { 'gramps_wiki_migrate_two_to_three_url' : - URL_WIKISTRING + + URL_WIKISTRING + "Gramps_3.4_Wiki_Manual_-_Manage_Family_Trees#" "Moving_a_Gramps_2.2_databases_to_Gramps_3.x" } - user.notify_error(_("%s could not be opened") % filename, + user.notify_error(_("%s could not be opened") % filename, _("The Database version is not supported " "by this version of Gramps." "You should use an old copy of Gramps at " diff --git a/gramps/plugins/importer/importprogen.py b/gramps/plugins/importer/importprogen.py index 16b72eeea..2a091cd17 100644 --- a/gramps/plugins/importer/importprogen.py +++ b/gramps/plugins/importer/importprogen.py @@ -49,9 +49,9 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gen.utils.id import create_id from gramps.gui.utils import ProgressMeter -from gramps.gen.lib import (Attribute, AttributeType, ChildRef, Date, Event, - EventRef, EventType, Family, FamilyRelType, Name, - NameType, Note, NoteType, Person, Place, Source, +from gramps.gen.lib import (Attribute, AttributeType, ChildRef, Date, Event, + EventRef, EventType, Family, FamilyRelType, Name, + NameType, Note, NoteType, Person, Place, Source, Surname, Citation, Location, NameOriginType) from gramps.gen.db import DbTxn from gramps.gen.utils.libformatting import ImportInfo @@ -87,11 +87,11 @@ def _importData(database, filename, user): def _find_from_handle(progen_id, table): """ - Find a handle corresponding to the specified Pro-Gen ID. - - The passed table contains the mapping. If the value is found, we return + Find a handle corresponding to the specified Pro-Gen ID. + + The passed table contains the mapping. If the value is found, we return it, otherwise we create a new handle, store it, and return it. - + """ intid = table.get(progen_id) if not intid: @@ -546,7 +546,7 @@ class ProgenParser(object): def __find_or_create_person(self, progen_id): """ Finds or creates a person based on the Pro-Gen ID. If the ID is - already used (is in the db), we return the item in the db. Otherwise, + already used (is in the db), we return the item in the db. Otherwise, we create a new person, assign the handle and GRAMPS ID. """ person = Person() @@ -565,7 +565,7 @@ class ProgenParser(object): def __find_or_create_family(self, progen_id): """ Finds or creates a family based on the Pro-Gen ID. If the ID is - already used (is in the db), we return the item in the db. Otherwise, + already used (is in the db), we return the item in the db. Otherwise, we create a new family, assign the handle and GRAMPS ID. """ family = Family() @@ -614,7 +614,7 @@ class ProgenParser(object): self.db.add_source(source, self.trans) self.db.commit_source(source, self.trans) self.skeys[source_name] = source.get_handle() - + citation = Citation() citation.set_reference_handle(source.get_handle()) if aktenr: @@ -660,7 +660,7 @@ class ProgenParser(object): note.set(note_text) self.db.add_note(note, self.trans) event.add_note(note.handle) - + self.db.add_event(event, self.trans) self.db.commit_event(event, self.trans) event_ref = EventRef() @@ -850,7 +850,7 @@ class ProgenParser(object): first_name = recflds[first_name_ix] surname_prefix, surname = _split_surname(recflds[surname_ix]) patronym = recflds[patron_ix] # INDI _PATR - alias = recflds[alias_ix] # INDI NAME _ALIA/INDI NAME COMM + alias = recflds[alias_ix] # INDI NAME _ALIA/INDI NAME COMM title1 = recflds[title1_ix] # INDI TITL title2 = recflds[title2_ix] # INDI _TITL2 title3 = recflds[title3_ix] # INDI _TITL3 @@ -916,7 +916,7 @@ class ProgenParser(object): name.add_surname(sname) name.set_first_name(' '.join(aname[0:-1])) name.set_type(NameType.AKA) - person.add_alternate_name(name) + person.add_alternate_name(name) if recflds[occu_ix]: event, event_ref = self.__create_event_and_ref(EventType.OCCUPATION, recflds[occu_ix]) diff --git a/gramps/plugins/importer/importvcard.py b/gramps/plugins/importer/importvcard.py index 9495afb5f..05bda1335 100644 --- a/gramps/plugins/importer/importvcard.py +++ b/gramps/plugins/importer/importvcard.py @@ -48,7 +48,7 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext ngettext = glocale.translation.ngettext # else "nearby" comments are ignored from gramps.gen.errors import GrampsImportError -from gramps.gen.lib import (Address, Date, DateError, Event, EventRef, +from gramps.gen.lib import (Address, Date, DateError, Event, EventRef, EventType, Name, NameType, Person, Surname, Url, UrlType) from gramps.gen.db import DbTxn from gramps.gen.plug.utils import OpenFileOrStdin @@ -218,7 +218,7 @@ class VCardParser(object): def parse(self, filehandle): """ Prepare the database and parse the input file. - + :param filehandle: open file handle positioned at start of the file """ tym = time.time() @@ -244,16 +244,16 @@ class VCardParser(object): break if line == "": continue - + if line.find(":") == -1: continue line_parts = self.name_value_split(line) if not line_parts: continue - + # No check for escaped ; because only fields[0] is used. fields = line_parts[0].split(";") - + property_name = fields[0].upper() if property_name == "BEGIN": self.next_person() @@ -373,14 +373,14 @@ class VCardParser(object): if len(data_fields) > 4 and data_fields[4].strip(): name.set_suffix(' '.join(self.unesc( self.split_unescaped(data_fields[4], ',')))) - + self.person.set_primary_name(name) return True def add_firstname(self, given_name, additional_names, name): """ Combine given_name and additional_names and add as firstname to name. - + If possible try to add given_name as call name. """ default = "%s %s" % (given_name, additional_names) @@ -478,7 +478,7 @@ class VCardParser(object): try: date.set(value=(d, m, y, False)) except DateError as e: - # TRANSLATORS: leave the {date} and {vcard_snippet} untranslated + # TRANSLATORS: leave the {date} and {vcard_snippet} untranslated # in the format string, but you may re-order them if needed. LOG.warning(_( "Invalid date {date} in BDAY {vcard_snippet}, " diff --git a/gramps/plugins/importer/importxml.py b/gramps/plugins/importer/importxml.py index 030099b71..ea41339eb 100644 --- a/gramps/plugins/importer/importxml.py +++ b/gramps/plugins/importer/importxml.py @@ -13,7 +13,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -65,9 +65,9 @@ from gramps.gen.utils.unknown import make_unknown, create_explanation_note from gramps.gen.utils.file import create_checksum, media_path, expand_media_path from gramps.gen.datehandler import parser, set_date from gramps.gen.display.name import displayer as name_displayer -from gramps.gen.db.dbconst import (PERSON_KEY, FAMILY_KEY, SOURCE_KEY, - EVENT_KEY, MEDIA_KEY, PLACE_KEY, - REPOSITORY_KEY, NOTE_KEY, TAG_KEY, +from gramps.gen.db.dbconst import (PERSON_KEY, FAMILY_KEY, SOURCE_KEY, + EVENT_KEY, MEDIA_KEY, PLACE_KEY, + REPOSITORY_KEY, NOTE_KEY, TAG_KEY, CITATION_KEY, CLASS_TO_KEY_MAP) from gramps.gen.updatecallback import UpdateCallback from gramps.version import VERSION @@ -91,12 +91,12 @@ except: PERSON_RE = re.compile(r"\s*\ 0 and not LOG.isEnabledFor(logging.DEBUG)) - + # Similarly, if the data is imported into an empty family tree, we also # import the Researcher; if the tree was not empty, the existing # Researcher is retained @@ -518,11 +518,11 @@ class GrampsParser(UpdateCallback): self.place_import = PlaceImport(self.db) self.resname = "" - self.resaddr = "" + self.resaddr = "" self.reslocality = "" self.rescity = "" self.resstate = "" - self.rescon = "" + self.rescon = "" self.respos = "" self.resphone = "" self.resemail = "" @@ -538,9 +538,9 @@ class GrampsParser(UpdateCallback): # List of new name formats and a dict for remapping them self.name_formats = [] self.name_formats_map = {} - self.taken_name_format_numbers = [num[0] + self.taken_name_format_numbers = [num[0] for num in self.db.name_formats] - + self.event = None self.eventref = None self.childref = None @@ -580,8 +580,8 @@ class GrampsParser(UpdateCallback): self.func_map = { #name part "name": (self.start_name, self.stop_name), - "first": (None, self.stop_first), - "call": (None, self.stop_call), + "first": (None, self.stop_first), + "call": (None, self.stop_call), "aka": (self.start_name, self.stop_aka), #deprecated < 1.3.0 "last": (self.start_last, self.stop_last), #deprecated in 1.4.0 "nick": (None, self.stop_nick), @@ -592,117 +592,117 @@ class GrampsParser(UpdateCallback): "group": (None, self.stop_group), #new in 1.4.0, replaces attribute #new in 1.4.0 "surname": (self.start_surname, self.stop_surname), - # + # "namemaps": (None, None), - "name-formats": (None, None), + "name-formats": (None, None), #other - "address": (self.start_address, self.stop_address), - "addresses": (None, None), + "address": (self.start_address, self.stop_address), + "addresses": (None, None), "alt_name": (None, self.stop_alt_name), - "childlist": (None, None), - "attribute": (self.start_attribute, self.stop_attribute), - "attr_type": (None, self.stop_attr_type), - "attr_value": (None, self.stop_attr_value), + "childlist": (None, None), + "attribute": (self.start_attribute, self.stop_attribute), + "attr_type": (None, self.stop_attr_type), + "attr_value": (None, self.stop_attr_value), "srcattribute": (self.start_srcattribute, self.stop_srcattribute), - "bookmark": (self.start_bmark, None), - "bookmarks": (None, None), - "format": (self.start_format, None), - "child": (self.start_child, None), - "childof": (self.start_childof, None), - "childref": (self.start_childref, self.stop_childref), - "personref": (self.start_personref, self.stop_personref), - "citation": (self.start_citation, self.stop_citation), - "citationref": (self.start_citationref, None), - "citations": (None, None), - "city": (None, self.stop_city), - "county": (None, self.stop_county), - "country": (None, self.stop_country), - "comment": (None, self.stop_comment), - "confidence": (None, self.stop_confidence), - "created": (self.start_created, None), - "ref": (None, self.stop_ref), - "database": (self.start_database, self.stop_database), - "phone": (None, self.stop_phone), - "date": (None, self.stop_date), - "cause": (None, self.stop_cause), - "code": (None, self.stop_code), - "description": (None, self.stop_description), - "event": (self.start_event, self.stop_event), - "type": (None, self.stop_type), - "witness": (self.start_witness, self.stop_witness), - "eventref": (self.start_eventref, self.stop_eventref), + "bookmark": (self.start_bmark, None), + "bookmarks": (None, None), + "format": (self.start_format, None), + "child": (self.start_child, None), + "childof": (self.start_childof, None), + "childref": (self.start_childref, self.stop_childref), + "personref": (self.start_personref, self.stop_personref), + "citation": (self.start_citation, self.stop_citation), + "citationref": (self.start_citationref, None), + "citations": (None, None), + "city": (None, self.stop_city), + "county": (None, self.stop_county), + "country": (None, self.stop_country), + "comment": (None, self.stop_comment), + "confidence": (None, self.stop_confidence), + "created": (self.start_created, None), + "ref": (None, self.stop_ref), + "database": (self.start_database, self.stop_database), + "phone": (None, self.stop_phone), + "date": (None, self.stop_date), + "cause": (None, self.stop_cause), + "code": (None, self.stop_code), + "description": (None, self.stop_description), + "event": (self.start_event, self.stop_event), + "type": (None, self.stop_type), + "witness": (self.start_witness, self.stop_witness), + "eventref": (self.start_eventref, self.stop_eventref), "data_item": (self.start_data_item, None), #deprecated in 1.6.0 - "families": (None, self.stop_families), - "family": (self.start_family, self.stop_family), - "rel": (self.start_rel, None), + "families": (None, self.stop_families), + "family": (self.start_family, self.stop_family), + "rel": (self.start_rel, None), "region": (self.start_region, None), - "father": (self.start_father, None), - "gender": (None, self.stop_gender), - "header": (None, self.stop_header), + "father": (self.start_father, None), + "gender": (None, self.stop_gender), + "header": (None, self.stop_header), "map": (self.start_namemap, None), "mediapath": (None, self.stop_mediapath), - "mother": (self.start_mother, None), - "note": (self.start_note, self.stop_note), - "noteref": (self.start_noteref, None), - "p": (None, self.stop_ptag), - "parentin": (self.start_parentin, None), - "people": (self.start_people, self.stop_people), - "person": (self.start_person, self.stop_person), - "img": (self.start_photo, self.stop_photo), - "objref": (self.start_objref, self.stop_objref), - "object": (self.start_object, self.stop_object), - "file": (self.start_file, None), - "page": (None, self.stop_page), - "place": (self.start_place, self.stop_place), - "dateval": (self.start_dateval, None), - "daterange": (self.start_daterange, None), - "datespan": (self.start_datespan, None), - "datestr": (self.start_datestr, None), - "places": (None, self.stop_places), - "placeobj": (self.start_placeobj, self.stop_placeobj), - "placeref": (self.start_placeref, self.stop_placeref), + "mother": (self.start_mother, None), + "note": (self.start_note, self.stop_note), + "noteref": (self.start_noteref, None), + "p": (None, self.stop_ptag), + "parentin": (self.start_parentin, None), + "people": (self.start_people, self.stop_people), + "person": (self.start_person, self.stop_person), + "img": (self.start_photo, self.stop_photo), + "objref": (self.start_objref, self.stop_objref), + "object": (self.start_object, self.stop_object), + "file": (self.start_file, None), + "page": (None, self.stop_page), + "place": (self.start_place, self.stop_place), + "dateval": (self.start_dateval, None), + "daterange": (self.start_daterange, None), + "datespan": (self.start_datespan, None), + "datestr": (self.start_datestr, None), + "places": (None, self.stop_places), + "placeobj": (self.start_placeobj, self.stop_placeobj), + "placeref": (self.start_placeref, self.stop_placeref), "ptitle": (None, self.stop_ptitle), "pname": (self.start_place_name, self.stop_place_name), - "location": (self.start_location, None), - "lds_ord": (self.start_lds_ord, self.stop_lds_ord), - "temple": (self.start_temple, None), - "status": (self.start_status, None), - "sealed_to": (self.start_sealed_to, None), - "coord": (self.start_coord, None), - "pos": (self.start_pos, None), + "location": (self.start_location, None), + "lds_ord": (self.start_lds_ord, self.stop_lds_ord), + "temple": (self.start_temple, None), + "status": (self.start_status, None), + "sealed_to": (self.start_sealed_to, None), + "coord": (self.start_coord, None), + "pos": (self.start_pos, None), "postal": (None, self.stop_postal), "range": (self.start_range, None), - "researcher": (None, self.stop_research), - "resname": (None, self.stop_resname), - "resaddr": (None, self.stop_resaddr), - "reslocality": (None, self.stop_reslocality), - "rescity": (None, self.stop_rescity), - "resstate": (None, self.stop_resstate), - "rescountry": (None, self.stop_rescountry), - "respostal": (None, self.stop_respostal), - "resphone": (None, self.stop_resphone), - "resemail": (None, self.stop_resemail), - "sauthor": (None, self.stop_sauthor), - "sabbrev": (None, self.stop_sabbrev), - "scomments": (None, self.stop_scomments), - "source": (self.start_source, self.stop_source), - "sourceref": (self.start_sourceref, self.stop_sourceref), - "sources": (None, None), - "spage": (None, self.stop_spage), - "spubinfo": (None, self.stop_spubinfo), - "state": (None, self.stop_state), - "stext": (None, self.stop_stext), - "stitle": (None, self.stop_stitle), - "street": (None, self.stop_street), + "researcher": (None, self.stop_research), + "resname": (None, self.stop_resname), + "resaddr": (None, self.stop_resaddr), + "reslocality": (None, self.stop_reslocality), + "rescity": (None, self.stop_rescity), + "resstate": (None, self.stop_resstate), + "rescountry": (None, self.stop_rescountry), + "respostal": (None, self.stop_respostal), + "resphone": (None, self.stop_resphone), + "resemail": (None, self.stop_resemail), + "sauthor": (None, self.stop_sauthor), + "sabbrev": (None, self.stop_sabbrev), + "scomments": (None, self.stop_scomments), + "source": (self.start_source, self.stop_source), + "sourceref": (self.start_sourceref, self.stop_sourceref), + "sources": (None, None), + "spage": (None, self.stop_spage), + "spubinfo": (None, self.stop_spubinfo), + "state": (None, self.stop_state), + "stext": (None, self.stop_stext), + "stitle": (None, self.stop_stitle), + "street": (None, self.stop_street), "style": (self.start_style, None), "tag": (self.start_tag, self.stop_tag), "tagref": (self.start_tagref, None), "tags": (None, None), "text": (None, self.stop_text), - "url": (self.start_url, None), - "repository": (self.start_repo, self.stop_repo), - "reporef": (self.start_reporef, self.stop_reporef), - "rname": (None, self.stop_rname), + "url": (self.start_url, None), + "repository": (self.start_repo, self.stop_repo), + "reporef": (self.start_reporef, self.stop_reporef), + "rname": (None, self.stop_rname), } self.grampsuri = re.compile(r"^gramps://(?P[A-Z][a-z]+)/" "handle/(?P\w+)$") @@ -734,7 +734,7 @@ class GrampsParser(UpdateCallback): if (orig_handle in self.import_handles and target in self.import_handles[orig_handle]): handle = self.import_handles[handle][target][HANDLE] - if not isinstance(prim_obj, collections.Callable): + if not isinstance(prim_obj, collections.Callable): # This method is called by a start_ method. get_raw_obj_data = {"person": self.db.get_raw_person_data, "family": self.db.get_raw_family_data, @@ -874,7 +874,7 @@ class GrampsParser(UpdateCallback): find_next_gramps_id): """ Given an import id, adjust it so that it fits with the existing data. - + :param id_: The id as it is in the Xml import file, might be None. :type id_: str :param key: Indicates kind of primary object this id is for. @@ -927,7 +927,7 @@ class GrampsParser(UpdateCallback): self.db.name_formats += self.name_formats # Register new formats name_displayer.set_name_format(self.db.name_formats) - + # If the database was originally empty we update the researcher from # the XML (or initialised to no researcher) if self.import_researcher: @@ -935,7 +935,7 @@ class GrampsParser(UpdateCallback): if self.home is not None: person = self.db.get_person_from_handle(self.home) self.db.set_default_person_handle(person.handle) - + # Set media path # The paths are normalized before being compared. if self.mediapath: @@ -949,7 +949,7 @@ class GrampsParser(UpdateCallback): "files to a correct directory or change the media " "path in the Preferences." ) % self.mediapath ) - + self.fix_not_instantiated() self.fix_families() for key in list(self.func_map.keys()): @@ -977,7 +977,7 @@ class GrampsParser(UpdateCallback): #leave version at 1.0.0 although it could be 0.0.0 ?? pass else: - #1.0 or before xml, no dtd schema yet on + #1.0 or before xml, no dtd schema yet on # http://www.gramps-project.org/xml/ self.__xml_version = (0, 0, 0) @@ -1021,7 +1021,7 @@ class GrampsParser(UpdateCallback): "The file will not be imported. Please use an older version" " of Gramps that supports version %(xmlversion)s of the " "xml.\nSee\n %(gramps_wiki_xml_url)s\n for more info." - ) % {'oldgramps': self.__gramps_version, + ) % {'oldgramps': self.__gramps_version, 'newgramps': VERSION, 'xmlversion': xmlversion_str, 'gramps_wiki_xml_url': URL_WIKISTRING + "GRAMPS_XML" , @@ -1036,7 +1036,7 @@ class GrampsParser(UpdateCallback): "older version of Gramps in the meantime to import this " "file, which is version %(xmlversion)s of the xml.\nSee\n " "%(gramps_wiki_xml_url)s\nfor more info." - ) % {'oldgramps': self.__gramps_version, + ) % {'oldgramps': self.__gramps_version, 'newgramps': VERSION, 'xmlversion': xmlversion_str, 'gramps_wiki_xml_url': URL_WIKISTRING + "GRAMPS_XML" , @@ -1086,7 +1086,7 @@ class GrampsParser(UpdateCallback): handle = self.inaugurate_id(attrs.get('ref'), FAMILY_KEY, Family) self.ord.set_family_handle(handle) - + def start_place(self, attrs): """A reference to a place in an object: event or lds_ord """ @@ -1099,7 +1099,7 @@ class GrampsParser(UpdateCallback): self.ord.set_place_handle(handle) elif self.event: self.event.set_place_handle(handle) - + def start_placeobj(self, attrs): """ Add a place object to db if it doesn't exist yet and assign @@ -1131,17 +1131,17 @@ class GrampsParser(UpdateCallback): self.placeobj.place_type.set_from_xml_str(attrs.get('type')) self.info.add('new-object', PLACE_KEY, self.placeobj) self.place_names = 0 - + # GRAMPS LEGACY: title in the placeobj tag self.placeobj.title = attrs.get('title', '') self.locations = 0 self.update(self.p.CurrentLineNumber) return self.placeobj - + def start_location(self, attrs): """Bypass the function calls for this one, since it appears to take up quite a bit of time""" - + loc = Location() loc.street = attrs.get('street', '') loc.locality = attrs.get('locality', '') @@ -1219,7 +1219,7 @@ class GrampsParser(UpdateCallback): event_ref.role.set(EventRoleType.WITNESS) person.event_ref_list.append(event_ref) self.db.commit_person(person, self.trans, self.change) - + def start_coord(self, attrs): self.placeobj.lat = attrs.get('lat', '') self.placeobj.long = attrs.get('long', '') @@ -1285,7 +1285,7 @@ class GrampsParser(UpdateCallback): event = self.db.get_event_from_handle(self.eventref.ref) if not event: return - + if self.family: event.personal = False self.family.add_event_ref(self.eventref) @@ -1401,7 +1401,7 @@ class GrampsParser(UpdateCallback): and handle not in self.db.media_bookmarks.get() ): self.db.media_bookmarks.append(handle) elif target == 'repository': - if (self.db.get_repository_from_handle(handle) + if (self.db.get_repository_from_handle(handle) is not None and handle not in self.db.repo_bookmarks.get()): self.db.repo_bookmarks.append(handle) elif target == 'note': @@ -1433,7 +1433,7 @@ class GrampsParser(UpdateCallback): self.name_formats_map[old_number] = new_number # Return new number return new_number - + def start_person(self, attrs): """ Add a person to db if it doesn't exist yet and assign @@ -1460,7 +1460,7 @@ class GrampsParser(UpdateCallback): self.person.change = int(attrs.get('change', self.change)) self.info.add('new-object', PERSON_KEY, self.person) self.convert_marker(attrs, self.person) - if self.default_tag: + if self.default_tag: self.person.add_tag(self.default_tag.handle) return self.person @@ -1493,7 +1493,7 @@ class GrampsParser(UpdateCallback): handle = self.inaugurate_id(attrs.get('ref'), PERSON_KEY, Person) self.family.set_mother_handle(handle) - + def start_child(self, attrs): """ Add a child reference to the family currently processed. @@ -1598,7 +1598,7 @@ class GrampsParser(UpdateCallback): if 'type' in attrs: self.family.type.set_from_xml_str(attrs["type"]) self.convert_marker(attrs, self.family) - if self.default_tag: + if self.default_tag: self.family.add_tag(self.default_tag.handle) return self.family @@ -1765,7 +1765,7 @@ class GrampsParser(UpdateCallback): if match: target = {"Person":"person", "Family":"family", "Event":"event", "Place":"place", "Source":"source", - "Citation":"citation", + "Citation":"citation", "Repository":"repository", "Media":"media", "Note":"note"}[str(match.group('object_class'))] if match.group('handle') in self.import_handles: @@ -1779,7 +1779,7 @@ class GrampsParser(UpdateCallback): tagvalue = None except ValueError: return - + self.note_tags.append(StyledTextTag(tagtype, tagvalue)) def start_tag(self, attrs): @@ -1844,7 +1844,7 @@ class GrampsParser(UpdateCallback): def start_range(self, attrs): self.note_tags[-1].ranges.append((int(attrs['start']), int(attrs['end']))) - + def start_note(self, attrs): """ Add a note to db if it doesn't exist yet and assign @@ -1864,7 +1864,7 @@ class GrampsParser(UpdateCallback): self.nidswap, self.db.nid2user_format, self.db.find_next_note_gramps_id) self.note.set_gramps_id(gramps_id) - if is_merge_candidate: + if is_merge_candidate: orig_note = self.db.get_note_from_handle(orig_handle) self.info.add('merge-candicate', NOTE_KEY, orig_note, self.note) @@ -1877,7 +1877,7 @@ class GrampsParser(UpdateCallback): self.note.type.set_from_xml_str(attrs.get('type', NoteType.UNKNOWN)) self.convert_marker(attrs, self.note) - + # Since StyledText was introduced (XML v1.3.0) the clear text # part of the note is moved between tags. # To catch the different versions here we reset the note_text @@ -1886,7 +1886,7 @@ class GrampsParser(UpdateCallback): self.note_tags = [] else: # GRAMPS LEGACY: old notes that were written inside other objects - # We need to create a top-level note, it's type depends on + # We need to create a top-level note, it's type depends on # the caller object, and inherits privacy from caller object # On stop_note the reference to this note will be added self.note = Note() @@ -1948,12 +1948,12 @@ class GrampsParser(UpdateCallback): elif self.repo: self.note.type.set(NoteType.REPO) self.note.private = self.repo.private - + self.db.add_note(self.note, self.trans) #set correct change time self.db.commit_note(self.note, self.trans, self.change) self.info.add('new-object', NOTE_KEY, self.note) - if self.default_tag: + if self.default_tag: self.note.add_tag(self.default_tag.handle) return self.note @@ -2212,7 +2212,7 @@ class GrampsParser(UpdateCallback): src = attrs.get("src", '') if src: self.object.path = src - if self.default_tag: + if self.default_tag: self.object.add_tag(self.default_tag.handle) return self.object @@ -2235,7 +2235,7 @@ class GrampsParser(UpdateCallback): orig_repo = self.db.get_repository_from_handle(orig_handle) self.info.add('merge-candidate', REPOSITORY_KEY, orig_repo, self.repo) - else: # old style XML + else: # old style XML self.inaugurate_id(attrs.get('id'), REPOSITORY_KEY, self.repo) self.repo.private = bool(attrs.get("priv")) self.repo.change = int(attrs.get('change', self.change)) @@ -2249,26 +2249,26 @@ class GrampsParser(UpdateCallback): self.update(self.p.CurrentLineNumber) def stop_object(self, *tag): - self.db.commit_media_object(self.object, self.trans, + self.db.commit_media_object(self.object, self.trans, self.object.get_change_time()) self.object = None def stop_objref(self, *tag): self.objref = None - + def stop_repo(self, *tag): - self.db.commit_repository(self.repo, self.trans, + self.db.commit_repository(self.repo, self.trans, self.repo.get_change_time()) self.repo = None def stop_reporef(self, *tag): self.reporef = None - + def start_photo(self, attrs): self.photo = MediaObject() self.pref = MediaRef() self.pref.set_reference_handle(self.photo.get_handle()) - + for key in list(attrs.keys()): if key == "descrip" or key == "description": self.photo.set_description(attrs[key]) @@ -2369,7 +2369,7 @@ class GrampsParser(UpdateCallback): qual = Date.QUAL_NONE else: qual = Date.QUAL_NONE - + dualdated = False if 'dualdated' in attrs: val = attrs['dualdated'] @@ -2385,12 +2385,12 @@ class GrampsParser(UpdateCallback): newyear = Date.newyear_to_code(newyear) try: - date_value.set(qual, mode, cal, - (day, month, year, dualdated, - rng_day, rng_month, rng_year, dualdated), + date_value.set(qual, mode, cal, + (day, month, year, dualdated, + rng_day, rng_month, rng_year, dualdated), newyear=newyear) except DateError as e: - self._set_date_to_xml_text(date_value, e, + self._set_date_to_xml_text(date_value, e, xml_element_name = ("datespan" if mode == Date.MOD_SPAN else "daterange"), xml_attrs = attrs) @@ -2476,7 +2476,7 @@ class GrampsParser(UpdateCallback): newyear = Date.newyear_to_code(newyear) try: - date_value.set(qual, mod, cal, (day, month, year, dualdated), + date_value.set(qual, mod, cal, (day, month, year, dualdated), newyear=newyear) except DateError as e: self._set_date_to_xml_text(date_value, e, 'dateval', attrs) @@ -2491,7 +2491,7 @@ class GrampsParser(UpdateCallback): xml = "<{element_name} {attrs}/>".format( element_name = xml_element_name, attrs = " ".join( - ['{}="{}"'.format(k,escape(v, entities={'"' : """})) + ['{}="{}"'.format(k,escape(v, entities={'"' : """})) for k,v in xml_attrs.items()])) # TRANSLATORS: leave the {date} and {xml} untranslated in the format string, # but you may re-order them if needed. @@ -2567,10 +2567,10 @@ class GrampsParser(UpdateCallback): elif self.repo: self.repo.add_address(self.address) self.address = None - + def stop_places(self, *tag): self.placeobj = None - + if self.__xml_version < (1, 6, 0): self.place_import.generate_hierarchy(self.trans) @@ -2591,7 +2591,7 @@ class GrampsParser(UpdateCallback): def stop_placeobj(self, *tag): if self.placeobj.name.get_value() == '': self.placeobj.name.set_value(self.placeobj.title) - self.db.commit_place(self.placeobj, self.trans, + self.db.commit_place(self.placeobj, self.trans, self.placeobj.get_change_time()) self.placeobj = None @@ -2599,7 +2599,7 @@ class GrampsParser(UpdateCallback): self.db.commit_family(self.family, self.trans, self.family.get_change_time()) self.family = None - + def stop_type(self, tag): if self.event: # Event type @@ -2645,13 +2645,13 @@ class GrampsParser(UpdateCallback): self.event.get_type() != EventType.CUSTOM: if self.family: text = EVENT_FAMILY_STR % { - 'event_name' : str(self.event.get_type()), - 'family' : family_name(self.family, self.db), + 'event_name' : str(self.event.get_type()), + 'family' : family_name(self.family, self.db), } elif self.person: text = EVENT_PERSON_STR % { - 'event_name' : str(self.event.get_type()), - 'person' : name_displayer.display(self.person), + 'event_name' : str(self.event.get_type()), + 'person' : name_displayer.display(self.person), } else: text = '' @@ -2683,17 +2683,17 @@ class GrampsParser(UpdateCallback): self.db.commit_note(note, self.trans, self.change) self.info.add('new-object', NOTE_KEY, note) self.event.add_note(note.handle) - else: + else: #first correct old xml that has no nametype set if self.alt_name: - # alternate name or former aka tag + # alternate name or former aka tag if self.name.get_type() == "": self.name.set_type(NameType.AKA) else: if self.name.get_type() == "": self.name.set_type(NameType.BIRTH) - - #same logic as bsddb upgrade for xml < 1.4.0 which will + + #same logic as bsddb upgrade for xml < 1.4.0 which will #have a surnamepat and/or surname. From 1.4.0 surname has been #added to name in self.stop_surname if not self.surnamepat: @@ -2785,7 +2785,7 @@ class GrampsParser(UpdateCallback): ## self.db.commit_place(self.placeobj,self.trans,self.change) ##self.place_ref = None pass - + def stop_date(self, tag): if tag: if self.address: @@ -2867,7 +2867,7 @@ class GrampsParser(UpdateCallback): def stop_state(self, tag): self.address.state = tag - + def stop_country(self, tag): self.address.country = tag @@ -2894,7 +2894,7 @@ class GrampsParser(UpdateCallback): def stop_sabbrev(self, tag): self.source.set_abbreviation(tag) - + def stop_stext(self, tag): if self.use_p: self.use_p = 0 @@ -2908,10 +2908,10 @@ class GrampsParser(UpdateCallback): note.private = self.citation.private note.set(text) note.type.set(NoteType.SOURCE_TEXT) - self.db.add_note(note, self.trans) + self.db.add_note(note, self.trans) #set correct change time self.db.commit_note(note, self.trans, self.change) - self.info.add('new-object', NOTE_KEY, note) + self.info.add('new-object', NOTE_KEY, note) self.citation.add_note(note.handle) def stop_scomments(self, tag): @@ -2984,7 +2984,7 @@ class GrampsParser(UpdateCallback): def stop_text(self, tag): self.note_text = tag - + def stop_note(self, tag): self.in_note = 0 if self.use_p: @@ -2994,7 +2994,7 @@ class GrampsParser(UpdateCallback): text = self.note_text else: text = tag - + self.note.set_styledtext(StyledText(text, self.note_tags)) # The order in this long if-then statement should reflect the @@ -3107,9 +3107,9 @@ class GrampsParser(UpdateCallback): def endElement(self, tag): if self.func: self.func(''.join(self.tlist)) - self.func_index -= 1 + self.func_index -= 1 self.func, self.tlist = self.func_list[self.func_index] - + def characters(self, data): if self.func: self.tlist.append(data) @@ -3117,7 +3117,7 @@ class GrampsParser(UpdateCallback): def convert_marker(self, attrs, obj): """ Convert markers into tags. - + Old and new markers: complete=1 and marker=word """ if attrs.get('complete'): # this is only true for complete=1 @@ -3188,7 +3188,7 @@ class GrampsParser(UpdateCallback): family = self.db.get_family_from_handle(family_handle) father_handle = family.get_father_handle() mother_handle = family.get_mother_handle() - + if father_handle: father = self.db.get_person_from_handle(father_handle) if father and \ @@ -3199,12 +3199,12 @@ class GrampsParser(UpdateCallback): " father '%(father)s'" " does not refer" " back to the family." - " Reference added." % - {'family' : family.gramps_id, + " Reference added." % + {'family' : family.gramps_id, 'father' : father.gramps_id}) self.info.add('unlinked-family', txt, None) LOG.warn(txt) - + if mother_handle: mother = self.db.get_person_from_handle(mother_handle) if mother and \ @@ -3215,12 +3215,12 @@ class GrampsParser(UpdateCallback): " mother '%(mother)s'" " does not refer" " back to the family." - " Reference added." % - {'family' : family.gramps_id, + " Reference added." % + {'family' : family.gramps_id, 'mother' : mother.gramps_id}) self.info.add('unlinked-family', txt, None) LOG.warn(txt) - + for child_ref in family.get_child_ref_list(): child_handle = child_ref.ref child = self.db.get_person_from_handle(child_handle) @@ -3237,8 +3237,8 @@ class GrampsParser(UpdateCallback): " child '%(child)s'" " does not " "refer back to the family. " - "Reference added." % - {'family' : family.gramps_id, + "Reference added." % + {'family' : family.gramps_id, 'child' : child.gramps_id}) self.info.add('unlinked-family', txt, None) LOG.warn(txt) diff --git a/gramps/plugins/importer/test/importvcard_test.py b/gramps/plugins/importer/test/importvcard_test.py index e43a93d06..b8107de46 100644 --- a/gramps/plugins/importer/test/importvcard_test.py +++ b/gramps/plugins/importer/test/importvcard_test.py @@ -27,7 +27,7 @@ Unittest of import of VCard import unittest import time import subprocess -import xml.etree.ElementTree as ET +import xml.etree.ElementTree as ET from gramps.plugins.lib.libgrampsxml import GRAMPS_XML_VERSION from gramps.version import VERSION @@ -64,7 +64,7 @@ class VCardCheck(unittest.TestCase): if hlink is not None: element.set('hlink', handles.get(hlink)) if element.get('change') is not None: - del element.attrib['change'] + del element.attrib['change'] if element.text is not None and not element.text.strip(): element.text = '' if element.tail is not None and not element.tail.strip(): @@ -79,9 +79,9 @@ class VCardCheck(unittest.TestCase): process = subprocess.Popen('python3 Gramps.py -d .Date -d .ImportVCard ' '--config=preferences.eprefix:DEFAULT ' '-i - -f vcf -e - -f gramps', - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, shell=True) result_str, err_str = process.communicate(input_str.encode("utf-8")) if debug: @@ -91,7 +91,7 @@ class VCardCheck(unittest.TestCase): if debug: print(self.canonicalize(result_doc)) print(self.canonicalize(expect_doc)) - self.assertEqual(self.canonicalize(result_doc), + self.assertEqual(self.canonicalize(result_doc), self.canonicalize(expect_doc)) def test_base(self): @@ -248,7 +248,7 @@ class VCardCheck(unittest.TestCase): ET.SubElement(self.name, 'suffix').text = 'Jr.' ET.SubElement(self.name, 'title').text = 'Mr.' self.do_case("\r\n".join(self.vcard), self.gramps) - + def test_add_name_multisurname(self): self.vcard[2] = "FN:Lastname Lastname2" self.vcard[3] = "N:Lastname,Lastname2;;;;" diff --git a/gramps/plugins/lib/libcairodoc.py b/gramps/plugins/lib/libcairodoc.py index dbaf537e4..2837ac8a8 100644 --- a/gramps/plugins/lib/libcairodoc.py +++ b/gramps/plugins/lib/libcairodoc.py @@ -109,28 +109,28 @@ def set_font_families(): """Set the used font families depending on availability. """ global font_families - - fonts = SystemFonts() + + fonts = SystemFonts() family_names = fonts.get_system_fonts() - + fam = [f for f in _TTF_FREEFONT.values() if f in family_names] if len(fam) == len(_TTF_FREEFONT): font_families = _TTF_FREEFONT log.debug('Using FreeFonts: %s' % font_families) return - + fam = [f for f in _MS_TTFONT.values() if f in family_names] if len(fam) == len(_MS_TTFONT): font_families = _MS_TTFONT log.debug('Using MS TrueType fonts: %s' % font_families) return - + fam = [f for f in _GNOME_FONT.values() if f in family_names] if len(fam) == len(_GNOME_FONT): font_families = _GNOME_FONT log.debug('Using Gnome fonts: %s' % font_families) return - + log.debug('No fonts found.') set_font_families() @@ -143,26 +143,26 @@ set_font_families() def fontstyle_to_fontdescription(font_style): """Convert a FontStyle instance to a Pango.FontDescription one. - + Font color and underline are not implemented in Pango.FontDescription, and have to be set with Pango.Layout.set_attributes(attrlist) method. - + """ if font_style.get_bold(): f_weight = Pango.Weight.BOLD else: f_weight = Pango.Weight.NORMAL - + if font_style.get_italic(): f_style = Pango.Style.ITALIC else: f_style = Pango.Style.NORMAL - + font_description = Pango.FontDescription(font_families[font_style.face]) font_description.set_size(int(round(font_style.get_size() * Pango.SCALE))) font_description.set_weight(f_weight) font_description.set_style(f_style) - + return font_description def tabstops_to_tabarray(tab_stops, dpi): @@ -170,11 +170,11 @@ def tabstops_to_tabarray(tab_stops, dpi): """ tab_array = Pango.TabArray.new(initial_size=len(tab_stops), positions_in_pixels=False) - + for index in range(len(tab_stops)): location = tab_stops[index] * dpi * Pango.SCALE / 2.54 tab_array.set_tab(index, Pango.TabAlign.LEFT, int(location)) - + return tab_array def raw_length(s): @@ -194,16 +194,16 @@ def raw_length(s): ### Table row style ### ###------------------------------------------------------------------------ - + ##class RowStyle(list): ##"""Specifies the format of a table row. - - ##RowStyle extents the available styles in - + + ##RowStyle extents the available styles in + ##The RowStyle contains the width of each column as a percentage of the ##width of the full row. Note! The width of the row is not known until ##divide() or draw() method is called. - + ##""" ##def __init__(self): ##self.columns = [] @@ -213,21 +213,21 @@ def raw_length(s): ##@param columns: number of columns that should be used. ##@param type: int - + ##""" ##self.columns = columns ##def get_columns(self): ##"""Return the number of columns. ##""" - ##return self.columns + ##return self.columns ##def set_column_widths(self, clist): ##"""Set the width of all the columns at once. - + ##@param clist: list of width of columns in % of the full row. ##@param tyle: list - + ##""" ##self.columns = len(clist) ##for i in range(self.columns): @@ -253,89 +253,89 @@ def raw_length(s): class FrameStyle(object): """Define the style properties of a Frame. - + - width: Width of the frame in cm. - height: Height of the frame in cm. - align: Horizontal position to entire page. Available values: 'left','center', 'right'. - spacing: Tuple of spacing around the frame in cm. Order of values: (left, right, top, bottom). - + """ def __init__(self, width=0, height=0, align='left', spacing=(0, 0, 0, 0)): self.width = width self.height = height self.align = align self.spacing = spacing - + #------------------------------------------------------------------------ # # Document element classes # #------------------------------------------------------------------------ - + class GtkDocBaseElement(object): """Base of all document elements. - + Support document element structuring and can render itself onto a Cairo surface. - + There are two categories of methods: 1. hierarchy building methods (add_child, get_children, set_parent, get_parent); 2. rendering methods (divide, draw). - + The hierarchy building methods generally don't have to be overridden in the subclass, while the rendering methods (divide, draw) must be implemented in the subclasses. - + """ _type = 'BASE' _allowed_children = [] - + def __init__(self, style=None): self._parent = None self._children = [] self._style = style - + def get_type(self): """Get the type of this element. """ return self._type - + def set_parent(self, parent): """Set the parent element of this element. """ self._parent = parent - + def get_parent(self): """Get the parent element of this element. """ return self._parent - + def add_child(self, element): """Add a child element. - + Returns False if the child cannot be added (e.g. not an allowed type), or True otherwise. - + """ # check if it is an allowed child for this type if element.get_type() not in self._allowed_children: log.debug("%r is not an allowed child for %r" % (element.__class__, self.__class__)) return False - + # append the child and set its parent self._children.append(element) element.set_parent(self) return True - + def get_children(self): """Get the list of children of this element. """ return self._children - + def get_marks(self): """Get the list of index marks for this element. """ @@ -346,7 +346,7 @@ class GtkDocBaseElement(object): def divide(self, layout, width, height, dpi_x, dpi_y): """Divide the element into two depending on available space. - + @param layout: pango layout to write on @param type: Pango.Layout @param width: width of available space for this element @@ -357,16 +357,16 @@ class GtkDocBaseElement(object): @param type: dots per inch @param dpi_y: the vertical resolution @param type: dots per inch - + @return: the divided element, and the height of the first part @rtype: (GtkDocXXX-1, GtkDocXXX-2), device points - + """ raise NotImplementedError - + def draw(self, cairo_context, pango_layout, width, dpi_x, dpi_y): """Draw itself onto a cairo surface. - + @param cairo_context: context to draw on @param type: cairo.Context class @param pango_layout: pango layout to write on @@ -376,31 +376,31 @@ class GtkDocBaseElement(object): @param dpi_x: the horizontal resolution @param type: dots per inch @param dpi_y: the vertical resolution - @param type: dots per inch - + @param type: dots per inch + @return: height of the element @rtype: device points - + """ raise NotImplementedError - + class GtkDocDocument(GtkDocBaseElement): """The whole document or a page. """ _type = 'DOCUMENT' _allowed_children = ['PARAGRAPH', 'PAGEBREAK', 'TABLE', 'IMAGE', 'FRAME', 'TOC', 'INDEX'] - + def draw(self, cairo_context, pango_layout, width, dpi_x, dpi_y): - + x = y = elem_height = 0 - + for elem in self._children: cairo_context.translate(x, elem_height) elem_height = elem.draw(cairo_context, pango_layout, width, dpi_x, dpi_y) y += elem_height - + return y def has_toc(self): @@ -420,16 +420,16 @@ class GtkDocPagebreak(GtkDocBaseElement): """ _type = 'PAGEBREAK' _allowed_children = [] - + def divide(self, layout, width, height, dpi_x, dpi_y): return (None, None), 0 - + class GtkDocTableOfContents(GtkDocBaseElement): """Implement a table of contents. """ _type = 'TOC' _allowed_children = [] - + def divide(self, layout, width, height, dpi_x, dpi_y): return (self, None), 0 @@ -441,7 +441,7 @@ class GtkDocAlphabeticalIndex(GtkDocBaseElement): """ _type = 'INDEX' _allowed_children = [] - + def divide(self, layout, width, height, dpi_x, dpi_y): return (self, None), 0 @@ -453,10 +453,10 @@ class GtkDocParagraph(GtkDocBaseElement): """ _type = 'PARAGRAPH' _allowed_children = [] - + # line spacing is not defined in ParagraphStyle spacingfractionfont = 0.2 - + def __init__(self, style, leader=None): GtkDocBaseElement.__init__(self, style) @@ -466,18 +466,18 @@ class GtkDocParagraph(GtkDocBaseElement): self._style.set_tabs([-1 * self._style.get_first_indent()]) else: self._text = '' - + self._plaintext = None self._attrlist = None - + self._marklist = [] - + def add_text(self, text): if self._plaintext is not None: raise PluginError('CairoDoc: text is already parsed.' ' You cannot add text anymore') self._text = self._text + text - + def add_mark(self, mark): """ Add an index mark to this paragraph @@ -504,25 +504,25 @@ class GtkDocParagraph(GtkDocBaseElement): self._plaintext = conv_to_unicode(plaintext, 'utf-8') else: self._plaintext = plaintext - + def __set_attrlist(self, attrlist): """ Internal method to allow for splitting of paragraphs """ self._attrlist = attrlist - + def __parse_text(self): """ - Parse the markup text. This method will only do this if not + Parse the markup text. This method will only do this if not done already """ if self._plaintext is None: parse_ok, self._attrlist, self._plaintext, accel_char= \ Pango.parse_markup(self._text, -1, '\000') - + def divide(self, layout, width, height, dpi_x, dpi_y): self.__parse_text() - + l_margin = self._style.get_left_margin() * dpi_x / 2.54 r_margin = self._style.get_right_margin() * dpi_x / 2.54 t_margin = self._style.get_top_margin() * dpi_y / 2.54 @@ -530,15 +530,15 @@ class GtkDocParagraph(GtkDocBaseElement): h_padding = self._style.get_padding() * dpi_x / 2.54 v_padding = self._style.get_padding() * dpi_y / 2.54 f_indent = self._style.get_first_indent() * dpi_x / 2.54 - + # calculate real width available for text text_width = width - l_margin - 2 * h_padding - r_margin if f_indent < 0: text_width -= f_indent layout.set_width(int(text_width * Pango.SCALE)) - + # set paragraph properties - layout.set_wrap(Pango.WrapMode.WORD_CHAR) + layout.set_wrap(Pango.WrapMode.WORD_CHAR) layout.set_indent(int(f_indent * Pango.SCALE)) layout.set_tabs(tabstops_to_tabarray(self._style.get_tabs(), dpi_x)) # @@ -553,7 +553,7 @@ class GtkDocParagraph(GtkDocBaseElement): layout.set_justify(False) layout.set_alignment(Pango.Alignment.CENTER) elif align == 'justify': - #We have a problem, in pango, justify works only on full lines, + #We have a problem, in pango, justify works only on full lines, # and we need an alignment for the partial lines. We don't know # for justify what alignment the user wants however. We assume # here LEFT ... @@ -567,32 +567,32 @@ class GtkDocParagraph(GtkDocBaseElement): #set line spacing based on font: spacing = font_style.get_size() * self.spacingfractionfont layout.set_spacing(int(round(spacing * Pango.SCALE))) - + text_height = height - t_margin - 2 * v_padding - + # calculate where to cut the paragraph layout.set_text(self._plaintext, -1) layout.set_attributes(self._attrlist) layout_width, layout_height = layout.get_pixel_size() line_count = layout.get_line_count() spacing = layout.get_spacing() / Pango.SCALE - + # if all paragraph fits we don't need to cut if layout_height - spacing <= text_height: paragraph_height = layout_height + spacing +t_margin + (2 * v_padding) if height - paragraph_height > b_margin: paragraph_height += b_margin return (self, None), paragraph_height - + # we need to cut paragraph: - + # 1. if paragraph part of a cell, we do not divide if only small part, # of paragraph can be shown, instead move to next page if line_count < 4 and self._parent._type == 'CELL': return (None, self), 0 - + lineiter = layout.get_iter() - + linenr = 0 linerange = lineiter.get_line_yrange() # 2. if nothing fits, move to next page without split @@ -600,7 +600,7 @@ class GtkDocParagraph(GtkDocBaseElement): if linerange[1] - linerange[0] + 2.*spacing \ > text_height * Pango.SCALE: return (None, self), 0 - + # 3. split the paragraph startheight = linerange[0] endheight = linerange[1] @@ -638,9 +638,9 @@ class GtkDocParagraph(GtkDocBaseElement): #now recalculate the attrilist: newattrlist = layout.get_attributes().copy() newattrlist.filter(self.filterattr, index) - + ## GTK3 PROBLEM: get_iterator no longer available!! -## REFERENCES: +## REFERENCES: ## http://www.gramps-project.org/bugs/view.php?id=6208 ## https://bugzilla.gnome.org/show_bug.cgi?id=646788 ## workaround: https://github.com/matasbbb/pitivit/commit/da815339e5ce3631b122a72158ba9ffcc9ee4372 @@ -713,7 +713,7 @@ class GtkDocParagraph(GtkDocBaseElement): def draw(self, cr, layout, width, dpi_x, dpi_y): self.__parse_text() - + l_margin = self._style.get_left_margin() * dpi_x / 2.54 r_margin = self._style.get_right_margin() * dpi_x / 2.54 t_margin = self._style.get_top_margin() * dpi_y / 2.54 @@ -721,13 +721,13 @@ class GtkDocParagraph(GtkDocBaseElement): h_padding = self._style.get_padding() * dpi_x / 2.54 v_padding = self._style.get_padding() * dpi_y / 2.54 f_indent = self._style.get_first_indent() * dpi_x / 2.54 - + # calculate real width available for text text_width = width - l_margin - 2 * h_padding - r_margin if f_indent < 0: text_width -= f_indent layout.set_width(int(text_width * Pango.SCALE)) - + # set paragraph properties layout.set_wrap(Pango.WrapMode.WORD_CHAR) layout.set_indent(int(f_indent * Pango.SCALE)) @@ -744,7 +744,7 @@ class GtkDocParagraph(GtkDocBaseElement): layout.set_justify(False) layout.set_alignment(Pango.Alignment.CENTER) elif align == 'justify': - #We have a problem, in pango, justify works only on full lines, + #We have a problem, in pango, justify works only on full lines, # and we need an alignment for the partial lines. We don't know # for justify what alignment the user wants however. We assume # here LEFT ... @@ -761,7 +761,7 @@ class GtkDocParagraph(GtkDocBaseElement): layout.set_text(self._plaintext, -1) layout.set_attributes(self._attrlist) layout_width, layout_height = layout.get_pixel_size() - + # render the layout onto the cairo surface x = l_margin + h_padding if f_indent < 0: @@ -770,7 +770,7 @@ class GtkDocParagraph(GtkDocBaseElement): cr.move_to(x, t_margin + v_padding + spacing * 0.75) cr.set_source_rgb(*ReportUtils.rgb_color(font_style.get_color())) PangoCairo.show_layout(cr, layout) - + # calculate the full paragraph height height = layout_height + spacing + t_margin + 2*v_padding + b_margin @@ -791,7 +791,7 @@ class GtkDocParagraph(GtkDocBaseElement): cr.set_line_width(1) cr.set_source_rgb(0, 0, 0) cr.stroke() - + if DEBUG: cr.set_line_width(0.1) cr.set_source_rgb(1.0, 0, 0) @@ -801,19 +801,19 @@ class GtkDocParagraph(GtkDocBaseElement): cr.rectangle(l_margin, t_margin, width-l_margin-r_margin, height-t_margin-b_margin) cr.stroke() - + return height - + class GtkDocTable(GtkDocBaseElement): """Implement a table. """ _type = 'TABLE' _allowed_children = ['ROW'] - + def divide(self, layout, width, height, dpi_x, dpi_y): #calculate real table width table_width = width * self._style.get_width() / 100 - + # calculate the height of each row table_height = 0 row_index = 0 @@ -827,7 +827,7 @@ class GtkDocTable(GtkDocBaseElement): table_height += row_height row_index += 1 height -= row_height - + # divide the table if any row did not fit new_table = None if row_index < len(self._children): @@ -836,15 +836,15 @@ class GtkDocTable(GtkDocBaseElement): new_table.add_child(r2) list(map(new_table.add_child, self._children[row_index+1:])) del self._children[row_index+1:] - + return (self, new_table), table_height - + def draw(self, cr, layout, width, dpi_x, dpi_y): #calculate real table width table_width = width * self._style.get_width() / 100 # TODO is a table always left aligned?? table_height = 0 - + # draw all the rows for row in self._children: cr.save() @@ -852,7 +852,7 @@ class GtkDocTable(GtkDocBaseElement): row_height = row.draw(cr, layout, table_width, dpi_x, dpi_y) cr.restore() table_height += row_height - + if DEBUG: cr.set_line_width(0.1) cr.set_source_rgb(1.0, 0, 0) @@ -887,11 +887,11 @@ class GtkDocTableRow(GtkDocBaseElement): else: dividedrow = True new_row.add_child(c2) - + # save height [inch] of the row to be able to draw exact cell border row_height = max(cell_heights) self.height = row_height / dpi_y - + # return the new row if dividing was needed if dividedrow: if row_height == 0: @@ -902,7 +902,7 @@ class GtkDocTableRow(GtkDocBaseElement): return (self, new_row), row_height else: return (self, None), row_height - + def draw(self, cr, layout, width, dpi_x, dpi_y): cr.save() @@ -925,7 +925,7 @@ class GtkDocTableRow(GtkDocBaseElement): cr.set_source_rgb(0, 0, 1.0) cr.rectangle(0, 0, width, row_height) cr.stroke() - + return row_height class GtkDocTableCell(GtkDocBaseElement): @@ -933,14 +933,14 @@ class GtkDocTableCell(GtkDocBaseElement): """ _type = 'CELL' _allowed_children = ['PARAGRAPH', 'IMAGE'] - + def __init__(self, style, span=1): GtkDocBaseElement.__init__(self, style) self._span = span def get_span(self): return self._span - + def divide(self, layout, width, height, dpi_x, dpi_y): h_padding = self._style.get_padding() * dpi_x / 2.54 v_padding = self._style.get_padding() * dpi_y / 2.54 @@ -953,11 +953,11 @@ class GtkDocTableCell(GtkDocBaseElement): cell_height = 0 new_cell = None e2 = None - + childnr = 0 for child in self._children: if new_cell is None: - (e1, e2), child_height = child.divide(layout, width, + (e1, e2), child_height = child.divide(layout, width, available_height, dpi_x, dpi_y) cell_height += child_height available_height -= child_height @@ -975,31 +975,31 @@ class GtkDocTableCell(GtkDocBaseElement): else: #cell has been divided new_cell.add_child(child) - + self._children = self._children[:childnr] # calculate real height if cell_height != 0: cell_height += 2 * v_padding - + # a cell can't be divided, return the height return (self, new_cell), cell_height - + def draw(self, cr, layout, width, cell_height, dpi_x, dpi_y): """Draw a cell. - + This draw method is a bit different from the others, as common cell height of all cells in a row is also given as parameter. This is needed to be able to draw proper vertical borders around each cell, i.e. the border should be as long as the highest cell in the given row. - + """ h_padding = self._style.get_padding() * dpi_x / 2.54 v_padding = self._style.get_padding() * dpi_y / 2.54 # calculate real available width i_width = width - 2 * h_padding - + # draw children cr.save() cr.translate(h_padding, v_padding) @@ -1007,7 +1007,7 @@ class GtkDocTableCell(GtkDocBaseElement): child_height = child.draw(cr, layout, i_width, dpi_x, dpi_y) cr.translate(0, child_height) cr.restore() - + # draw the borders if self._style.get_top_border(): cr.move_to(0, 0) @@ -1025,13 +1025,13 @@ class GtkDocTableCell(GtkDocBaseElement): cr.set_line_width(1) cr.set_source_rgb(0, 0, 0) cr.stroke() - + if DEBUG: cr.set_line_width(0.1) cr.set_source_rgb(0, 1.0, 0) cr.rectangle(0, 0, width, cell_height) cr.stroke() - + return cell_height class GtkDocPicture(GtkDocBaseElement): @@ -1039,18 +1039,18 @@ class GtkDocPicture(GtkDocBaseElement): """ _type = 'IMAGE' _allowed_children = [] - + def __init__(self, style, filename, width, height, crop=None): GtkDocBaseElement.__init__(self, style) self._filename = filename self._width = width self._height = height self._crop = crop - + def divide(self, layout, width, height, dpi_x, dpi_y): img_width = self._width * dpi_x / 2.54 img_height = self._height * dpi_y / 2.54 - + # image can't be divided, a new page must begin # if it can't fit on the current one if img_height <= height: @@ -1062,28 +1062,28 @@ class GtkDocPicture(GtkDocBaseElement): from gi.repository import Gtk, Gdk img_width = self._width * dpi_x / 2.54 img_height = self._height * dpi_y / 2.54 - + if self._style == 'right': l_margin = width - img_width elif self._style == 'center': l_margin = (width - img_width) / 2.0 else: l_margin = 0 - + # load the image and get its extents - pixbuf = resize_to_buffer(self._filename, [img_width, img_height], + pixbuf = resize_to_buffer(self._filename, [img_width, img_height], self._crop) pixbuf_width = pixbuf.get_width() pixbuf_height = pixbuf.get_height() - + # calculate the scale to fit image into the set extents scale = min(img_width / pixbuf_width, img_height / pixbuf_height) - + # draw the image cr.save() cr.translate(l_margin, 0) cr.scale(scale, scale) - Gdk.cairo_set_source_pixbuf(cr, pixbuf, + Gdk.cairo_set_source_pixbuf(cr, pixbuf, (img_width / scale - pixbuf_width) / 2, (img_height / scale - pixbuf_height) / 2) cr.rectangle(0 , 0, img_width / scale, img_height / scale) @@ -1094,7 +1094,7 @@ class GtkDocPicture(GtkDocBaseElement): ##cr.scale(scale, scale) cr.fill() cr.restore() - + if DEBUG: cr.set_line_width(0.1) cr.set_source_rgb(1.0, 0, 0) @@ -1114,7 +1114,7 @@ class GtkDocFrame(GtkDocBaseElement): frame_height = round(self._style.height * dpi_y / 2.54) t_margin = self._style.spacing[2] * dpi_y / 2.54 b_margin = self._style.spacing[3] * dpi_y / 2.54 - + # frame can't be divided, a new page must begin # if it can't fit on the current one if frame_height + t_margin + b_margin <= height: @@ -1131,7 +1131,7 @@ class GtkDocFrame(GtkDocBaseElement): r_margin = self._style.spacing[1] * dpi_x / 2.54 t_margin = self._style.spacing[2] * dpi_y / 2.54 b_margin = self._style.spacing[3] * dpi_y / 2.54 - + if self._style.align == 'left': x_offset = l_margin elif self._style.align == 'right': @@ -1146,10 +1146,10 @@ class GtkDocFrame(GtkDocBaseElement): cr.translate(x_offset, t_margin) cr.rectangle(0, 0, frame_width, frame_height) cr.clip() - + for elem in self._children: elem.draw(cr, layout, frame_width, dpi_x, dpi_y) - + cr.restore() if DEBUG: @@ -1159,7 +1159,7 @@ class GtkDocFrame(GtkDocBaseElement): cr.stroke() return frame_height + t_margin + b_margin - + class GtkDocLine(GtkDocBaseElement): """Implement a line. """ @@ -1170,12 +1170,12 @@ class GtkDocLine(GtkDocBaseElement): GtkDocBaseElement.__init__(self, style) self._start = (x1, y1) self._end = (x2, y2) - + def draw(self, cr, layout, width, dpi_x, dpi_y): start = (self._start[0] * dpi_x / 2.54, self._start[1] * dpi_y / 2.54) end = (self._end[0] * dpi_x / 2.54, self._end[1] * dpi_y / 2.54) line_color = ReportUtils.rgb_color(self._style.get_color()) - + cr.save() cr.set_source_rgb(*line_color) cr.set_line_width(self._style.get_line_width()) @@ -1187,7 +1187,7 @@ class GtkDocLine(GtkDocBaseElement): cr.line_to(*end) cr.stroke() cr.restore() - + return 0 class GtkDocPolygon(GtkDocBaseElement): @@ -1199,13 +1199,13 @@ class GtkDocPolygon(GtkDocBaseElement): def __init__(self, style, path): GtkDocBaseElement.__init__(self, style) self._path = path - + def draw(self, cr, layout, width, dpi_x, dpi_y): path = [(x * dpi_x / 2.54, y * dpi_y / 2.54) for (x, y) in self._path] path_start = path.pop(0) path_stroke_color = ReportUtils.rgb_color(self._style.get_color()) path_fill_color = ReportUtils.rgb_color(self._style.get_fill_color()) - + cr.save() cr.move_to(*path_start) for (x, y) in path: @@ -1221,9 +1221,9 @@ class GtkDocPolygon(GtkDocBaseElement): cr.set_dash(self._style.get_dash_style(line_style), 0) cr.stroke() cr.restore() - + return 0 - + class GtkDocBox(GtkDocBaseElement): """Implement a box with optional shadow around it. """ @@ -1236,19 +1236,19 @@ class GtkDocBox(GtkDocBaseElement): self._y = y self._width = width self._height = height - + def draw(self, cr, layout, width, dpi_x, dpi_y): box_x = self._x * dpi_x / 2.54 box_y = self._y * dpi_y / 2.54 box_width = self._width * dpi_x / 2.54 box_height = self._height * dpi_y / 2.54 - + box_stroke_color = ReportUtils.rgb_color((0, 0, 0)) box_fill_color = ReportUtils.rgb_color(self._style.get_fill_color()) shadow_color = ReportUtils.rgb_color((192, 192, 192)) - + cr.save() - + cr.set_line_width(self._style.get_line_width()) # TODO line style line_style = self._style.get_line_style() @@ -1262,7 +1262,7 @@ class GtkDocBox(GtkDocBaseElement): cr.set_source_rgb(*shadow_color) cr.rectangle(shadow_x, shadow_y, box_width, box_height) cr.fill() - + cr.rectangle(box_x, box_y, box_width, box_height) cr.set_source_rgb(*box_fill_color) cr.fill_preserve() @@ -1270,9 +1270,9 @@ class GtkDocBox(GtkDocBaseElement): cr.stroke() cr.restore() - + return 0 - + class GtkDocText(GtkDocBaseElement): """Implement a text on graphical reports. """ @@ -1281,7 +1281,7 @@ class GtkDocText(GtkDocBaseElement): # line spacing is not defined in ParagraphStyle spacingfractionfont = 0.2 - + def __init__(self, style, vertical_alignment, text, x, y, angle=0, mark=None): GtkDocBaseElement.__init__(self, style) @@ -1293,14 +1293,14 @@ class GtkDocText(GtkDocBaseElement): self._marklist = [] if mark: self._marklist = [mark] - + def draw(self, cr, layout, width, dpi_x, dpi_y): text_x = self._x * dpi_x / 2.54 text_y = self._y * dpi_y / 2.54 # turn off text wrapping layout.set_width(-1) - + # set paragraph properties align = self._style.get_alignment_text() if align == 'left': @@ -1313,7 +1313,7 @@ class GtkDocText(GtkDocBaseElement): layout.set_justify(False) layout.set_alignment(Pango.Alignment.CENTER) elif align == 'justify': - #We have a problem, in pango, justify works only on full lines, + #We have a problem, in pango, justify works only on full lines, # and we need an alignment for the partial lines. We don't know # for justify what alignment the user wants however. We assume # here CENTER ... @@ -1350,7 +1350,7 @@ class GtkDocText(GtkDocBaseElement): align_y = - layout_height else: raise ValueError - + # render the layout onto the cairo surface cr.save() cr.translate(text_x, text_y) @@ -1375,31 +1375,31 @@ class GtkDocText(GtkDocBaseElement): #------------------------------------------------------------------------ class CairoDoc(BaseDoc, TextDoc, DrawDoc): """Act as an abstract document that can render onto a cairo context. - + Maintains an abstract model of the document. The root of this abstract document is self._doc. The model is build via the subclassed BaseDoc, and the implemented TextDoc, DrawDoc interface methods. - + It can render the model onto cairo context pages, according to the received page style. - + """ - + # BaseDoc implementation - EXT = 'pdf' - + EXT = 'pdf' + def open(self, filename): fe = filename.split('.') if len(fe) == 1: filename = filename + '.' + self.EXT elif fe[-1] != self.EXT: - # NOTE: the warning will be bogus + # NOTE: the warning will be bogus # if the EXT isn't properly overridden by derived class log.warn(_( """Mismatch between selected extension %(ext)s and actual format. - Writing to %(filename)s in format %(impliedext)s.""") % - {'ext' : fe[-1], - 'filename' : filename, + Writing to %(filename)s in format %(impliedext)s.""") % + {'ext' : fe[-1], + 'filename' : filename, 'impliedext' : self.EXT} ) self._backend = CairoBackend(filename) self._doc = GtkDocDocument() @@ -1407,77 +1407,77 @@ class CairoDoc(BaseDoc, TextDoc, DrawDoc): self._pages = [] self._elements_to_paginate = [] self._links_error = False - + def close(self): self.run() # TextDoc implementation - + def page_break(self): self._active_element.add_child(GtkDocPagebreak()) def start_bold(self): self.__write_text('', markup=True) - + def end_bold(self): self.__write_text('', markup=True) - + def start_superscript(self): self.__write_text('', markup=True) - + def end_superscript(self): self.__write_text('', markup=True) - + def start_paragraph(self, style_name, leader=None): style_sheet = self.get_style_sheet() style = style_sheet.get_paragraph_style(style_name) - + new_paragraph = GtkDocParagraph(style, leader) self._active_element.add_child(new_paragraph) self._active_element = new_paragraph - + def end_paragraph(self): self._active_element = self._active_element.get_parent() - + def start_table(self, name, style_name): style_sheet = self.get_style_sheet() style = style_sheet.get_table_style(style_name) - + new_table = GtkDocTable(style) self._active_element.add_child(new_table) self._active_element = new_table - + # we need to remember the column width list from the table style. # this is an ugly hack, but got no better idea. self._active_row_style = list(map(style.get_column_width, list(range(style.get_columns())))) - + def end_table(self): self._active_element = self._active_element.get_parent() - + def start_row(self): new_row = GtkDocTableRow(self._active_row_style) self._active_element.add_child(new_row) self._active_element = new_row - + def end_row(self): self._active_element = self._active_element.get_parent() - + def start_cell(self, style_name, span=1): style_sheet = self.get_style_sheet() style = style_sheet.get_cell_style(style_name) - + new_cell = GtkDocTableCell(style, span) self._active_element.add_child(new_cell) self._active_element = new_cell - + def end_cell(self): self._active_element = self._active_element.get_parent() def write_styled_note(self, styledtext, format, style_name, contains_html=False, links=False): """ - Convenience function to write a styledtext to the cairo doc. + Convenience function to write a styledtext to the cairo doc. styledtext : assumed a StyledText object to write format : = 0 : Flowed, = 1 : Preformatted style_name : name of the style to use for default presentation @@ -1491,7 +1491,7 @@ class CairoDoc(BaseDoc, TextDoc, DrawDoc): s_tags = styledtext.get_tags() #FIXME: following split should be regex to match \n\s*\n instead? - markuptext = self._backend.add_markup_from_styled(text, s_tags, + markuptext = self._backend.add_markup_from_styled(text, s_tags, split='\n\n') if format == 1: @@ -1514,12 +1514,12 @@ class CairoDoc(BaseDoc, TextDoc, DrawDoc): newlines.append(' '.join(singleline.split())) self.__write_text('\n'.join(newlines), markup=True, links=links) self.end_paragraph() - + def __markup(self, text, markup=None): - if not markup: + if not markup: # We need to escape the text here for later Pango.Layout.set_markup # calls. This way we save the markup created by the report - # The markup in the note editor is not in the text so is not + # The markup in the note editor is not in the text so is not # considered. It must be added by pango too text = self._backend.ESCAPE_FUNC()(text) return text @@ -1528,7 +1528,7 @@ class CairoDoc(BaseDoc, TextDoc, DrawDoc): """ @param text: text to write. @param mark: IndexMark to use for indexing - @param markup: True if text already contains markup info. + @param markup: True if text already contains markup info. Then text will no longer be escaped @param links: True if URLs should be made clickable """ @@ -1564,12 +1564,12 @@ links (like ODF) and write PDF from that format. @param links: True if URLs should be made clickable """ self.__write_text(text, mark, links=links) - + def write_markup(self, text, s_tags, mark=None): """ Writes the text in the current paragraph. Should only be used after a - start_paragraph and before an end_paragraph. - + start_paragraph and before an end_paragraph. + @param text: text to write. The text is assumed to be _not_ escaped @param s_tags: assumed to be list of styledtexttags to apply to the text @@ -1577,8 +1577,8 @@ links (like ODF) and write PDF from that format. """ markuptext = self._backend.add_markup_from_styled(text, s_tags) self.__write_text(markuptext, mark=mark, markup=True) - - def add_media_object(self, name, pos, x_cm, y_cm, alt='', + + def add_media_object(self, name, pos, x_cm, y_cm, alt='', style_name=None, crop=None): new_image = GtkDocPicture(pos, name, x_cm, y_cm, crop=crop) self._active_element.add_child(new_image) @@ -1610,23 +1610,23 @@ links (like ODF) and write PDF from that format. self._doc.add_child(GtkDocAlphabeticalIndex()) # DrawDoc implementation - + def start_page(self): # if this is not the first page we need to "close" the previous one children = self._doc.get_children() if children and children[-1].get_type() != 'PAGEBREAK': self._doc.add_child(GtkDocPagebreak()) - + new_frame_style = FrameStyle(width=self.get_usable_width(), height=self.get_usable_height()) new_frame = GtkDocFrame(new_frame_style) - + self._active_element.add_child(new_frame) self._active_element = new_frame - + def end_page(self): self._active_element = self._active_element.get_parent() - + def draw_line(self, style_name, x1, y1, x2, y2): style_sheet = self.get_style_sheet() style = style_sheet.get_draw_style(style_name) @@ -1640,7 +1640,7 @@ links (like ODF) and write PDF from that format. new_polygon = GtkDocPolygon(style, path) self._active_element.add_child(new_polygon) - + def draw_box(self, style_name, text, x, y, w, h, mark=None): """ @param mark: IndexMark to use for indexing """ # we handle the box and... @@ -1655,19 +1655,19 @@ links (like ODF) and write PDF from that format. if paragraph_style_name: paragraph_style = style_sheet.get_paragraph_style(paragraph_style_name) paragraph_style.set_alignment(PARA_ALIGN_LEFT) - + # horizontal position of the text is not included in the style, # we assume that it is the size of the shadow, or 0.2mm if style.get_shadow(): x_offset = style.get_shadow_space() else: x_offset = 0.2 - - new_text = GtkDocText(paragraph_style, 'center', + + new_text = GtkDocText(paragraph_style, 'center', self.__markup(text), x + x_offset, y + h / 2, angle=0, mark=mark) self._active_element.add_child(new_text) - + def draw_text(self, style_name, text, x, y, mark=None): """ @param mark: IndexMark to use for indexing """ style_sheet = self.get_style_sheet() @@ -1675,11 +1675,11 @@ links (like ODF) and write PDF from that format. paragraph_style_name = style.get_paragraph_style() paragraph_style = style_sheet.get_paragraph_style(paragraph_style_name) paragraph_style.set_alignment(PARA_ALIGN_LEFT) - - new_text = GtkDocText(paragraph_style, 'top', + + new_text = GtkDocText(paragraph_style, 'top', self.__markup(text), x, y, angle=0, mark=mark) self._active_element.add_child(new_text) - + def center_text(self, style_name, text, x, y, mark=None): """ @param mark: IndexMark to use for indexing """ style_sheet = self.get_style_sheet() @@ -1687,11 +1687,11 @@ links (like ODF) and write PDF from that format. paragraph_style_name = style.get_paragraph_style() paragraph_style = style_sheet.get_paragraph_style(paragraph_style_name) paragraph_style.set_alignment(PARA_ALIGN_CENTER) - - new_text = GtkDocText(paragraph_style, 'top', + + new_text = GtkDocText(paragraph_style, 'top', self.__markup(text), x, y, angle=0, mark=mark) self._active_element.add_child(new_text) - + def rotate_text(self, style_name, text, x, y, angle, mark=None): """ @param mark: IndexMark to use for indexing """ style_sheet = self.get_style_sheet() @@ -1699,20 +1699,20 @@ links (like ODF) and write PDF from that format. paragraph_style_name = style.get_paragraph_style() paragraph_style = style_sheet.get_paragraph_style(paragraph_style_name) paragraph_style.set_alignment(PARA_ALIGN_CENTER) - - new_text = GtkDocText(paragraph_style, 'center', + + new_text = GtkDocText(paragraph_style, 'center', self.__markup('\n'.join(text)), x, y, angle, mark) self._active_element.add_child(new_text) - + # paginating and drawing interface - + def run(self): """Create the physical output from the meta document. - + It must be implemented in the subclasses. The idea is that with different subclass different output could be generated: e.g. Print, PDF, PS, PNG (which are currently supported by Cairo). - + """ raise NotImplementedError @@ -1724,7 +1724,7 @@ links (like ODF) and write PDF from that format. def paginate(self, layout, page_width, page_height, dpi_x, dpi_y): """Paginate the meta document in chunks. - + Only one document level element is handled at one run. """ @@ -1733,7 +1733,7 @@ links (like ODF) and write PDF from that format. self._elements_to_paginate = self._doc.get_children()[:] self._pages.append(GtkDocDocument()) self._available_height = page_height - + # try to fit the next element to current page, divide it if needed if not self._elements_to_paginate: #this is a self._doc where nothing has been added. Empty page. @@ -1760,9 +1760,9 @@ links (like ODF) and write PDF from that format. if (e1 is None) or (e2 is not None): self._pages.append(GtkDocDocument()) self._available_height = page_height - + return len(self._elements_to_paginate) == 0 - + def draw_page(self, page_nr, cr, layout, width, height, dpi_x, dpi_y): """Draw a page on a Cairo context. """ diff --git a/gramps/plugins/lib/libgedcom.py b/gramps/plugins/lib/libgedcom.py index 863e8c791..b9f09e984 100644 --- a/gramps/plugins/lib/libgedcom.py +++ b/gramps/plugins/lib/libgedcom.py @@ -11,7 +11,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -36,9 +36,9 @@ parsing techniques, such as LALR. The LEVEL token implies too much to be useful in this context. While this makes parsing more difficult, it does provide one very beneficial feature for GEDCOM: Error recoverability. GEDCOM is a poorly implemented standard, primarily because it is a poor -standard to begin with. +standard to begin with. -Most commercial applications that implement GEDCOM output add custom +Most commercial applications that implement GEDCOM output add custom extensions, and feel free to violate the existing structure. If one were cynical, one might believe that the commercial programs were trying to make it difficult to transfer your data to another application. @@ -51,17 +51,17 @@ parser contains: Level, Token, Token text, Data, and line number. -The Data field is typically text, but in some cases, it may be a integer +The Data field is typically text, but in some cases, it may be a integer value representing an enumerated type or a GRAMPS object (in the case of dates). -The parser works on the current level. Each context and level has a an +The parser works on the current level. Each context and level has a an associated table (dictionary) of functions indexed by the corresponding TOKEN. When a token is found, we index into the table to find the function associated with the token. If no token is found, a function that skips the -line and all subordinate (lines with a higher number). If a function is +line and all subordinate (lines with a higher number). If a function is found, then we call that function, which in turn processes the line, and -all tokens at the lower level. +all tokens at the lower level. For example: @@ -71,14 +71,14 @@ For example: 3 NOTE DATA The function parsing the individual at level 1, would encounter the BIRT tag. -It would look up the BIRT token in the table to see if a function as defined +It would look up the BIRT token in the table to see if a function as defined for this TOKEN, and pass control to this function. This function would then -start parsing level 2. It would encounter the DATE tag, look up the -corresponding function in the level 2 table, and pass control to its +start parsing level 2. It would encounter the DATE tag, look up the +corresponding function in the level 2 table, and pass control to its associated function. This function would terminate, and return control back to the level 2 parser, which would then encounter the "UKNOWN" tag. Since this is not a valid token, it would not be in the table, and a function that would skip -all lines until the next level 2 token is found (in this case, skipping the +all lines until the next level 2 token is found (in this case, skipping the "3 NOTE DATA" line. """ @@ -114,7 +114,7 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gen.errors import GedcomError from gramps.gen.const import DATA_DIR -from gramps.gen.lib import (Address, Attribute, AttributeType, ChildRef, +from gramps.gen.lib import (Address, Attribute, AttributeType, ChildRef, ChildRefType, Citation, Date, Event, EventRef, EventRoleType, EventType, Family, FamilyRelType, LdsOrd, Location, MediaObject, MediaRef, Name, NameType, Note, NoteType, Person, PersonRef, Place, @@ -406,52 +406,52 @@ TYPE_ADOPT = ChildRefType(ChildRefType.ADOPTED) TYPE_FOSTER = ChildRefType(ChildRefType.FOSTER) RELATION_TYPES = ( - ChildRefType.BIRTH, - ChildRefType.UNKNOWN, - ChildRefType.NONE, + ChildRefType.BIRTH, + ChildRefType.UNKNOWN, + ChildRefType.NONE, ) PEDIGREE_TYPES = { - 'birth' : ChildRefType(), - 'natural': ChildRefType(), - 'step' : TYPE_ADOPT, - 'adopted': TYPE_ADOPT, - 'foster' : TYPE_FOSTER, + 'birth' : ChildRefType(), + 'natural': ChildRefType(), + 'step' : TYPE_ADOPT, + 'adopted': TYPE_ADOPT, + 'foster' : TYPE_FOSTER, } MIME_MAP = { - 'jpeg' : 'image/jpeg', 'jpg' : 'image/jpeg', - 'rtf' : 'text/rtf', 'pdf' : 'application/pdf', - 'mpeg' : 'video/mpeg', 'mpg' : 'video/mpeg', - 'gif' : 'image/gif', 'bmp' : 'image/x-ms-bmp', - 'tiff' : 'image/tiff', 'aif' : 'audio/x-aiff', - 'text' : 'text/plain', 'w8bn' : 'application/msword', - 'wav' : 'audio/x-wav', 'mov' : 'video/quicktime', + 'jpeg' : 'image/jpeg', 'jpg' : 'image/jpeg', + 'rtf' : 'text/rtf', 'pdf' : 'application/pdf', + 'mpeg' : 'video/mpeg', 'mpg' : 'video/mpeg', + 'gif' : 'image/gif', 'bmp' : 'image/x-ms-bmp', + 'tiff' : 'image/tiff', 'aif' : 'audio/x-aiff', + 'text' : 'text/plain', 'w8bn' : 'application/msword', + 'wav' : 'audio/x-wav', 'mov' : 'video/quicktime', } FTW_BAD_PLACE = [ - EventType.OCCUPATION, - EventType.RELIGION, + EventType.OCCUPATION, + EventType.RELIGION, EventType.DEGREE ] MEDIA_MAP = { - 'audio' : SourceMediaType.AUDIO, - 'book' : SourceMediaType.BOOK, - 'card' : SourceMediaType.CARD, - 'electronic' : SourceMediaType.ELECTRONIC, - 'fiche' : SourceMediaType.FICHE, - 'microfiche' : SourceMediaType.FICHE, - 'microfilm' : SourceMediaType.FICHE, - 'film' : SourceMediaType.FILM, - 'magazine' : SourceMediaType.MAGAZINE, - 'manuscript' : SourceMediaType.MANUSCRIPT, - 'map' : SourceMediaType.MAP, - 'newspaper' : SourceMediaType.NEWSPAPER, - 'photo' : SourceMediaType.PHOTO, - 'tombstone' : SourceMediaType.TOMBSTONE, - 'grave' : SourceMediaType.TOMBSTONE, - 'video' : SourceMediaType.VIDEO, + 'audio' : SourceMediaType.AUDIO, + 'book' : SourceMediaType.BOOK, + 'card' : SourceMediaType.CARD, + 'electronic' : SourceMediaType.ELECTRONIC, + 'fiche' : SourceMediaType.FICHE, + 'microfiche' : SourceMediaType.FICHE, + 'microfilm' : SourceMediaType.FICHE, + 'film' : SourceMediaType.FILM, + 'magazine' : SourceMediaType.MAGAZINE, + 'manuscript' : SourceMediaType.MANUSCRIPT, + 'map' : SourceMediaType.MAP, + 'newspaper' : SourceMediaType.NEWSPAPER, + 'photo' : SourceMediaType.PHOTO, + 'tombstone' : SourceMediaType.TOMBSTONE, + 'grave' : SourceMediaType.TOMBSTONE, + 'video' : SourceMediaType.VIDEO, } #------------------------------------------------------------------------- @@ -505,15 +505,15 @@ PERSONALCONSTANTEVENTS = { EventType.CHRISTEN : "CHR" , EventType.CONFIRMATION : "CONF", EventType.CREMATION : "CREM", - EventType.DEGREE : "_DEG", + EventType.DEGREE : "_DEG", EventType.DIV_FILING : "DIVF", EventType.EDUCATION : "EDUC", EventType.ELECTED : "", EventType.EMIGRATION : "EMIG", EventType.FIRST_COMMUN : "FCOM", EventType.GRADUATION : "GRAD", - EventType.MED_INFO : "_MDCL", - EventType.MILITARY_SERV : "_MILT", + EventType.MED_INFO : "_MDCL", + EventType.MILITARY_SERV : "_MILT", EventType.NATURALIZATION : "NATU", EventType.NOB_TITLE : "TITL", EventType.NUM_MARRIAGES : "NMR", @@ -522,7 +522,7 @@ PERSONALCONSTANTEVENTS = { EventType.PROBATE : "PROB", EventType.PROPERTY : "PROP", EventType.RELIGION : "RELI", - EventType.RESIDENCE : "RESI", + EventType.RESIDENCE : "RESI", EventType.RETIREMENT : "RETI", EventType.WILL : "WILL", } @@ -587,56 +587,56 @@ GED_TO_GRAMPS_ATTR = {} for __val, __key in PERSONALCONSTANTATTRIBUTES.items(): if __key != "": GED_TO_GRAMPS_ATTR[__key] = __val - + #------------------------------------------------------------------------- # # GEDCOM Date Constants # #------------------------------------------------------------------------- HMONTH = [ - "", "ELUL", "TSH", "CSH", "KSL", "TVT", "SHV", "ADR", + "", "ELUL", "TSH", "CSH", "KSL", "TVT", "SHV", "ADR", "ADS", "NSN", "IYR", "SVN", "TMZ", "AAV", "ELL" ] FMONTH = [ - "", "VEND", "BRUM", "FRIM", "NIVO", "PLUV", "VENT", + "", "VEND", "BRUM", "FRIM", "NIVO", "PLUV", "VENT", "GERM", "FLOR", "PRAI", "MESS", "THER", "FRUC", "COMP"] MONTH = [ - "", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", + "", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ] CALENDAR_MAP = { - Date.CAL_HEBREW : (HMONTH, '@#DHEBREW@'), - Date.CAL_FRENCH : (FMONTH, '@#DFRENCH R@'), - Date.CAL_JULIAN : (MONTH, '@#DJULIAN@'), - Date.CAL_SWEDISH : (MONTH, '@#DUNKNOWN@'), + Date.CAL_HEBREW : (HMONTH, '@#DHEBREW@'), + Date.CAL_FRENCH : (FMONTH, '@#DFRENCH R@'), + Date.CAL_JULIAN : (MONTH, '@#DJULIAN@'), + Date.CAL_SWEDISH : (MONTH, '@#DUNKNOWN@'), } CALENDAR_MAP_PARSESTRING = { - Date.CAL_HEBREW : ' (h)', - Date.CAL_FRENCH : ' (f)', - Date.CAL_JULIAN : ' (j)', - Date.CAL_SWEDISH : ' (s)', + Date.CAL_HEBREW : ' (h)', + Date.CAL_FRENCH : ' (f)', + Date.CAL_JULIAN : ' (j)', + Date.CAL_SWEDISH : ' (s)', } #how wrong calendar use is shown CALENDAR_MAP_WRONGSTRING = { - Date.CAL_HEBREW : ' ', - Date.CAL_FRENCH : ' ', - Date.CAL_JULIAN : ' ', - Date.CAL_SWEDISH : ' ', + Date.CAL_HEBREW : ' ', + Date.CAL_FRENCH : ' ', + Date.CAL_JULIAN : ' ', + Date.CAL_SWEDISH : ' ', } DATE_MODIFIER = { - Date.MOD_ABOUT : "ABT", - Date.MOD_BEFORE : "BEF", - Date.MOD_AFTER : "AFT", + Date.MOD_ABOUT : "ABT", + Date.MOD_BEFORE : "BEF", + Date.MOD_AFTER : "AFT", #Date.MOD_INTERPRETED : "INT", } DATE_QUALITY = { - Date.QUAL_CALCULATED : "CAL", - Date.QUAL_ESTIMATED : "EST", + Date.QUAL_CALCULATED : "CAL", + Date.QUAL_ESTIMATED : "EST", } #------------------------------------------------------------------------- @@ -671,7 +671,7 @@ class GedcomDateParser(DateParser): 'may' : 5, 'jun' : 6, 'jul' : 7, 'aug' : 8, 'sep' : 9, 'oct' : 10, 'nov' : 11, 'dec' : 12, } - + #------------------------------------------------------------------------- # # Lexer - serves as the lexical analysis engine @@ -753,7 +753,7 @@ class Lexer(object): line_value = line[2].lstrip() ## Ignore meaningless @IDENT@ on CONT or CONC line ## as noted at http://www.tamurajones.net/IdentCONT.xhtml - if (line_value.lstrip().startswith("CONT ") or + if (line_value.lstrip().startswith("CONT ") or line_value.lstrip().startswith("CONC ")): line = line_value.lstrip().partition(' ') tag = line[0] @@ -801,17 +801,17 @@ class Lexer(object): #----------------------------------------------------------------------- class GedLine(object): """ - GedLine is a class the represents a GEDCOM line. The form of a GEDCOM line + GedLine is a class the represents a GEDCOM line. The form of a GEDCOM line is: - + This gets parsed into Line Number, Level, Token Value, Token Text, and Data - Data is dependent on the context the Token Value. For most of tokens, - this is just a text string. However, for certain tokens where we know + Data is dependent on the context the Token Value. For most of tokens, + this is just a text string. However, for certain tokens where we know the context, we can provide some value. The current parsed tokens are: TOKEN_DATE - Date @@ -819,7 +819,7 @@ class GedLine(object): TOEKN_UKNOWN - Check to see if this is a known event """ __DATE_CNV = GedcomDateParser() - + @staticmethod def __extract_date(text): """ @@ -859,10 +859,10 @@ class GedLine(object): if cal1 != cal2: #not supported by GRAMPS, import as text, we construct a string # that the parser will not parse as a correct date - return GedLine.__DATE_CNV.parse('%sbetween %s%s and %s%s' % + return GedLine.__DATE_CNV.parse('%sbetween %s%s and %s%s' % (mod, data1, CALENDAR_MAP_WRONGSTRING.get(cal1, ''), CALENDAR_MAP_WRONGSTRING.get(cal2, ''), data2)) - + #add hebrew, ... calendar so that months are recognized data1 += CALENDAR_MAP_PARSESTRING.get(cal1, '') data2 += CALENDAR_MAP_PARSESTRING.get(cal2, '') @@ -891,7 +891,7 @@ class GedLine(object): if cal1 != cal2: #not supported by GRAMPS, import as text, we construct a string # that the parser will not parse as a correct date - return GedLine.__DATE_CNV.parse('%sfrom %s%s to %s%s' % + return GedLine.__DATE_CNV.parse('%sfrom %s%s to %s%s' % (mod, data1, CALENDAR_MAP_WRONGSTRING.get(cal1, ''), CALENDAR_MAP_WRONGSTRING.get(cal2, ''), data2)) #add hebrew, ... calendar so that months are recognized @@ -903,7 +903,7 @@ class GedLine(object): start.get_start_date() + stop.get_start_date()) dateobj.set_quality(qual) return dateobj - + match = CAL.match(text) if match: (abt, call, data) = match.groups() @@ -921,12 +921,12 @@ class GedLine(object): def __init__(self, data): """ - If the level is 0, then this is a top level instance. In this case, + If the level is 0, then this is a top level instance. In this case, we may find items in the form of: @ID@ - If this is not the top level, we check the MAP_DATA array to see if + If this is not the top level, we check the MAP_DATA array to see if there is a conversion function for the data. """ self.line = data[4] @@ -952,7 +952,7 @@ class GedLine(object): Converts the data field to a gen.lib token indicating the gender """ try: - self.data = SEX_MAP.get(self.data.strip()[0], + self.data = SEX_MAP.get(self.data.strip()[0], Person.UNKNOWN) except: self.data = Person.UNKNOWN @@ -965,7 +965,7 @@ class GedLine(object): def calc_unknown(self): """ - Checks to see if the token maps a known GEDCOM event. If so, we + Checks to see if the token maps a known GEDCOM event. If so, we change the type from UNKNOWN to TOKEN_GEVENT (gedcom event), and the data is assigned to the associated GRAMPS EventType """ @@ -1006,7 +1006,7 @@ class GedLine(object): self.token = TOKEN_ATTR def __repr__(self): - return "%d: %d (%d:%s) %s" % (self.line, self.level, self.token, + return "%d: %d (%d:%s) %s" % (self.line, self.level, self.token, self.token_text, self.data) _MAP_DATA = { @@ -1041,7 +1041,7 @@ class GedcomDescription(object): self.tag2gramps_map = {} self.prefix = PREFIX_YES self.endl = "\n" - + def set_dest(self, val): self.dest = val @@ -1065,7 +1065,7 @@ class GedcomDescription(object): def get_prefix(self): return self.prefix - + def set_conc(self, val): self.conc = val @@ -1154,7 +1154,7 @@ class GedcomInfoDB(object): def get_name_list(self): return ["GEDCOM 5.5 standard"] + sorted(self.map) - + #------------------------------------------------------------------------- # # GedInfoParser @@ -1169,7 +1169,7 @@ class GedInfoParser(object): p = ParserCreate() p.StartElementHandler = self.startElement p.ParseFile(ged_file) - + def startElement(self, tag, attrs): if tag == "target": name = attrs['name'] @@ -1282,7 +1282,7 @@ class AnsiReader(BaseReader): def __init__(self, ifile, __add_msg): BaseReader.__init__(self, ifile, 'latin1', __add_msg) - + def readline(self): line = self.ifile.readline() line = line.decode(self.enc, errors='replace') @@ -1294,7 +1294,7 @@ class CP1252Reader(BaseReader): def __init__(self, ifile, __add_msg): BaseReader.__init__(self, ifile, 'cp1252', __add_msg) - + def readline(self): line = self.ifile.readline() line = line.decode(self.enc, errors='replace') @@ -1303,11 +1303,11 @@ class CP1252Reader(BaseReader): class AnselReader(BaseReader): """ ANSEL to Unicode Conversion - + ANSEL references: http://lcweb2.loc.gov/diglib/codetables/45.html http://www.gymel.com/charsets/ANSEL.html - + list of ANSEL codes that replicate ASCII note that DEL (127=0x7F) is a control char Note: spec allows control-chars that Gramps probably doesn't use @@ -1321,47 +1321,47 @@ class AnselReader(BaseReader): __printable_ascii = list(map(chr, list(range(32, 127)))) # note: up thru 126 # LF CR Esc GS RS US __use_ASCII = list(map(chr, [10, 13, 27, 29 , 30, 31])) + __printable_ascii - + # mappings of single byte ANSEL codes to unicode __onebyte = { - b'\xA1' : '\u0141', b'\xA2' : '\u00d8', b'\xA3' : '\u0110', - b'\xA4' : '\u00de', b'\xA5' : '\u00c6', b'\xA6' : '\u0152', - b'\xA7' : '\u02b9', b'\xA8' : '\u00b7', b'\xA9' : '\u266d', - b'\xAA' : '\u00ae', b'\xAB' : '\u00b1', b'\xAC' : '\u01a0', - b'\xAD' : '\u01af', b'\xAE' : '\u02bc', b'\xB0' : '\u02bb', - b'\xB1' : '\u0142', b'\xB2' : '\u00f8', b'\xB3' : '\u0111', - b'\xB4' : '\u00fe', b'\xB5' : '\u00e6', b'\xB6' : '\u0153', - b'\xB7' : '\u02ba', b'\xB8' : '\u0131', b'\xB9' : '\u00a3', - b'\xBA' : '\u00f0', b'\xBC' : '\u01a1', b'\xBD' : '\u01b0', + b'\xA1' : '\u0141', b'\xA2' : '\u00d8', b'\xA3' : '\u0110', + b'\xA4' : '\u00de', b'\xA5' : '\u00c6', b'\xA6' : '\u0152', + b'\xA7' : '\u02b9', b'\xA8' : '\u00b7', b'\xA9' : '\u266d', + b'\xAA' : '\u00ae', b'\xAB' : '\u00b1', b'\xAC' : '\u01a0', + b'\xAD' : '\u01af', b'\xAE' : '\u02bc', b'\xB0' : '\u02bb', + b'\xB1' : '\u0142', b'\xB2' : '\u00f8', b'\xB3' : '\u0111', + b'\xB4' : '\u00fe', b'\xB5' : '\u00e6', b'\xB6' : '\u0153', + b'\xB7' : '\u02ba', b'\xB8' : '\u0131', b'\xB9' : '\u00a3', + b'\xBA' : '\u00f0', b'\xBC' : '\u01a1', b'\xBD' : '\u01b0', b'\xBE' : '\u25a1', b'\xBF' : '\u25a0', - b'\xC0' : '\u00b0', b'\xC1' : '\u2113', b'\xC2' : '\u2117', - b'\xC3' : '\u00a9', b'\xC4' : '\u266f', b'\xC5' : '\u00bf', - b'\xC6' : '\u00a1', b'\xC7' : '\u00df', b'\xC8' : '\u20ac', + b'\xC0' : '\u00b0', b'\xC1' : '\u2113', b'\xC2' : '\u2117', + b'\xC3' : '\u00a9', b'\xC4' : '\u266f', b'\xC5' : '\u00bf', + b'\xC6' : '\u00a1', b'\xC7' : '\u00df', b'\xC8' : '\u20ac', b'\xCD' : '\u0065', b'\xCE' : '\u006f', b'\xCF' : '\u00df', } - + # combining forms (in ANSEL, they precede the modified ASCII character # whereas the unicode combining term follows the character modified - # Note: unicode allows multiple modifiers, but ANSEL may not (TDB?), + # Note: unicode allows multiple modifiers, but ANSEL may not (TDB?), # so we ignore multiple combining forms in this module # 8d & 8e are zero-width joiner (ZWJ), and zero-width non-joiner ZWNJ # (strange things) probably not commonly found in our needs, unless one # starts writing persian (or???) poetry in ANSEL __acombiners = { - b'\x8D' : '\u200d', b'\x8E' : '\u200c', b'\xE0' : '\u0309', - b'\xE1' : '\u0300', b'\xE2' : '\u0301', b'\xE3' : '\u0302', - b'\xE4' : '\u0303', b'\xE5' : '\u0304', b'\xE6' : '\u0306', - b'\xE7' : '\u0307', b'\xE8' : '\u0308', b'\xE9' : '\u030c', - b'\xEA' : '\u030a', b'\xEB' : '\ufe20', b'\xEC' : '\ufe21', - b'\xED' : '\u0315', b'\xEE' : '\u030b', b'\xEF' : '\u0310', - b'\xF0' : '\u0327', b'\xF1' : '\u0328', b'\xF2' : '\u0323', - b'\xF3' : '\u0324', b'\xF4' : '\u0325', b'\xF5' : '\u0333', - b'\xF6' : '\u0332', b'\xF7' : '\u0326', b'\xF8' : '\u031c', - b'\xF9' : '\u032e', b'\xFA' : '\ufe22', b'\xFB' : '\ufe23', + b'\x8D' : '\u200d', b'\x8E' : '\u200c', b'\xE0' : '\u0309', + b'\xE1' : '\u0300', b'\xE2' : '\u0301', b'\xE3' : '\u0302', + b'\xE4' : '\u0303', b'\xE5' : '\u0304', b'\xE6' : '\u0306', + b'\xE7' : '\u0307', b'\xE8' : '\u0308', b'\xE9' : '\u030c', + b'\xEA' : '\u030a', b'\xEB' : '\ufe20', b'\xEC' : '\ufe21', + b'\xED' : '\u0315', b'\xEE' : '\u030b', b'\xEF' : '\u0310', + b'\xF0' : '\u0327', b'\xF1' : '\u0328', b'\xF2' : '\u0323', + b'\xF3' : '\u0324', b'\xF4' : '\u0325', b'\xF5' : '\u0333', + b'\xF6' : '\u0332', b'\xF7' : '\u0326', b'\xF8' : '\u031c', + b'\xF9' : '\u032e', b'\xFA' : '\ufe22', b'\xFB' : '\ufe23', b'\xFC' : '\u0338', - b'\xFE' : '\u0313', + b'\xFE' : '\u0313', } - + # mappings of two byte (precomposed forms) ANSEL codes to unicode __twobyte = { b'\xE0\x41' : '\u1ea2', b'\xE0\x45' : '\u1eba', @@ -1423,7 +1423,7 @@ class AnselReader(BaseReader): b'\xE5\x67' : '\u1e21', b'\xE5\x69' : '\u012b', b'\xE5\x6F' : '\u014d', b'\xE5\x75' : '\u016b', b'\xE5\xA5' : '\u01e2', b'\xE5\xB5' : '\u01e3', - b'\xE6\x41' : '\u0102', b'\xE6\x45' : '\u0114', + b'\xE6\x41' : '\u0102', b'\xE6\x45' : '\u0114', b'\xE6\x47' : '\u011e', b'\xE6\x49' : '\u012c', b'\xE6\x4F' : '\u014e', b'\xE6\x55' : '\u016c', b'\xE6\x61' : '\u0103', b'\xE6\x65' : '\u0115', @@ -1480,7 +1480,7 @@ class AnselReader(BaseReader): b'\xF0\x43' : '\u00c7', b'\xF0\x44' : '\u1e10', b'\xF0\x47' : '\u0122', b'\xF0\x48' : '\u1e28', b'\xF0\x4B' : '\u0136', b'\xF0\x4C' : '\u013b', - b'\xF0\x4E' : '\u0145', b'\xF0\x52' : '\u0156', + b'\xF0\x4E' : '\u0145', b'\xF0\x52' : '\u0156', b'\xF0\x53' : '\u015e', b'\xF0\x54' : '\u0162', b'\xF0\x63' : '\u00e7', b'\xF0\x64' : '\u1e11', b'\xF0\x67' : '\u0123', b'\xF0\x68' : '\u1e29', @@ -1513,12 +1513,12 @@ class AnselReader(BaseReader): b'\xF2\x79' : '\u1ef5', b'\xF2\x7A' : '\u1e93', b'\xF3\x55' : '\u1e72', b'\xF3\x75' : '\u1e73', b'\xF4\x41' : '\u1e00', b'\xF4\x61' : '\u1e01', - b'\xF9\x48' : '\u1e2a', b'\xF9\x68' : '\u1e2b', + b'\xF9\x48' : '\u1e2a', b'\xF9\x68' : '\u1e2b', } def __ansel_to_unicode(self, s): """ Convert an ANSEL encoded string to unicode """ - + buff = StringIO() error = "" while s: @@ -1550,7 +1550,7 @@ class AnselReader(BaseReader): else: # just drop the unexpected combiner error += " (%#X)" % s[0] - continue + continue else: error += " (%#X)" % s[0] head = '\ufffd' # "Replacement Char" @@ -1569,7 +1569,7 @@ class AnselReader(BaseReader): def readline(self): return self.__ansel_to_unicode(self.ifile.readline()) - + #------------------------------------------------------------------------- # # CurrentState @@ -1605,7 +1605,7 @@ class CurrentState(object): self.location = None self.place_fields = None # method for parsing places self.ref = None # PersonRef - self.handle = None # + self.handle = None # self.form = "" # Multimedia format self.frel = None # Child relation to father self.mrel = None @@ -1769,7 +1769,7 @@ class IdMapper(object): self.find_next = find_next self.id2user_format = id2user_format self.swap = {} - + def __getitem__(self, gid): if gid == "": # We need to find the next gramps ID provided it is not already @@ -1804,13 +1804,13 @@ class IdMapper(object): # from the original format self.swap[gid] = new_val return new_val - + def clean(self, gid): temp = gid.strip() if len(temp) > 1 and temp[0] == '@' and temp[-1] == '@': temp = temp[1:-1] return temp - + def map(self): return self.swap @@ -1831,29 +1831,29 @@ class GedcomParser(UpdateCallback): SyntaxError = "Syntax Error" BadFile = "Not a GEDCOM file" - + @staticmethod def __find_from_handle(gramps_id, table): """ - Find a handle corresponding to the specified GRAMPS ID. - - The passed table contains the mapping. If the value is found, we return + Find a handle corresponding to the specified GRAMPS ID. + + The passed table contains the mapping. If the value is found, we return it, otherwise we create a new handle, store it, and return it. - + """ intid = table.get(gramps_id) if not intid: intid = create_id() table[gramps_id] = intid return intid - + @staticmethod def __parse_name_personal(text): """ Parses a GEDCOM NAME value into an Name structure """ name = Name() - + match = SURNAME_RE.match(text) if match: #/surname/ extra, we assume extra is given name @@ -1878,7 +1878,7 @@ class GedcomParser(UpdateCallback): name.set_first_name(text.strip()) return name - def __init__(self, dbase, ifile, filename, user, stage_one, + def __init__(self, dbase, ifile, filename, user, stage_one, default_source, default_tag_format=None): UpdateCallback.__init__(self, user.callback) self.user = user @@ -1926,28 +1926,28 @@ class GedcomParser(UpdateCallback): self.want_parse_warnings = True self.pid_map = IdMapper( - self.dbase.id_trans, - self.dbase.find_next_person_gramps_id, + self.dbase.id_trans, + self.dbase.find_next_person_gramps_id, self.dbase.id2user_format) self.fid_map = IdMapper( - self.dbase.fid_trans, - self.dbase.find_next_family_gramps_id, + self.dbase.fid_trans, + self.dbase.find_next_family_gramps_id, self.dbase.fid2user_format) self.sid_map = IdMapper( - self.dbase.sid_trans, - self.dbase.find_next_source_gramps_id, + self.dbase.sid_trans, + self.dbase.find_next_source_gramps_id, self.dbase.sid2user_format) self.oid_map = IdMapper( - self.dbase.oid_trans, - self.dbase.find_next_object_gramps_id, + self.dbase.oid_trans, + self.dbase.find_next_object_gramps_id, self.dbase.oid2user_format) self.rid_map = IdMapper( - self.dbase.rid_trans, - self.dbase.find_next_repository_gramps_id, + self.dbase.rid_trans, + self.dbase.find_next_repository_gramps_id, self.dbase.rid2user_format) self.nid_map = IdMapper( - self.dbase.nid_trans, - self.dbase.find_next_note_gramps_id, + self.dbase.nid_trans, + self.dbase.find_next_note_gramps_id, self.dbase.nid2user_format) self.gid2id = {} @@ -1975,11 +1975,11 @@ class GedcomParser(UpdateCallback): # (N.B. GEDCOM allows multiple SUBMitter records) self.subm_parse_tbl = { # +1 NAME - TOKEN_NAME : self.__subm_name, + TOKEN_NAME : self.__subm_name, # +1 <> - TOKEN_ADDR : self.__subm_addr, + TOKEN_ADDR : self.__subm_addr, TOKEN_PHON : self.__subm_phon, - TOKEN_EMAIL : self.__subm_email, + TOKEN_EMAIL : self.__subm_email, # +1 <> # +1 LANG # +1 RFN @@ -2018,96 +2018,96 @@ class GedcomParser(UpdateCallback): self.indi_parse_tbl = { # +1 RESN {0:1} - TOKEN_RESN : self.__person_resn, + TOKEN_RESN : self.__person_resn, # +1 <> {0:M} - TOKEN_NAME : self.__person_name, + TOKEN_NAME : self.__person_name, # +1 SEX {0:1} - TOKEN_SEX : self.__person_sex, + TOKEN_SEX : self.__person_sex, # +1 <> {0:M} - TOKEN_EVEN : self.__person_even, - TOKEN_GEVENT: self.__person_std_event, - TOKEN_BIRT : self.__person_birt, - TOKEN_RELI : self.__person_reli, - TOKEN_ADOP : self.__person_adop, - TOKEN_DEAT : self.__person_deat, + TOKEN_EVEN : self.__person_even, + TOKEN_GEVENT: self.__person_std_event, + TOKEN_BIRT : self.__person_birt, + TOKEN_RELI : self.__person_reli, + TOKEN_ADOP : self.__person_adop, + TOKEN_DEAT : self.__person_deat, # +1 <> {0:M} # +1 AFN {0:1} - TOKEN_ATTR : self.__person_std_attr, - TOKEN_FACT : self.__person_fact, + TOKEN_ATTR : self.__person_std_attr, + TOKEN_FACT : self.__person_fact, #+1 <> {0:M} - TOKEN_BAPL : self.__person_bapl, - TOKEN_CONL : self.__person_conl, - TOKEN_ENDL : self.__person_endl, - TOKEN_SLGC : self.__person_slgc, + TOKEN_BAPL : self.__person_bapl, + TOKEN_CONL : self.__person_conl, + TOKEN_ENDL : self.__person_endl, + TOKEN_SLGC : self.__person_slgc, #+1 <> {0:M} - TOKEN_FAMC : self.__person_famc, + TOKEN_FAMC : self.__person_famc, # +1 <> {0:M} - TOKEN_FAMS : self.__person_fams, + TOKEN_FAMS : self.__person_fams, # +1 SUBM @@ {0:M} - TOKEN_SUBM : self.__skip_record, + TOKEN_SUBM : self.__skip_record, # +1 <> {0:M} - TOKEN_ASSO : self.__person_asso, + TOKEN_ASSO : self.__person_asso, # +1 ALIA @@ {0:M} - TOKEN_ALIA : self.__person_alt_name, + TOKEN_ALIA : self.__person_alt_name, # +1 ANCI @@ {0:M} - TOKEN_ANCI : self.__skip_record, + TOKEN_ANCI : self.__skip_record, # +1 DESI @@ {0:M} - TOKEN_DESI : self.__skip_record, + TOKEN_DESI : self.__skip_record, # +1 <> {0:M} - TOKEN_SOUR : self.__person_sour, + TOKEN_SOUR : self.__person_sour, # +1 <> {0:M} - TOKEN_OBJE : self.__person_object, - # +1 <> {0:M} - TOKEN_NOTE : self.__person_note, - TOKEN_RNOTE : self.__person_note, - TOKEN__COMM : self.__person_note, + TOKEN_OBJE : self.__person_object, + # +1 <> {0:M} + TOKEN_NOTE : self.__person_note, + TOKEN_RNOTE : self.__person_note, + TOKEN__COMM : self.__person_note, # +1 RFN {0:1} - TOKEN_RFN : self.__person_attr, + TOKEN_RFN : self.__person_attr, # +1 REFN {0:M} # +2 TYPE {0:1} - TOKEN_REFN : self.__person_attr, + TOKEN_REFN : self.__person_attr, # TYPE should be below REFN, but will work here anyway - TOKEN_TYPE : self.__person_attr, + TOKEN_TYPE : self.__person_attr, # +1 RIN {0:1} - TOKEN_RIN : self.__person_attr, + TOKEN_RIN : self.__person_attr, # +1 <> {0:1} - TOKEN_CHAN : self.__person_chan, + TOKEN_CHAN : self.__person_chan, - TOKEN_ADDR : self.__person_addr, + TOKEN_ADDR : self.__person_addr, TOKEN_PHON : self.__person_phon, TOKEN_EMAIL : self.__person_email, - TOKEN_URL : self.__person_url, - TOKEN__TODO : self.__skip_record, - TOKEN_TITL : self.__person_titl, + TOKEN_URL : self.__person_url, + TOKEN__TODO : self.__skip_record, + TOKEN_TITL : self.__person_titl, } self.func_list.append(self.indi_parse_tbl) self.name_parse_tbl = { # +1 NPFX {0:1} - TOKEN_NPFX : self.__name_npfx, + TOKEN_NPFX : self.__name_npfx, # +1 GIVN {0:1} - TOKEN_GIVN : self.__name_givn, + TOKEN_GIVN : self.__name_givn, # NICK {0:1} - TOKEN_NICK : self.__name_nick, + TOKEN_NICK : self.__name_nick, # +1 SPFX {0:1} - TOKEN_SURN : self.__name_surn, + TOKEN_SURN : self.__name_surn, # +1 NSFX {0:1} - TOKEN_NSFX : self.__name_nsfx, + TOKEN_NSFX : self.__name_nsfx, # +1 <> {0:M} - TOKEN_SOUR : self.__name_sour, + TOKEN_SOUR : self.__name_sour, # +1 <> {0:M} - TOKEN_NOTE : self.__name_note, - TOKEN_RNOTE : self.__name_note, + TOKEN_NOTE : self.__name_note, + TOKEN_RNOTE : self.__name_note, # Extensions - TOKEN_ALIA : self.__name_alia, - TOKEN__MARNM : self.__name_marnm, + TOKEN_ALIA : self.__name_alia, + TOKEN__MARNM : self.__name_marnm, TOKEN__MAR : self.__name_marnm, # Generated by geni.com TOKEN__MARN : self.__name_marnm, # Gen'd by BROSKEEP 6.1.31 WIN TOKEN__AKA : self.__name_aka, # PAF and AncestQuest TOKEN_TYPE : self.__name_type, # This is legal GEDCOM 5.5.1 - TOKEN_BIRT : self.__ignore, + TOKEN_BIRT : self.__ignore, TOKEN_DATE : self.__name_date, # This handles date as a subsidiary of "1 ALIA" which might be used # by Family Tree Maker and Reunion, and by cheating (handling a @@ -2120,7 +2120,7 @@ class GedcomParser(UpdateCallback): # # Parse table for <> below the level 0 REPO tag - # + # # n @@ REPO {1:1} # +1 NAME {0:1} # +1 <> {0:1} @@ -2131,60 +2131,60 @@ class GedcomParser(UpdateCallback): # +1 <> {0:1} self.repo_parse_tbl = { - TOKEN_NAME : self.__repo_name, - TOKEN_ADDR : self.__repo_addr, - TOKEN_RIN : self.__ignore, - TOKEN_NOTE : self.__repo_note, - TOKEN_RNOTE : self.__repo_note, - TOKEN_CHAN : self.__repo_chan, - TOKEN_PHON : self.__repo_phon, - TOKEN_EMAIL : self.__repo_email, - TOKEN_WWW : self.__repo_www, + TOKEN_NAME : self.__repo_name, + TOKEN_ADDR : self.__repo_addr, + TOKEN_RIN : self.__ignore, + TOKEN_NOTE : self.__repo_note, + TOKEN_RNOTE : self.__repo_note, + TOKEN_CHAN : self.__repo_chan, + TOKEN_PHON : self.__repo_phon, + TOKEN_EMAIL : self.__repo_email, + TOKEN_WWW : self.__repo_www, } self.func_list.append(self.repo_parse_tbl) self.event_parse_tbl = { # n TYPE {0:1} - TOKEN_TYPE : self.__event_type, + TOKEN_TYPE : self.__event_type, # n DATE {0:1} p.*/* - TOKEN_DATE : self.__event_date, + TOKEN_DATE : self.__event_date, # n <> {0:1} p.* - TOKEN_PLAC : self.__event_place, + TOKEN_PLAC : self.__event_place, # n <> {0:1} p.* - TOKEN_ADDR : self.__event_addr, + TOKEN_ADDR : self.__event_addr, # n AGE {0:1} p.* - TOKEN_AGE : self.__event_age, + TOKEN_AGE : self.__event_age, # n AGNC {0:1} p.* - TOKEN_AGNC : self.__event_agnc, + TOKEN_AGNC : self.__event_agnc, # n CAUS {0:1} p.* - TOKEN_CAUS : self.__event_cause, + TOKEN_CAUS : self.__event_cause, # n <> {0:M} p.* - TOKEN_SOUR : self.__event_source, + TOKEN_SOUR : self.__event_source, # n <> {0:M} p.*, * - TOKEN_OBJE : self.__event_object, + TOKEN_OBJE : self.__event_object, # n <> {0:M} p. - TOKEN_NOTE : self.__event_inline_note, - TOKEN_RNOTE : self.__event_note, + TOKEN_NOTE : self.__event_inline_note, + TOKEN_RNOTE : self.__event_note, # Other - TOKEN__PRIV : self.__event_privacy, - TOKEN_OFFI : self.__event_note, - TOKEN_PHON : self.__event_phon, - TOKEN__GODP : self.__event_witness, - TOKEN__WITN : self.__event_witness, - TOKEN__WTN : self.__event_witness, + TOKEN__PRIV : self.__event_privacy, + TOKEN_OFFI : self.__event_note, + TOKEN_PHON : self.__event_phon, + TOKEN__GODP : self.__event_witness, + TOKEN__WITN : self.__event_witness, + TOKEN__WTN : self.__event_witness, TOKEN_RELI : self.__ignore, - # Not legal, but inserted by PhpGedView - TOKEN_TIME : self.__event_time, - TOKEN_ASSO : self.__ignore, - TOKEN_IGNORE : self.__ignore, - TOKEN_STAT : self.__ignore, - TOKEN_TEMP : self.__ignore, - TOKEN_HUSB : self.__event_husb, - TOKEN_WIFE : self.__event_wife, - TOKEN_FAMC : self.__person_birth_famc, + # Not legal, but inserted by PhpGedView + TOKEN_TIME : self.__event_time, + TOKEN_ASSO : self.__ignore, + TOKEN_IGNORE : self.__ignore, + TOKEN_STAT : self.__ignore, + TOKEN_TEMP : self.__ignore, + TOKEN_HUSB : self.__event_husb, + TOKEN_WIFE : self.__event_wife, + TOKEN_FAMC : self.__person_birth_famc, # Not legal, but inserted by Ultimate Family Tree - TOKEN_CHAN : self.__ignore, - TOKEN_QUAY : self.__ignore, + TOKEN_CHAN : self.__ignore, + TOKEN_QUAY : self.__ignore, # Not legal, but inserted by FamilyTreeBuilder TOKEN_RIN : self.__event_rin, TOKEN_ATTR : self.__event_attr, # FTB for _UID @@ -2194,145 +2194,145 @@ class GedcomParser(UpdateCallback): self.func_list.append(self.event_parse_tbl) self.adopt_parse_tbl = { - TOKEN_TYPE : self.__event_type, - TOKEN__PRIV : self.__event_privacy, - TOKEN_DATE : self.__event_date, - TOKEN_SOUR : self.__event_source, - TOKEN_PLAC : self.__event_place, - TOKEN_ADDR : self.__event_addr, + TOKEN_TYPE : self.__event_type, + TOKEN__PRIV : self.__event_privacy, + TOKEN_DATE : self.__event_date, + TOKEN_SOUR : self.__event_source, + TOKEN_PLAC : self.__event_place, + TOKEN_ADDR : self.__event_addr, TOKEN_PHON : self.__event_phon, - TOKEN_CAUS : self.__event_cause, - TOKEN_AGNC : self.__event_agnc, - TOKEN_AGE : self.__event_age, - TOKEN_NOTE : self.__event_note, - TOKEN_RNOTE : self.__event_note, - TOKEN_OFFI : self.__event_note, - TOKEN__GODP : self.__event_witness, - TOKEN__WITN : self.__event_witness, - TOKEN__WTN : self.__event_witness, - TOKEN_RELI : self.__ignore, - TOKEN_TIME : self.__ignore, - TOKEN_ASSO : self.__ignore, - TOKEN_IGNORE : self.__ignore, - TOKEN_STAT : self.__ignore, - TOKEN_TEMP : self.__ignore, - TOKEN_OBJE : self.__event_object, - TOKEN_FAMC : self.__person_adopt_famc, + TOKEN_CAUS : self.__event_cause, + TOKEN_AGNC : self.__event_agnc, + TOKEN_AGE : self.__event_age, + TOKEN_NOTE : self.__event_note, + TOKEN_RNOTE : self.__event_note, + TOKEN_OFFI : self.__event_note, + TOKEN__GODP : self.__event_witness, + TOKEN__WITN : self.__event_witness, + TOKEN__WTN : self.__event_witness, + TOKEN_RELI : self.__ignore, + TOKEN_TIME : self.__ignore, + TOKEN_ASSO : self.__ignore, + TOKEN_IGNORE : self.__ignore, + TOKEN_STAT : self.__ignore, + TOKEN_TEMP : self.__ignore, + TOKEN_OBJE : self.__event_object, + TOKEN_FAMC : self.__person_adopt_famc, # Not legal, but inserted by Ultimate Family Tree - TOKEN_CHAN : self.__ignore, - TOKEN_QUAY : self.__ignore, + TOKEN_CHAN : self.__ignore, + TOKEN_QUAY : self.__ignore, } self.func_list.append(self.adopt_parse_tbl) self.famc_parse_tbl = { # n FAMC @@ {1:1} # +1 PEDI {0:M} p.* - TOKEN_PEDI : self.__person_famc_pedi, + TOKEN_PEDI : self.__person_famc_pedi, # +1 <> {0:M} p.* - TOKEN_NOTE : self.__person_famc_note, - TOKEN_RNOTE : self.__person_famc_note, + TOKEN_NOTE : self.__person_famc_note, + TOKEN_RNOTE : self.__person_famc_note, # Extras - TOKEN__PRIMARY: self.__person_famc_primary, - TOKEN_SOUR : self.__person_famc_sour, + TOKEN__PRIMARY: self.__person_famc_primary, + TOKEN_SOUR : self.__person_famc_sour, # GEDit - TOKEN_STAT : self.__ignore, + TOKEN_STAT : self.__ignore, } self.func_list.append(self.famc_parse_tbl) self.person_fact_parse_tbl = { - TOKEN_TYPE : self.__person_fact_type, - TOKEN_SOUR : self.__person_attr_source, - TOKEN_NOTE : self.__person_attr_note, - TOKEN_RNOTE : self.__person_attr_note, + TOKEN_TYPE : self.__person_fact_type, + TOKEN_SOUR : self.__person_attr_source, + TOKEN_NOTE : self.__person_attr_note, + TOKEN_RNOTE : self.__person_attr_note, } self.func_list.append(self.person_fact_parse_tbl) self.person_attr_parse_tbl = { - TOKEN_TYPE : self.__person_attr_type, - TOKEN_CAUS : self.__ignore, - TOKEN_DATE : self.__ignore, - TOKEN_TIME : self.__ignore, - TOKEN_ADDR : self.__ignore, - TOKEN_IGNORE : self.__ignore, - TOKEN_STAT : self.__ignore, - TOKEN_TEMP : self.__ignore, - TOKEN_OBJE : self.__ignore, - TOKEN_SOUR : self.__person_attr_source, - TOKEN_PLAC : self.__person_attr_place, - TOKEN_NOTE : self.__person_attr_note, - TOKEN_RNOTE : self.__person_attr_note, + TOKEN_TYPE : self.__person_attr_type, + TOKEN_CAUS : self.__ignore, + TOKEN_DATE : self.__ignore, + TOKEN_TIME : self.__ignore, + TOKEN_ADDR : self.__ignore, + TOKEN_IGNORE : self.__ignore, + TOKEN_STAT : self.__ignore, + TOKEN_TEMP : self.__ignore, + TOKEN_OBJE : self.__ignore, + TOKEN_SOUR : self.__person_attr_source, + TOKEN_PLAC : self.__person_attr_place, + TOKEN_NOTE : self.__person_attr_note, + TOKEN_RNOTE : self.__person_attr_note, } self.func_list.append(self.person_attr_parse_tbl) self.lds_parse_tbl = { - TOKEN_TEMP : self.__lds_temple, - TOKEN_DATE : self.__lds_date, - TOKEN_FAMC : self.__lds_famc, - TOKEN_FORM : self.__lds_form, - TOKEN_PLAC : self.__lds_plac, - TOKEN_SOUR : self.__lds_sour, - TOKEN_NOTE : self.__lds_note, - TOKEN_RNOTE : self.__lds_note, - TOKEN_STAT : self.__lds_stat, + TOKEN_TEMP : self.__lds_temple, + TOKEN_DATE : self.__lds_date, + TOKEN_FAMC : self.__lds_famc, + TOKEN_FORM : self.__lds_form, + TOKEN_PLAC : self.__lds_plac, + TOKEN_SOUR : self.__lds_sour, + TOKEN_NOTE : self.__lds_note, + TOKEN_RNOTE : self.__lds_note, + TOKEN_STAT : self.__lds_stat, } self.func_list.append(self.lds_parse_tbl) self.asso_parse_tbl = { - TOKEN_RELA : self.__person_asso_rela, - TOKEN_SOUR : self.__person_asso_sour, - TOKEN_NOTE : self.__person_asso_note, - TOKEN_RNOTE : self.__person_asso_note, + TOKEN_RELA : self.__person_asso_rela, + TOKEN_SOUR : self.__person_asso_sour, + TOKEN_NOTE : self.__person_asso_note, + TOKEN_RNOTE : self.__person_asso_note, } self.func_list.append(self.asso_parse_tbl) self.citation_parse_tbl = { - TOKEN_PAGE : self.__citation_page, - TOKEN_DATE : self.__citation_date, - TOKEN_DATA : self.__citation_data, - TOKEN_OBJE : self.__citation_obje, - TOKEN_REFN : self.__citation_refn, - TOKEN_EVEN : self.__citation_even, - TOKEN_IGNORE : self.__ignore, - TOKEN__LKD : self.__ignore, - TOKEN_QUAY : self.__citation_quay, - TOKEN_NOTE : self.__citation_note, - TOKEN_RNOTE : self.__citation_note, - TOKEN_TEXT : self.__citation_data_text, + TOKEN_PAGE : self.__citation_page, + TOKEN_DATE : self.__citation_date, + TOKEN_DATA : self.__citation_data, + TOKEN_OBJE : self.__citation_obje, + TOKEN_REFN : self.__citation_refn, + TOKEN_EVEN : self.__citation_even, + TOKEN_IGNORE : self.__ignore, + TOKEN__LKD : self.__ignore, + TOKEN_QUAY : self.__citation_quay, + TOKEN_NOTE : self.__citation_note, + TOKEN_RNOTE : self.__citation_note, + TOKEN_TEXT : self.__citation_data_text, } self.func_list.append(self.citation_parse_tbl) self.object_parse_tbl = { - TOKEN_FORM : self.__object_ref_form, - TOKEN_TITL : self.__object_ref_titl, - TOKEN_FILE : self.__object_ref_file, - TOKEN_NOTE : self.__object_ref_note, - TOKEN_RNOTE : self.__object_ref_note, - TOKEN_IGNORE : self.__ignore, + TOKEN_FORM : self.__object_ref_form, + TOKEN_TITL : self.__object_ref_titl, + TOKEN_FILE : self.__object_ref_file, + TOKEN_NOTE : self.__object_ref_note, + TOKEN_RNOTE : self.__object_ref_note, + TOKEN_IGNORE : self.__ignore, } self.func_list.append(self.object_parse_tbl) self.parse_loc_tbl = { - TOKEN_ADR1 : self.__location_adr1, - TOKEN_ADR2 : self.__location_adr2, - TOKEN_CITY : self.__location_city, - TOKEN_STAE : self.__location_stae, - TOKEN_POST : self.__location_post, - TOKEN_CTRY : self.__location_ctry, - # Not legal GEDCOM - not clear why these are included at this level - TOKEN_ADDR : self.__ignore, + TOKEN_ADR1 : self.__location_adr1, + TOKEN_ADR2 : self.__location_adr2, + TOKEN_CITY : self.__location_city, + TOKEN_STAE : self.__location_stae, + TOKEN_POST : self.__location_post, + TOKEN_CTRY : self.__location_ctry, + # Not legal GEDCOM - not clear why these are included at this level + TOKEN_ADDR : self.__ignore, TOKEN_DATE : self.__ignore, # there is nowhere to put a date - TOKEN_NOTE : self.__location_note, - TOKEN_RNOTE : self.__location_note, - TOKEN__LOC : self.__ignore, - TOKEN__NAME : self.__ignore, - TOKEN_PHON : self.__location_phone, - TOKEN_IGNORE : self.__ignore, + TOKEN_NOTE : self.__location_note, + TOKEN_RNOTE : self.__location_note, + TOKEN__LOC : self.__ignore, + TOKEN__NAME : self.__ignore, + TOKEN_PHON : self.__location_phone, + TOKEN_IGNORE : self.__ignore, } self.func_list.append(self.parse_loc_tbl) - + # # Parse table for <> below the level 0 FAM tag - # + # # n @@ FAM {1:1} # +1 <> {0:M} # +1 HUSB @@ {0:1} @@ -2350,52 +2350,52 @@ class GedcomParser(UpdateCallback): self.family_func = { # +1 <> {0:M} - TOKEN_GEVENT : self.__family_std_event, - TOKEN_EVEN : self.__fam_even, + TOKEN_GEVENT : self.__family_std_event, + TOKEN_EVEN : self.__fam_even, # +1 HUSB @@ {0:1} - TOKEN_HUSB : self.__family_husb, + TOKEN_HUSB : self.__family_husb, # +1 WIFE @@ {0:1} - TOKEN_WIFE : self.__family_wife, + TOKEN_WIFE : self.__family_wife, # +1 CHIL @@ {0:M} - TOKEN_CHIL : self.__family_chil, + TOKEN_CHIL : self.__family_chil, # +1 NCHI {0:1} # +1 SUBM @@ {0:M} # +1 <> {0:M} - TOKEN_SLGS : self.__family_slgs, + TOKEN_SLGS : self.__family_slgs, # +1 <> {0:M} - TOKEN_SOUR : self.__family_source, + TOKEN_SOUR : self.__family_source, # +1 <> {0:M} - TOKEN_OBJE : self.__family_object, + TOKEN_OBJE : self.__family_object, # +1 <> {0:M} - TOKEN__COMM : self.__family_comm, - TOKEN_NOTE : self.__family_note, - TOKEN_RNOTE : self.__family_note, + TOKEN__COMM : self.__family_comm, + TOKEN_NOTE : self.__family_note, + TOKEN_RNOTE : self.__family_note, # +1 REFN {0:M} - TOKEN_REFN : self.__family_cust_attr, + TOKEN_REFN : self.__family_cust_attr, # TYPE should be below REFN, but will work here anyway - TOKEN_TYPE : self.__family_cust_attr, + TOKEN_TYPE : self.__family_cust_attr, # +1 RIN {0:1} # +1 <> {0:1} - TOKEN_CHAN : self.__family_chan, - TOKEN_ENDL : self.__ignore, - TOKEN_ADDR : self.__ignore, - TOKEN_RIN : self.__family_cust_attr, - TOKEN_SUBM : self.__ignore, - TOKEN_ATTR : self.__family_attr, + TOKEN_CHAN : self.__family_chan, + TOKEN_ENDL : self.__ignore, + TOKEN_ADDR : self.__ignore, + TOKEN_RIN : self.__family_cust_attr, + TOKEN_SUBM : self.__ignore, + TOKEN_ATTR : self.__family_attr, } self.func_list.append(self.family_func) self.family_rel_tbl = { - TOKEN__FREL : self.__family_frel, - TOKEN__MREL : self.__family_mrel, - TOKEN_ADOP : self.__family_adopt, - TOKEN__STAT : self.__family_stat, + TOKEN__FREL : self.__family_frel, + TOKEN__MREL : self.__family_mrel, + TOKEN_ADOP : self.__family_adopt, + TOKEN__STAT : self.__family_stat, } self.func_list.append(self.family_rel_tbl) # # Parse table for <> below the level 0 SOUR tag - # + # # n @@ SOUR {1:1} # +1 DATA {0:1} # +2 EVEN {0:M} @@ -2421,35 +2421,35 @@ class GedcomParser(UpdateCallback): # +1 <> {0:1} self.source_func = { - TOKEN_TITL : self.__source_title, - TOKEN_TAXT : self.__source_taxt_peri, - TOKEN_PERI : self.__source_taxt_peri, - TOKEN_AUTH : self.__source_auth, - TOKEN_PUBL : self.__source_publ, - TOKEN_NOTE : self.__source_note, - TOKEN_RNOTE : self.__source_note, - TOKEN_TEXT : self.__source_text, - TOKEN_ABBR : self.__source_abbr, - TOKEN_REFN : self.__source_attr, - TOKEN_RIN : self.__source_attr, - TOKEN_REPO : self.__source_repo, - TOKEN_OBJE : self.__source_object, - TOKEN_CHAN : self.__source_chan, - TOKEN_MEDI : self.__source_attr, - TOKEN__NAME : self.__source_attr, - TOKEN_DATA : self.__ignore, + TOKEN_TITL : self.__source_title, + TOKEN_TAXT : self.__source_taxt_peri, + TOKEN_PERI : self.__source_taxt_peri, + TOKEN_AUTH : self.__source_auth, + TOKEN_PUBL : self.__source_publ, + TOKEN_NOTE : self.__source_note, + TOKEN_RNOTE : self.__source_note, + TOKEN_TEXT : self.__source_text, + TOKEN_ABBR : self.__source_abbr, + TOKEN_REFN : self.__source_attr, + TOKEN_RIN : self.__source_attr, + TOKEN_REPO : self.__source_repo, + TOKEN_OBJE : self.__source_object, + TOKEN_CHAN : self.__source_chan, + TOKEN_MEDI : self.__source_attr, + TOKEN__NAME : self.__source_attr, + TOKEN_DATA : self.__ignore, # TYPE should be below REFN, but will work here anyway - TOKEN_TYPE : self.__source_attr, - TOKEN_CALN : self.__ignore, + TOKEN_TYPE : self.__source_attr, + TOKEN_CALN : self.__ignore, # not legal, but Ultimate Family Tree does this - TOKEN_DATE : self.__ignore, - TOKEN_IGNORE : self.__ignore, + TOKEN_DATE : self.__ignore, + TOKEN_IGNORE : self.__ignore, } self.func_list.append(self.source_func) # # Parse table for <> below the level 0 OBJE tag - # + # # n @@ OBJE {1:1} # +1 FORM {1:1} # +1 TITL {0:1} @@ -2463,89 +2463,89 @@ class GedcomParser(UpdateCallback): # +1 RIN {0:1} self.obje_func = { - TOKEN_FORM : self.__obje_form, - TOKEN_TITL : self.__obje_title, - TOKEN_FILE : self.__obje_file, - TOKEN_NOTE : self.__obje_note, - TOKEN_RNOTE : self.__obje_note, - TOKEN_BLOB : self.__obje_blob, - TOKEN_REFN : self.__obje_refn, - TOKEN_TYPE : self.__obje_type, - TOKEN_RIN : self.__obje_rin, - TOKEN_CHAN : self.__obje_chan, + TOKEN_FORM : self.__obje_form, + TOKEN_TITL : self.__obje_title, + TOKEN_FILE : self.__obje_file, + TOKEN_NOTE : self.__obje_note, + TOKEN_RNOTE : self.__obje_note, + TOKEN_BLOB : self.__obje_blob, + TOKEN_REFN : self.__obje_refn, + TOKEN_TYPE : self.__obje_type, + TOKEN_RIN : self.__obje_rin, + TOKEN_CHAN : self.__obje_chan, } self.func_list.append(self.obje_func) self.parse_addr_tbl = { - TOKEN_DATE : self.__address_date, - TOKEN_ADR1 : self.__address_adr1, - TOKEN_ADR2 : self.__address_adr2, - TOKEN_CITY : self.__address_city, - TOKEN_STAE : self.__address_state, - TOKEN_POST : self.__address_post, - TOKEN_CTRY : self.__address_country, - TOKEN_PHON : self.__ignore, - TOKEN_SOUR : self.__address_sour, - TOKEN_NOTE : self.__address_note, - TOKEN_RNOTE : self.__address_note, - TOKEN__LOC : self.__ignore, - TOKEN__NAME : self.__ignore, - TOKEN_IGNORE : self.__ignore, - TOKEN_TYPE : self.__ignore, - TOKEN_CAUS : self.__ignore, + TOKEN_DATE : self.__address_date, + TOKEN_ADR1 : self.__address_adr1, + TOKEN_ADR2 : self.__address_adr2, + TOKEN_CITY : self.__address_city, + TOKEN_STAE : self.__address_state, + TOKEN_POST : self.__address_post, + TOKEN_CTRY : self.__address_country, + TOKEN_PHON : self.__ignore, + TOKEN_SOUR : self.__address_sour, + TOKEN_NOTE : self.__address_note, + TOKEN_RNOTE : self.__address_note, + TOKEN__LOC : self.__ignore, + TOKEN__NAME : self.__ignore, + TOKEN_IGNORE : self.__ignore, + TOKEN_TYPE : self.__ignore, + TOKEN_CAUS : self.__ignore, } self.func_list.append(self.parse_addr_tbl) self.event_cause_tbl = { - TOKEN_SOUR : self.__event_cause_source, + TOKEN_SOUR : self.__event_cause_source, } self.func_list.append(self.event_cause_tbl) self.event_place_map = { - TOKEN_NOTE : self.__event_place_note, - TOKEN_RNOTE : self.__event_place_note, - TOKEN_FORM : self.__event_place_form, + TOKEN_NOTE : self.__event_place_note, + TOKEN_RNOTE : self.__event_place_note, + TOKEN_FORM : self.__event_place_form, # Not legal. - TOKEN_OBJE : self.__event_place_object, - TOKEN_SOUR : self.__event_place_sour, - TOKEN__LOC : self.__ignore, - TOKEN_MAP : self.__place_map, + TOKEN_OBJE : self.__event_place_object, + TOKEN_SOUR : self.__event_place_sour, + TOKEN__LOC : self.__ignore, + TOKEN_MAP : self.__place_map, # Not legal, but generated by Ultimate Family Tree - TOKEN_QUAY : self.__ignore, + TOKEN_QUAY : self.__ignore, } self.func_list.append(self.event_place_map) self.place_map_tbl = { - TOKEN_LATI : self.__place_lati, - TOKEN_LONG : self.__place_long, + TOKEN_LATI : self.__place_lati, + TOKEN_LONG : self.__place_long, } self.func_list.append(self.place_map_tbl) self.repo_ref_tbl = { - TOKEN_CALN : self.__repo_ref_call, - TOKEN_NOTE : self.__repo_ref_note, - TOKEN_RNOTE : self.__repo_ref_note, - TOKEN_MEDI : self.__repo_ref_medi, - TOKEN_IGNORE : self.__ignore, + TOKEN_CALN : self.__repo_ref_call, + TOKEN_NOTE : self.__repo_ref_note, + TOKEN_RNOTE : self.__repo_ref_note, + TOKEN_MEDI : self.__repo_ref_medi, + TOKEN_IGNORE : self.__ignore, } self.func_list.append(self.repo_ref_tbl) self.parse_person_adopt = { - TOKEN_ADOP : self.__person_adopt_famc_adopt, + TOKEN_ADOP : self.__person_adopt_famc_adopt, } self.func_list.append(self.parse_person_adopt) self.opt_note_tbl = { - TOKEN_RNOTE : self.__optional_note, - TOKEN_NOTE : self.__optional_note, + TOKEN_RNOTE : self.__optional_note, + TOKEN_NOTE : self.__optional_note, } self.func_list.append(self.opt_note_tbl) self.citation_data_tbl = { - TOKEN_DATE : self.__citation_data_date, + TOKEN_DATE : self.__citation_data_date, TOKEN_TEXT : self.__citation_data_text, - TOKEN_RNOTE : self.__citation_data_note, - TOKEN_NOTE : self.__citation_data_note, + TOKEN_RNOTE : self.__citation_data_note, + TOKEN_NOTE : self.__citation_data_note, } self.func_list.append(self.citation_data_tbl) @@ -2553,10 +2553,10 @@ class GedcomParser(UpdateCallback): TOKEN_ROLE : self.__citation_even_role, } self.func_list.append(self.citation_even_tbl) - + # # Parse table for <
> record below the level 0 HEAD tag - # + # # n HEAD {1:1} # +1 SOUR {1:1} # +2 VERS {0:1} @@ -2587,62 +2587,62 @@ class GedcomParser(UpdateCallback): # * NOTE: Submissions to the Family History Department for Ancestral # File submission or for clearing temple ordinances must use a # DESTination of ANSTFILE or TempleReady. - + self.head_parse_tbl = { - TOKEN_SOUR : self.__header_sour, + TOKEN_SOUR : self.__header_sour, TOKEN_NAME : self.__header_sour_name, # This should be below SOUR TOKEN_VERS : self.__header_sour_vers, # This should be below SOUR - TOKEN_FILE : self.__header_file, - TOKEN_COPR : self.__header_copr, - TOKEN_SUBM : self.__header_subm, + TOKEN_FILE : self.__header_file, + TOKEN_COPR : self.__header_copr, + TOKEN_SUBM : self.__header_subm, TOKEN_CORP : self.__ignore, # This should be below SOUR TOKEN_DATA : self.__ignore, # This should be below SOUR - TOKEN_SUBN : self.__header_subn, - TOKEN_LANG : self.__header_lang, - TOKEN_TIME : self.__ignore, # This should be below DATE - TOKEN_DEST : self.__header_dest, - TOKEN_CHAR : self.__header_char, - TOKEN_GEDC : self.__header_gedc, - TOKEN__SCHEMA: self.__ignore, - TOKEN_PLAC : self.__header_plac, - TOKEN_DATE : self.__header_date, - TOKEN_NOTE : self.__header_note, + TOKEN_SUBN : self.__header_subn, + TOKEN_LANG : self.__header_lang, + TOKEN_TIME : self.__ignore, # This should be below DATE + TOKEN_DEST : self.__header_dest, + TOKEN_CHAR : self.__header_char, + TOKEN_GEDC : self.__header_gedc, + TOKEN__SCHEMA: self.__ignore, + TOKEN_PLAC : self.__header_plac, + TOKEN_DATE : self.__header_date, + TOKEN_NOTE : self.__header_note, } self.func_list.append(self.head_parse_tbl) self.header_sour_parse_tbl = { TOKEN_VERS : self.__header_sour_vers, - TOKEN_NAME : self.__header_sour_name, + TOKEN_NAME : self.__header_sour_name, TOKEN_CORP : self.__header_sour_corp, TOKEN_DATA : self.__header_sour_data, } self.func_list.append(self.header_sour_parse_tbl) self.header_sour_data = { - TOKEN_DATE : self.__header_sour_date, - TOKEN_COPR : self.__header_sour_copr, + TOKEN_DATE : self.__header_sour_date, + TOKEN_COPR : self.__header_sour_copr, } self.func_list.append(self.header_sour_data) self.header_corp_addr = { - TOKEN_ADDR : self.__repo_addr, - TOKEN_PHON : self.__repo_phon, + TOKEN_ADDR : self.__repo_addr, + TOKEN_PHON : self.__repo_phon, } self.func_list.append(self.header_corp_addr) self.header_subm = { - TOKEN_NAME : self.__header_subm_name, + TOKEN_NAME : self.__header_subm_name, } self.func_list.append(self.header_subm) self.place_form = { - TOKEN_FORM : self.__place_form, + TOKEN_FORM : self.__place_form, } self.func_list.append(self.place_form) # # Parse table for <> below the level 0 NOTE tag - # + # # n @@ NOTE {1:1} # +1 [ CONC | CONT] {0:M} # +1 <> {0:M} @@ -2652,14 +2652,14 @@ class GedcomParser(UpdateCallback): # +1 <> {0:1} self.note_parse_tbl = { - TOKEN_SOUR : self.__ignore, - TOKEN_REFN : self.__ignore, - TOKEN_RIN : self.__ignore, - TOKEN_CHAN : self.__note_chan, + TOKEN_SOUR : self.__ignore, + TOKEN_REFN : self.__ignore, + TOKEN_RIN : self.__ignore, + TOKEN_CHAN : self.__note_chan, } self.func_list.append(self.note_parse_tbl) - # look for existing place titles, build a map + # look for existing place titles, build a map self.place_names = defaultdict(list) cursor = dbase.get_place_cursor() data = next(cursor) @@ -2688,10 +2688,10 @@ class GedcomParser(UpdateCallback): fullpath = os.path.normpath(os.path.abspath(filename)) self.geddir = os.path.dirname(fullpath) - + self.error_count = 0 amap = PERSONALCONSTANTATTRIBUTES - + self.attrs = list(amap.values()) self.gedattr = dict([key, val] for val, key in amap.items()) self.search_paths = [] @@ -2699,7 +2699,7 @@ class GedcomParser(UpdateCallback): def parse_gedcom_file(self, use_trans=False): """ Parses the opened GEDCOM file. - + LINEAGE_LINKED_GEDCOM: = 0 <
> {1:1} 0 <> {0:1} @@ -2728,9 +2728,9 @@ class GedcomParser(UpdateCallback): src.set_title(title) self.dbase.add_source(src, self.trans) self.__clean_up() - + self.place_import.generate_hierarchy(self.trans) - + if not self.dbase.get_feature("skip-check-xref"): self.__check_xref() self.dbase.enable_signals() @@ -2759,7 +2759,7 @@ class GedcomParser(UpdateCallback): del self.func_list del self.update self.lexer.clean_up() - + def __find_person_handle(self, gramps_id): """ Return the database handle associated with the person's GRAMPS ID @@ -2771,7 +2771,7 @@ class GedcomParser(UpdateCallback): Return the database handle associated with the family's GRAMPS ID """ return self.__find_from_handle(gramps_id, self.fid2id) - + def __find_object_handle(self, gramps_id): """ Return the database handle associated with the media object's GRAMPS ID @@ -2787,7 +2787,7 @@ class GedcomParser(UpdateCallback): def __find_or_create_person(self, gramps_id): """ Finds or creates a person based on the GRAMPS ID. If the ID is - already used (is in the db), we return the item in the db. Otherwise, + already used (is in the db), we return the item in the db. Otherwise, we create a new person, assign the handle and GRAMPS ID. """ person = Person() @@ -2803,7 +2803,7 @@ class GedcomParser(UpdateCallback): def __find_or_create_family(self, gramps_id): """ Finds or creates a family based on the GRAMPS ID. If the ID is - already used (is in the db), we return the item in the db. Otherwise, + already used (is in the db), we return the item in the db. Otherwise, we create a new family, assign the handle and GRAMPS ID. """ family = Family() @@ -2821,7 +2821,7 @@ class GedcomParser(UpdateCallback): def __find_or_create_object(self, gramps_id): """ Finds or creates a media object based on the GRAMPS ID. If the ID is - already used (is in the db), we return the item in the db. Otherwise, + already used (is in the db), we return the item in the db. Otherwise, we create a new media object, assign the handle and GRAMPS ID. """ obj = MediaObject() @@ -2836,11 +2836,11 @@ class GedcomParser(UpdateCallback): def __find_or_create_source(self, gramps_id): """ - Find or create a source based on the GRAMPS ID. - - If the ID is already used (is in the db), we return the item in the + Find or create a source based on the GRAMPS ID. + + If the ID is already used (is in the db), we return the item in the db. Otherwise, we create a new source, assign the handle and GRAMPS ID. - + """ obj = Source() intid = self.sid2id.get(gramps_id) @@ -2855,11 +2855,11 @@ class GedcomParser(UpdateCallback): def __find_or_create_repository(self, gramps_id): """ Finds or creates a repository based on the GRAMPS ID. If the ID is - already used (is in the db), we return the item in the db. Otherwise, + already used (is in the db), we return the item in the db. Otherwise, we create a new repository, assign the handle and GRAMPS ID. - Some GEDCOM "flavors" destroy the specification, and declare the - repository inline instead of in a object. + Some GEDCOM "flavors" destroy the specification, and declare the + repository inline instead of in a object. """ repository = Repository() intid = self.rid2id.get(gramps_id) @@ -2874,11 +2874,11 @@ class GedcomParser(UpdateCallback): def __find_or_create_note(self, gramps_id): """ Finds or creates a repository based on the GRAMPS ID. If the ID is - already used (is in the db), we return the item in the db. Otherwise, + already used (is in the db), we return the item in the db. Otherwise, we create a new repository, assign the handle and GRAMPS ID. - Some GEDCOM "flavors" destroy the specification, and declare the - repository inline instead of in a object. + Some GEDCOM "flavors" destroy the specification, and declare the + repository inline instead of in a object. """ note = Note() if not gramps_id: @@ -2901,7 +2901,7 @@ class GedcomParser(UpdateCallback): def __loc_is_empty(self, location): """ Determines whether a location is empty. - + @param location: The current location @type location: gen.lib.Location @return True of False @@ -2913,11 +2913,11 @@ class GedcomParser(UpdateCallback): elif location.is_empty(): return True return False - + def __find_place(self, title, location, placeref_list): """ Finds an existing place based on the title and primary location. - + @param title: The place title @type title: string @param location: The current location @@ -2942,7 +2942,7 @@ class GedcomParser(UpdateCallback): """ Add a new place to an event if not already present, or update a place. - + @param event: The event @type event: gen.lib.Event @param substate: The sub-state for PLAC or ADDR elements (i.e. parsed by @@ -2970,12 +2970,12 @@ class GedcomParser(UpdateCallback): tries = [] fullname = fullname.replace('\\', os.path.sep) tries.append(fullname) - + try: if os.path.isfile(fullname): return (1, fullname) except UnicodeEncodeError: - # FIXME: problem possibly caused by umlaut/accented character + # FIXME: problem possibly caused by umlaut/accented character # in filename return (0, tries) other = os.path.join(altpath, fullname) @@ -3006,7 +3006,7 @@ class GedcomParser(UpdateCallback): if not self.backoff: self.groups = self.lexer.readline() self.update() - + # EOF ? if not self.groups: self.backoff = False @@ -3021,7 +3021,7 @@ class GedcomParser(UpdateCallback): self.backoff = False return self.groups - + def __undefined(self, line, state): """ @param line: The current line in GedLine format @@ -3078,11 +3078,11 @@ class GedcomParser(UpdateCallback): return self.__add_msg(_("Skipped subordinate line"), line, state) skips += 1 - + def __level_is_finished(self, text, level): """ Check to see if the level has been completed, indicated by finding - a level indiciated by the passed level value. If the level is finished, + a level indiciated by the passed level value. If the level is finished, then make sure to call self._backup to reset the text pointer. """ done = text.level < level @@ -3098,7 +3098,7 @@ class GedcomParser(UpdateCallback): problem = problem.ljust(prob_width)[0:(prob_width-1)] text = str(line.data).replace("\n", "\n".ljust(prob_width + 22)) message = "%s Line %5d: %s %s %s\n" % (problem, line.line, - line.level, + line.level, line.token_text, text) else: @@ -3113,7 +3113,7 @@ class GedcomParser(UpdateCallback): message = _("Records not imported into ") + record_name + ":\n\n" + \ state.msg new_note = Note() - tag = StyledTextTag(StyledTextTagType.FONTFACE, 'Monospace', + tag = StyledTextTag(StyledTextTagType.FONTFACE, 'Monospace', [(0, len(message))]) text = StyledText(message, [tag]) new_note.set_styledtext(text) @@ -3140,10 +3140,10 @@ class GedcomParser(UpdateCallback): # Check whether an object exists for the mapped gramps_id bgramps_id = gramps_id.encode('utf-8') if not trans.get(bgramps_id): - handle = self.__find_from_handle(gramps_id, + handle = self.__find_from_handle(gramps_id, gramps_id2handle) if msg == "FAM": - make_unknown(gramps_id, self.explanation.handle, + make_unknown(gramps_id, self.explanation.handle, class_func, commit_func, self.trans, db=self.dbase) self.__add_msg(_("Error: %(msg)s '%(gramps_id)s'" @@ -3152,7 +3152,7 @@ class GedcomParser(UpdateCallback): {'msg' : msg, 'gramps_id' : gramps_id, 'xref' : input_id}) else: - make_unknown(gramps_id, self.explanation.handle, + make_unknown(gramps_id, self.explanation.handle, class_func, commit_func, self.trans) self.missing_references +=1 self.__add_msg(_("Error: %(msg)s '%(gramps_id)s'" @@ -3161,7 +3161,7 @@ class GedcomParser(UpdateCallback): " attribute 'Unknown' created") % {'msg' : msg, 'gramps_id' : gramps_id, 'xref' : input_id}) - + self.explanation = create_explanation_note(self.dbase) self.missing_references = 0 @@ -3184,7 +3184,7 @@ class GedcomParser(UpdateCallback): for (k,v) in self.fid_map.map().items(): if v == gramps_id: return k - + for input_id, gramps_id in self.pid_map.map().items(): person_handle = self.__find_from_handle(gramps_id, self.gid2id) person = self.dbase.get_person_from_handle(person_handle) @@ -3199,23 +3199,23 @@ class GedcomParser(UpdateCallback): " (input as %(orig_person)s) is not a" " member of the referenced family." " Family reference removed from person") % - {'family' : family.gramps_id, - 'orig_family' : + {'family' : family.gramps_id, + 'orig_family' : __input_fid(family.gramps_id), 'person' : person.gramps_id, 'orig_person' : input_id}) - + def __input_pid(gramps_id): for (k,v) in self.pid_map.map().items(): if v == gramps_id: return k - + for input_id, gramps_id in self.fid_map.map().items(): family_handle = self.__find_from_handle(gramps_id, self.fid2id) family = self.dbase.get_family_from_handle(family_handle) father_handle = family.get_father_handle() mother_handle = family.get_mother_handle() - + if father_handle: father = self.dbase.get_person_from_handle(father_handle) if father and \ @@ -3225,11 +3225,11 @@ class GedcomParser(UpdateCallback): self.__add_msg("Error: family '%(family)s' (input as" " @%(orig_family)s@) father '%(father)s'" " (input as '%(orig_father)s') does not refer" - " back to the family. Reference added." % - {'family' : family.gramps_id, - 'orig_family' : input_id, + " back to the family. Reference added." % + {'family' : family.gramps_id, + 'orig_family' : input_id, 'father' : father.gramps_id, - 'orig_father' : + 'orig_father' : __input_pid(father.gramps_id)}) if mother_handle: @@ -3241,11 +3241,11 @@ class GedcomParser(UpdateCallback): self.__add_msg("Error: family '%(family)s' (input as" " @%(orig_family)s@) mother '%(mother)s'" " (input as '%(orig_mother)s') does not refer" - " back to the family. Reference added." % - {'family' : family.gramps_id, - 'orig_family' : input_id, + " back to the family. Reference added." % + {'family' : family.gramps_id, + 'orig_family' : input_id, 'mother' : mother.gramps_id, - 'orig_mother' : + 'orig_mother' : __input_pid(mother.gramps_id)}) for child_ref in family.get_child_ref_list(): @@ -3263,11 +3263,11 @@ class GedcomParser(UpdateCallback): " @%(orig_family)s@) child '%(child)s'" " (input as '%(orig_child)s') does not " "refer back to the family. " - "Reference added." % - {'family' : family.gramps_id, - 'orig_family' : input_id, + "Reference added." % + {'family' : family.gramps_id, + 'orig_family' : input_id, 'child' : child.gramps_id, - 'orig_child' : + 'orig_child' : __input_pid(child.gramps_id)}) if self.missing_references: @@ -3280,11 +3280,11 @@ class GedcomParser(UpdateCallback): ) % {'new': self.missing_references, 'unknown': self.explanation.gramps_id} self.__add_msg(txt) self.number_of_errors -= 1 - + def __merge_address(self, free_form_address, addr, line, state): """ Merge freeform and structured addrssses. - n ADDR {0:1} + n ADDR {0:1} +1 CONT {0:M} +1 ADR1 {0:1} (Street) +1 ADR2 {0:1} (Locality) @@ -3292,32 +3292,32 @@ class GedcomParser(UpdateCallback): +1 STAE {0:1} +1 POST {0:1} +1 CTRY {0:1} - + This is done along the lines suggested by Tamura Jones in http://www.tamurajones.net/GEDCOMADDR.xhtml as a result of bug 6382. "When a GEDCOM reader encounters a double address, it should read the structured address. ... A GEDCOM reader that does verify that the addresses are the same should issue an error if they are not". - + This is called for SUBMitter addresses (__subm_addr), INDIvidual addresses (__person_addr), REPO addresses and HEADer corp address (__repo_address) and EVENt addresses (__event_adr). - + The structured address (if any) will have been accumulated into an object of type LocationBase, which will either be a Location, or an Address object. - + If ADDR is provided, but none of ADR1, ADR2, CITY, STAE, or POST (not CTRY), then Street is set to the freeform address. N.B. this is a change for Repository addresses and HEADer Corp address where previously the free-form address was deconstrucated into different structured components. N.B. PAF provides a free-form address and a country, so this allows for that case. - + If both forms of address are provided, then the structured address is used, and if the ADDR/CONT contains anything not in the structured address, a warning is issued. - + If just ADR1, ADR2, CITY, STAE, POST or CTRY are provided (this is not actually legal GEDCOM symtax, but may be possible by GEDCOM extensions) then just the structrued address is used. @@ -3325,7 +3325,7 @@ class GedcomParser(UpdateCallback): if not (addr.get_street() or addr.get_locality() or addr.get_city() or addr.get_state() or addr.get_postal_code()): - + addr.set_street(free_form_address) else: # structured address provided @@ -3356,7 +3356,7 @@ class GedcomParser(UpdateCallback): self.__check_msgs(_("TRLR (trailer)"), state, None) except TypeError: return - + def __parse_submitter(self, line): """ Parses the submitter data @@ -3377,11 +3377,11 @@ class GedcomParser(UpdateCallback): repo = Repository() state.repo = repo self.__parse_level(state, self.subm_parse_tbl, self.__undefined) - # If this is the submitter that we were told about in the HEADer, then + # If this is the submitter that we were told about in the HEADer, then # we will need to update the researcher if line.token_text == self.subm and self.import_researcher: self.dbase.set_researcher(state.res) - + localized_submitter = _("(Submitter):") if state.res.get_name() == "": submitter_name = "SUBM %s @%s@" % ( localized_submitter, @@ -3394,7 +3394,7 @@ class GedcomParser(UpdateCallback): repo.set_name(submitter_name) repo.set_handle(create_id()) repo.set_gramps_id(self.dbase.find_next_repository_gramps_id()) - + addr = Address() addr.set_street(state.res.get_address()) addr.set_locality(state.res.get_locality()) @@ -3405,13 +3405,13 @@ class GedcomParser(UpdateCallback): addr.set_county(state.res.get_county()) addr.set_phone(state.res.get_phone()) repo.add_address(addr) - + if state.res.get_email(): url = Url() url.set_path(state.res.get_email()) url.set_type(UrlType(UrlType.EMAIL)) repo.add_url(url) - + rtype = RepositoryType() rtype.set((RepositoryType.CUSTOM, _('GEDCOM data'))) repo.set_type(rtype) @@ -3426,7 +3426,7 @@ class GedcomParser(UpdateCallback): self.dbase.commit_source(self.def_src, self.trans) else: self.__check_msgs(submitter_name, state, None) - + def __parse_record(self): """ @@ -3446,8 +3446,8 @@ class GedcomParser(UpdateCallback): n <> {1:1} | n <> {1:1} - ] - + ] + This also deals with the SUBN (submission) record, of which there should be exactly one. """ @@ -3501,15 +3501,15 @@ class GedcomParser(UpdateCallback): state = CurrentState() self.__not_recognized(line, 1, state) self.__check_msgs(_("Top Level"), state, None) - + def __parse_level(self, state, __map, default): """ - Loop trough the current GEDCOM level, calling the appropriate - functions associated with the TOKEN. - - If no matching function for the token is found, the default function + Loop trough the current GEDCOM level, calling the appropriate + functions associated with the TOKEN. + + If no matching function for the token is found, the default function is called instead. - + """ while True: line = self.__get_next_line() @@ -3547,7 +3547,7 @@ class GedcomParser(UpdateCallback): +1 DESI @@ {0:M} +1 <> {0:M} +1 <> {0:M} - +1 <> {0:M} + +1 <> {0:M} +1 RFN {0:1} +1 AFN {0:1} +1 REFN {0:M} @@ -3572,7 +3572,7 @@ class GedcomParser(UpdateCallback): # Add a default tag if provided self.__add_default_tag(person) - self.__check_msgs(_("INDI (individual) Gramps ID %s") % + self.__check_msgs(_("INDI (individual) Gramps ID %s") % person.get_gramps_id(), state, person) # commit the person to the database self.dbase.commit_person(person, self.trans, state.person.change) @@ -3610,8 +3610,8 @@ class GedcomParser(UpdateCallback): # parse table is encountered. It is remotely possible that this is # actally a DATE tag, in which case line.data will be a date object, so # we need to convert it back to a string here. - event_ref = self.__build_event_pair(state, EventType.CUSTOM, - self.event_parse_tbl, + event_ref = self.__build_event_pair(state, EventType.CUSTOM, + self.event_parse_tbl, str(line.data)) state.person.add_event_ref(event_ref) @@ -3622,9 +3622,9 @@ class GedcomParser(UpdateCallback): @param state: The current state @type state: CurrentState """ - event_ref = self.__build_family_event_pair(state, - EventType.CUSTOM, - self.event_parse_tbl, + event_ref = self.__build_family_event_pair(state, + EventType.CUSTOM, + self.event_parse_tbl, line.data) state.family.add_event_ref(event_ref) @@ -3636,7 +3636,7 @@ class GedcomParser(UpdateCallback): @type state: CurrentState """ self.__parse_change(line, state.person, state.level+1, state) - + def __person_resn(self, line, state): """ Parses the RESN tag, adding it as an attribute. @@ -3653,22 +3653,22 @@ class GedcomParser(UpdateCallback): def __person_alt_name(self, line, state): """ This parses the standard GEDCOM structure: - + n @XREF:INDI@ INDI {1:1} +1 ALIA @@ {0:M} - + The ALIA tag is supposed to cross reference another person. We will store this in the Association record. - + ALIA {ALIAS}: = An indicator to link different record descriptions of a person who may be the same person. - + Some systems use the ALIA tag as an alternate NAME tag, which is not legal in GEDCOM, but oddly enough, is easy to support. This parses the illegal (ALIA or ALIAS) or non-standard (_ALIA) GEDCOM. "1 ALIA" is used by Family Tree Maker and Reunion. "1 ALIAS" and "1 _ALIA" do not appear to be used. - + n @XREF:INDI@ INDI {1:1} +1 {1:1} +2 NPFX {0:1} @@ -3682,7 +3682,7 @@ class GedcomParser(UpdateCallback): +3 <> {0:M} +2 <> {0:M} where == ALIA | _ALIA | ALIAS - + @param line: The current line in GedLine format @type line: GedLine @param state: The current state @@ -3699,14 +3699,14 @@ class GedcomParser(UpdateCallback): state.person.add_person_ref(ref) else: self.__parse_alias_name(line, state) - + def __parse_alias_name(self, line, state): """ Parse a level 1 alias name and subsidiary levels when called from __person_alt_name (when the does not start with @). Also parses a level 2 alias name and subsidiary levels when called from __name_alias. - + +1 {1:1} +2 NPFX {0:1} +2 GIVN {0:1} @@ -3740,13 +3740,13 @@ class GedcomParser(UpdateCallback): def __person_object(self, line, state): """ - + Embedded form - + > n OBJE @@ {1:1} Linked form - + > n OBJE {1:1} > +1 FORM {1:1} > +1 TITL {0:1} @@ -3761,7 +3761,7 @@ class GedcomParser(UpdateCallback): if line.data and line.data[0] == '@': # Reference to a named multimedia object defined elsewhere gramps_id = self.oid_map[line.data] - + handle = self.__find_object_handle(gramps_id) ref = MediaRef() ref.set_reference_handle(handle) @@ -3801,7 +3801,7 @@ class GedcomParser(UpdateCallback): """ # build a Name structure from the text - + name = self.__parse_name_personal(line.data) # Add the name as the primary name if this is the first one that @@ -3809,7 +3809,7 @@ class GedcomParser(UpdateCallback): # first name, that it is a birth name. Otherwise, label it as an # "Also Known As (AKA)". GEDCOM does not seem to have the concept # of different name types - + if state.name_cnt == 0: name.set_type(NameType.BIRTH) state.person.set_primary_name(name) @@ -3852,7 +3852,7 @@ class GedcomParser(UpdateCallback): @param state: The current state @type state: CurrentState """ - event_ref = self.__build_event_pair(state, EventType.CUSTOM, + event_ref = self.__build_event_pair(state, EventType.CUSTOM, self.event_parse_tbl, line.data) state.person.add_event_ref(event_ref) @@ -3885,7 +3885,7 @@ class GedcomParser(UpdateCallback): state.msg += sub_state.msg self.__add_place(event, sub_state) - + self.dbase.commit_event(event, self.trans) event_ref.ref = event.handle state.person.add_event_ref(event_ref) @@ -3902,14 +3902,14 @@ class GedcomParser(UpdateCallback): @param state: The current state @type state: CurrentState """ - event_ref = self.__build_event_pair(state, EventType.RELIGION, + event_ref = self.__build_event_pair(state, EventType.RELIGION, self.event_parse_tbl, line.data) state.person.add_event_ref(event_ref) def __person_birt(self, line, state): """ Parses GEDCOM BIRT tag into a GRAMPS birth event. Additional work - must be done, since additional handling must be done by GRAMPS to set + must be done, since additional handling must be done by GRAMPS to set this up as a birth reference event. n BIRT [Y|] {1:1} @@ -3925,7 +3925,7 @@ class GedcomParser(UpdateCallback): @param state: The current state @type state: CurrentState """ - event_ref = self.__build_event_pair(state, EventType.BIRTH, + event_ref = self.__build_event_pair(state, EventType.BIRTH, self.event_parse_tbl, line.data) if state.person.get_birth_ref(): state.person.add_event_ref(event_ref) @@ -3947,14 +3947,14 @@ class GedcomParser(UpdateCallback): @param state: The current state @type state: CurrentState """ - event_ref = self.__build_event_pair(state, EventType.ADOPT, + event_ref = self.__build_event_pair(state, EventType.ADOPT, self.adopt_parse_tbl, line.data) state.person.add_event_ref(event_ref) def __person_deat(self, line, state): """ Parses GEDCOM DEAT tag into a GRAMPS birth event. Additional work - must be done, since additional handling must be done by GRAMPS to set + must be done, since additional handling must be done by GRAMPS to set this up as a death reference event. n DEAT [Y|] {1:1} @@ -3965,7 +3965,7 @@ class GedcomParser(UpdateCallback): @param state: The current state @type state: CurrentState """ - event_ref = self.__build_event_pair(state, EventType.DEATH, + event_ref = self.__build_event_pair(state, EventType.DEATH, self.event_parse_tbl, line.data) if state.person.get_death_ref(): state.person.add_event_ref(event_ref) @@ -3998,7 +3998,7 @@ class GedcomParser(UpdateCallback): """ Parses the INDIvidual - n ADDR {0:1} + n ADDR {0:1} +1 CONT {0:M} +1 ADR1 {0:1} (Street) +1 ADR2 {0:1} (Locality) @@ -4014,13 +4014,13 @@ class GedcomParser(UpdateCallback): @type state: CurrentState """ free_form = line.data - + sub_state = CurrentState(level=state.level + 1) sub_state.addr = Address() - + self.__parse_level(sub_state, self.parse_addr_tbl, self.__ignore) state.msg += sub_state.msg - + self.__merge_address(free_form, sub_state.addr, line, state) state.person.add_address(sub_state.addr) @@ -4038,7 +4038,7 @@ class GedcomParser(UpdateCallback): addr.set_phone(line.data) state.person.add_address(addr) self.__skip_subordinate_levels(state.level+1, state) - + def __person_email(self, line, state): """ O INDI @@ -4053,7 +4053,7 @@ class GedcomParser(UpdateCallback): url.set_path(line.data) url.set_type(UrlType(UrlType.EMAIL)) state.person.add_url(url) - + def __person_url(self, line, state): """ O INDI @@ -4093,7 +4093,7 @@ class GedcomParser(UpdateCallback): state.msg += sub_state.msg self.__add_place(event, sub_state) - + self.dbase.add_event(event, self.trans) event_ref.ref = event.handle state.person.add_event_ref(event_ref) @@ -4145,7 +4145,7 @@ class GedcomParser(UpdateCallback): """ This parses the illegal (ALIA or ALIAS) or non-standard (_ALIA) GEDCOM tag as a subsidiary of the NAME tag. - + n @XREF:INDI@ INDI {1:1} +1 NAME {1:1} +2 NPFX {0:1} @@ -4174,11 +4174,11 @@ class GedcomParser(UpdateCallback): name (if the same elements are provided in both), so the names should match. - "2 _ALIA" is used for example, by PRO-GEN v 3.0a and "2 ALIA" is used + "2 _ALIA" is used for example, by PRO-GEN v 3.0a and "2 ALIA" is used by GTEdit and Brother's keeper 5.2 for windows. It had been supported in previous versions of Gramps but as it was probably incorrectly coded as it would only work if the name started with '@'. - + @param line: The current line in GedLine format @type line: GedLine @param state: The current state @@ -4244,12 +4244,12 @@ class GedcomParser(UpdateCallback): Quest and Personal Ancestral File 5. This will also handle a usage which has been found in Brother's Keeper (BROSKEEP VERS 6.1.31 WINDOWS) as follows: - + 0 @I203@ INDI 1 NAME John Richard/Doe/ 2 _MARN Some Other Name 3 DATE 27 JUN 1817 - + @param line: The current line in GedLine format @type line: GedLine @param state: The current state @@ -4305,10 +4305,10 @@ class GedcomParser(UpdateCallback): stored by Gramps in the nick_name field of the name structure, while the _AKA, if it is a single word, will be stored in the NICKNAME attribute. If more than one word it is stored as an AKA alternate name. - + This will also handle a usage which has been found in in Brother's Keeper (BROSKEEP VERS 6.1.31 WINDOWS) as follows: - + 0 @I203@ INDI 1 NAME John Richard/Doe/ 2 _AKAN Some Other Name @@ -4318,7 +4318,7 @@ class GedcomParser(UpdateCallback): @type line: GedLine @param state: The current state @type state: CurrentState - """ + """ lname = line.data.split() name_len = len(lname) if name_len == 1: @@ -4359,7 +4359,7 @@ class GedcomParser(UpdateCallback): name.set_type((NameType.CUSTOM, "Adopted")) state.person.add_alternate_name(name) - + def __name_sour(self, line, state): """ @param line: The current line in GedLine format @@ -4384,7 +4384,7 @@ class GedcomParser(UpdateCallback): sub_state.attr = line.data sub_state.level = state.level+1 state.person.add_attribute(sub_state.attr) - self.__parse_level(sub_state, self.person_attr_parse_tbl, + self.__parse_level(sub_state, self.person_attr_parse_tbl, self.__ignore) state.msg += sub_state.msg @@ -4403,13 +4403,13 @@ class GedcomParser(UpdateCallback): sub_state.attr.set_value(line.data) sub_state.level = state.level+1 state.person.add_attribute(sub_state.attr) - self.__parse_level(sub_state, self.person_fact_parse_tbl, + self.__parse_level(sub_state, self.person_fact_parse_tbl, self.__ignore) state.msg += sub_state.msg def __person_fact_type(self, line, state): state.attr.set_type(line.data) - + def __person_bapl(self, line, state): """ Parses an BAPL TOKEN, producing a GRAMPS LdsOrd instance @@ -4478,7 +4478,7 @@ class GedcomParser(UpdateCallback): if sub_state.place: place_title = place_displayer.display(self.dbase, sub_state.place) sub_state.place_fields.load_place(self.place_import, - sub_state.place, + sub_state.place, place_title) def __lds_temple(self, line, state): @@ -4494,7 +4494,7 @@ class GedcomParser(UpdateCallback): if value: state.lds_ord.set_temple(value) - def __lds_date(self, line, state): + def __lds_date(self, line, state): """ Parses the DATE tag for the LdsOrd @@ -4517,9 +4517,9 @@ class GedcomParser(UpdateCallback): gid = self.fid_map[line.data] state.lds_ord.set_family_handle(self.__find_family_handle(gid)) - def __lds_form(self, line, state): + def __lds_form(self, line, state): """ - Parses the FORM tag thate defines the place structure for a place. + Parses the FORM tag thate defines the place structure for a place. This tag, if found, will override any global place structure. @param line: The current line in GedLine format @@ -4556,7 +4556,7 @@ class GedcomParser(UpdateCallback): def __lds_sour(self, line, state): """ - Parses the SOUR tag attached to the LdsOrd. + Parses the SOUR tag attached to the LdsOrd. @param line: The current line in GedLine format @type line: GedLine @@ -4568,7 +4568,7 @@ class GedcomParser(UpdateCallback): def __lds_note(self, line, state): """ - Parses the NOTE tag attached to the LdsOrd. + Parses the NOTE tag attached to the LdsOrd. @param line: The current line in GedLine format @type line: GedLine @@ -4577,9 +4577,9 @@ class GedcomParser(UpdateCallback): """ self.__parse_note(line, state.lds_ord, state.level+1, state) - def __lds_stat(self, line, state): + def __lds_stat(self, line, state): """ - Parses the STAT (status) tag attached to the LdsOrd. + Parses the STAT (status) tag attached to the LdsOrd. @param line: The current line in GedLine format @type line: GedLine @@ -4631,7 +4631,7 @@ class GedcomParser(UpdateCallback): # search childrefs family, new = self.dbase.find_family_from_handle(handle, self.trans) family.set_gramps_id(gid) - + for ref in family.get_child_ref_list(): if ref.ref == state.person.handle: if sub_state.ftype: @@ -4647,7 +4647,7 @@ class GedcomParser(UpdateCallback): family.add_child_ref(ref) self.dbase.commit_family(family, self.trans) - def __person_famc_pedi(self, line, state): + def __person_famc_pedi(self, line, state): """ Parses the PEDI tag attached to a INDI.FAMC record. No values are set at this point, because we have to do some post processing. Instead, we @@ -4660,7 +4660,7 @@ class GedcomParser(UpdateCallback): @param state: The current state @type state: CurrentState """ - state.ftype = PEDIGREE_TYPES.get(line.data.lower(), + state.ftype = PEDIGREE_TYPES.get(line.data.lower(), ChildRefType.UNKNOWN) def __person_famc_note(self, line, state): @@ -4674,9 +4674,9 @@ class GedcomParser(UpdateCallback): """ self.__parse_note(line, state.person, state.level+1, state) - def __person_famc_primary(self, line, state): + def __person_famc_primary(self, line, state): """ - Parses the _PRIM tag on an INDI.FAMC tag. This value is stored in + Parses the _PRIM tag on an INDI.FAMC tag. This value is stored in the state record to be used later. @param line: The current line in GedLine format @@ -4727,17 +4727,17 @@ class GedcomParser(UpdateCallback): Parse the ASSO tag, add the referenced person to the person we are currently parsing. The GEDCOM spec indicates that valid ASSO tag is: - + n ASSO @@ {0:M} - + And the sub tags are: - + ASSOCIATION_STRUCTURE:= +1 RELA {1:1} +1 <> {0:M} +1 <> {0:M} - The Gedcom spec notes that the ASSOCIATION_STRUCTURE + The Gedcom spec notes that the ASSOCIATION_STRUCTURE can only link to an INDIVIDUAL_RECORD @param line: The current line in GedLine format @@ -4764,7 +4764,7 @@ class GedcomParser(UpdateCallback): if not sub_state.ignore: state.person.add_person_ref(sub_state.ref) - def __person_asso_rela(self, line, state): + def __person_asso_rela(self, line, state): """ Parses the INDI.ASSO.RELA tag. @@ -4798,11 +4798,11 @@ class GedcomParser(UpdateCallback): self.__parse_note(line, state.ref, state.level, state) #------------------------------------------------------------------- - # + # # FAM parsing # #------------------------------------------------------------------- - + def __parse_fam(self, line): """ n @@ FAM {1:1} @@ -4821,7 +4821,7 @@ class GedcomParser(UpdateCallback): +1 <> {0:1} """ # create a family - + gid = self.fid_map[line.token_text] family = self.__find_or_create_family(gid) @@ -4858,11 +4858,11 @@ class GedcomParser(UpdateCallback): # Add a default tag if provided self.__add_default_tag(family) - self.__check_msgs(_("FAM (family) Gramps ID %s") % family.get_gramps_id(), + self.__check_msgs(_("FAM (family) Gramps ID %s") % family.get_gramps_id(), state, family) # commit family to database self.dbase.commit_family(family, self.trans, family.change) - + def __family_husb(self, line, state): """ Parses the husband line of a family @@ -4964,7 +4964,7 @@ class GedcomParser(UpdateCallback): self.__parse_level(sub_state, self.event_parse_tbl, self.__undefined) state.msg += sub_state.msg - + self.__add_place(event, sub_state) self.dbase.commit_event(event, self.trans) @@ -5016,7 +5016,7 @@ class GedcomParser(UpdateCallback): def set_child_ref_order(self, family, child_ref): """ Sets the child_ref in family.child_ref_list to be in the position - family.child_ref_count. This reorders the children to be in the + family.child_ref_count. This reorders the children to be in the order given in the FAM section. """ family.child_ref_list.remove(child_ref) @@ -5053,7 +5053,7 @@ class GedcomParser(UpdateCallback): if sub_state.place: place_title = place_displayer.display(self.dbase, sub_state.place) sub_state.place_fields.load_place(self.place_import, - sub_state.place, + sub_state.place, place_title) def __family_source(self, line, state): @@ -5092,7 +5092,7 @@ class GedcomParser(UpdateCallback): if line.data and line.data[0] == '@': # Reference to a named multimedia object defined elsewhere gramps_id = self.oid_map[line.data] - + handle = self.__find_object_handle(gramps_id) ref = MediaRef() ref.set_reference_handle(handle) @@ -5138,7 +5138,7 @@ class GedcomParser(UpdateCallback): """ self.__parse_change(line, state.family, state.level+1, state) - def __family_attr(self, line, state): + def __family_attr(self, line, state): """ @param line: The current line in GedLine format @type line: GedLine @@ -5147,7 +5147,7 @@ class GedcomParser(UpdateCallback): """ state.family.add_attribute(line.data) - def __family_cust_attr(self, line, state): + def __family_cust_attr(self, line, state): """ @param line: The current line in GedLine format @type line: GedLine @@ -5165,7 +5165,7 @@ class GedcomParser(UpdateCallback): +1 FORM {1:1} +1 TITL {0:1} +1 FILE {1:1} - +1 <> {0:M} + +1 <> {0:M} @param line: The current line in GedLine format @type line: GedLine @@ -5181,10 +5181,10 @@ class GedcomParser(UpdateCallback): self.__parse_level(sub_state, self.object_parse_tbl, self.__ignore) state.msg += sub_state.msg - return (sub_state.form, sub_state.filename, sub_state.title, + return (sub_state.form, sub_state.filename, sub_state.title, sub_state.note) - def __object_ref_form(self, line, state): + def __object_ref_form(self, line, state): """ +1 FORM {1:1} @@ -5195,7 +5195,7 @@ class GedcomParser(UpdateCallback): """ state.form = line.data - def __object_ref_titl(self, line, state): + def __object_ref_titl(self, line, state): """ +1 TITL {0:1} @@ -5206,7 +5206,7 @@ class GedcomParser(UpdateCallback): """ state.title = line.data - def __object_ref_file(self, line, state): + def __object_ref_file(self, line, state): """ +1 FILE {1:1} @@ -5217,9 +5217,9 @@ class GedcomParser(UpdateCallback): """ state.filename = line.data - def __object_ref_note(self, line, state): + def __object_ref_note(self, line, state): """ - +1 <> {0:M} + +1 <> {0:M} @param line: The current line in GedLine format @type line: GedLine @@ -5253,7 +5253,7 @@ class GedcomParser(UpdateCallback): sub_state = CurrentState(level=state.level+1) sub_state.note = new_note - self.__parse_level(sub_state, self.note_parse_tbl, + self.__parse_level(sub_state, self.note_parse_tbl, self.__undefined) state.msg += sub_state.msg @@ -5320,7 +5320,7 @@ class GedcomParser(UpdateCallback): if line.data and line.data[0] == '@': # Reference to a named multimedia object defined elsewhere gramps_id = self.oid_map[line.data] - + handle = self.__find_object_handle(gramps_id) ref = MediaRef() ref.set_reference_handle(handle) @@ -5351,7 +5351,7 @@ class GedcomParser(UpdateCallback): name = EventType((EventType.CUSTOM, val)) else: try: - name = EventType((EventType.CUSTOM, + name = EventType((EventType.CUSTOM, line.data)) except AttributeError: name = EventType(EventType.UNKNOWN) @@ -5376,7 +5376,7 @@ class GedcomParser(UpdateCallback): def __event_place(self, line, state): """ Parse the place portion of a event. A special case has to be made for - Family Tree Maker, which violates the GEDCOM spec. It uses the PLAC + Family Tree Maker, which violates the GEDCOM spec. It uses the PLAC field to store the description or value associated with the event. n PLAC {1:1} @@ -5398,7 +5398,7 @@ class GedcomParser(UpdateCallback): if place: # We encounter a PLAC, having previously encountered an ADDR if place.get_title() and place.get_title() != "": - # We have previously found a PLAC + # We have previously found a PLAC self.__add_msg(_("A second PLAC ignored"), line, state) # ignore this second PLAC, and use the old one else: @@ -5411,12 +5411,12 @@ class GedcomParser(UpdateCallback): place = state.place place.set_title(line.data) place.name.set_value(line.data) - + sub_state = CurrentState() sub_state.place = place sub_state.level = state.level+1 - self.__parse_level(sub_state, self.event_place_map, + self.__parse_level(sub_state, self.event_place_map, self.__undefined) state.msg += sub_state.msg @@ -5448,7 +5448,7 @@ class GedcomParser(UpdateCallback): if line.data and line.data[0] == '@': # Reference to a named multimedia object defined elsewhere gramps_id = self.oid_map[line.data] - + handle = self.__find_object_handle(gramps_id) ref = MediaRef() ref.set_reference_handle(handle) @@ -5473,11 +5473,11 @@ class GedcomParser(UpdateCallback): def __place_map(self, line, state): """ - + n MAP n+1 LONG n+1 LATI - + @param line: The current line in GedLine format @type line: GedLine @param state: The current state @@ -5516,7 +5516,7 @@ class GedcomParser(UpdateCallback): @type state: CurrentState """ free_form = line.data - + sub_state = CurrentState(level=state.level+1) sub_state.location = Location() sub_state.event = state.event @@ -5528,7 +5528,7 @@ class GedcomParser(UpdateCallback): self.__merge_address(free_form, sub_state.location, line, state) location = sub_state.location - + if self.addr_is_detail and state.place: # Commit the enclosing place place = self.__find_place(state.place.get_title(), None, @@ -5542,7 +5542,7 @@ class GedcomParser(UpdateCallback): self.dbase.commit_place(place, self.trans) place_title = place_displayer.display(self.dbase, place) state.pf.load_place(self.place_import, place, place_title) - + # Create the Place Details (it is committed with the event) place_detail = Place() place_detail.set_name(location.get_street()) @@ -5651,7 +5651,7 @@ class GedcomParser(UpdateCallback): self.dbase.add_note(new_note, self.trans) self.__skip_subordinate_levels(state.level+2, state) state.event.add_note(new_note.get_handle()) - + def __event_source(self, line, state): """ @param line: The current line in GedLine format @@ -5851,7 +5851,7 @@ class GedcomParser(UpdateCallback): attr.set_type(AttributeType.WITNESS) attr.set_value(line.data) state.event.add_attribute(attr) - + def __person_adopt_famc(self, line, state): """ @param line: The current line in GedLine format @@ -5867,7 +5867,7 @@ class GedcomParser(UpdateCallback): sub_state.mrel = TYPE_BIRTH sub_state.frel = TYPE_BIRTH - self.__parse_level(sub_state, self.parse_person_adopt, + self.__parse_level(sub_state, self.parse_person_adopt, self.__undefined) state.msg += sub_state.msg @@ -5878,7 +5878,7 @@ class GedcomParser(UpdateCallback): if state.person.get_main_parents_family_handle() == handle: state.person.set_main_parent_family_handle(None) state.person.add_parent_family_handle(handle) - + reflist = [ref for ref in family.get_child_ref_list() if ref.ref == state.person.handle] if reflist: @@ -5920,7 +5920,7 @@ class GedcomParser(UpdateCallback): if state.person.get_main_parents_family_handle() == handle: state.person.set_main_parent_family_handle(None) state.person.add_parent_family_handle(handle) - + frel = mrel = ChildRefType.BIRTH family, new = self.dbase.find_family_from_handle(handle, self.trans) @@ -6007,7 +6007,7 @@ class GedcomParser(UpdateCallback): @type state: CurrentState """ state.addr.set_postal_code(line.data) - + def __address_country(self, line, state): """ Parses the country line of an ADDR tag @@ -6018,7 +6018,7 @@ class GedcomParser(UpdateCallback): @type state: CurrentState """ state.addr.set_country(line.data) - + def __address_sour(self, line, state): """ Parses the SOUR line of an ADDR tag @@ -6029,7 +6029,7 @@ class GedcomParser(UpdateCallback): @type state: CurrentState """ state.addr.add_citation(self.handle_source(line, state.level, state)) - + def __address_note(self, line, state): """ Parses the NOTE line of an ADDR tag @@ -6063,7 +6063,7 @@ class GedcomParser(UpdateCallback): """ state.citation.set_date_object(line.data) - def __citation_data(self, line, state): + def __citation_data(self, line, state): """ Parses the DATA line of an SOUR instance tag @@ -6104,7 +6104,7 @@ class GedcomParser(UpdateCallback): def __citation_data_note(self, line, state): self.__parse_note(line, state.citation, state.level, state) - def __citation_obje(self, line, state): + def __citation_obje(self, line, state): """ Parses the OBJE line of an SOUR instance tag @@ -6116,7 +6116,7 @@ class GedcomParser(UpdateCallback): if line.data and line.data[0] == '@': # Reference to a named multimedia object defined elsewhere gramps_id = self.oid_map[line.data] - + handle = self.__find_object_handle(gramps_id) ref = MediaRef() ref.set_reference_handle(handle) @@ -6129,7 +6129,7 @@ class GedcomParser(UpdateCallback): self.__add_msg(_("Form omitted"), line, state) self.build_media_object(state.citation, form, filename, title, note) - def __citation_refn(self, line, state): + def __citation_refn(self, line, state): """ Parses the REFN line of an SOUR instance tag @@ -6141,7 +6141,7 @@ class GedcomParser(UpdateCallback): self.__add_msg(_("REFN ignored"), line, state) self.__skip_subordinate_levels(state.level+1, state) - def __citation_even(self, line, state): + def __citation_even(self, line, state): """ Parses the EVEN line of an SOUR instance tag @@ -6160,7 +6160,7 @@ class GedcomParser(UpdateCallback): self.__parse_level(sub_state, self.citation_even_tbl, self.__undefined) state.msg += sub_state.msg - def __citation_even_role(self, line, state): + def __citation_even_role(self, line, state): """ Parses the EVEN line of an SOUR instance tag @@ -6174,7 +6174,7 @@ class GedcomParser(UpdateCallback): sattr.set_value(line.data) state.citation.add_attribute(sattr) - def __citation_quay(self, line, state): + def __citation_quay(self, line, state): """ Parses the QUAY line of an SOUR instance tag @@ -6194,7 +6194,7 @@ class GedcomParser(UpdateCallback): else: state.citation.set_confidence_level(val) - def __citation_note(self, line, state): + def __citation_note(self, line, state): """ Parses the NOTE line of an SOUR instance tag @@ -6216,7 +6216,7 @@ class GedcomParser(UpdateCallback): n @@ SOUR {1:1} +1 DATA {0:1} +2 EVEN {0:M} - +3 DATE {0:1} + +3 DATE {0:1} +3 PLAC {0:1} +2 AGNC {0:1} +2 <> {0:M} @@ -6225,8 +6225,8 @@ class GedcomParser(UpdateCallback): +1 ABBR {0:1} +1 PUBL {0:1} +1 TEXT {0:1} - +1 <> {0:1} - +1 <> {0:M} + +1 <> {0:1} + +1 <> {0:M} +1 <> {0:M} +1 REFN {0:M} +2 TYPE {0:1} @@ -6235,15 +6235,15 @@ class GedcomParser(UpdateCallback): """ state = CurrentState() - state.source = self.__find_or_create_source(self.sid_map[name]) + state.source = self.__find_or_create_source(self.sid_map[name]) # SOURce with the given gramps_id had no title - state.source.set_title(_("No title - ID %s") % + state.source.set_title(_("No title - ID %s") % state.source.get_gramps_id()) state.level = level self.__parse_level(state, self.source_func, self.__undefined) - self.__check_msgs(_("SOUR (source) Gramps ID %s") % - state.source.get_gramps_id(), + self.__check_msgs(_("SOUR (source) Gramps ID %s") % + state.source.get_gramps_id(), state, state.source) self.dbase.commit_source(state.source, self.trans, state.source.change) @@ -6269,7 +6269,7 @@ class GedcomParser(UpdateCallback): if line.data and line.data[0] == '@': # Reference to a named multimedia object defined elsewhere gramps_id = self.oid_map[line.data] - + handle = self.__find_object_handle(gramps_id) ref = MediaRef() ref.set_reference_handle(handle) @@ -6348,7 +6348,7 @@ class GedcomParser(UpdateCallback): self.repo2id[line.data] = repo.get_gramps_id() repo.set_name(line.data) self.dbase.commit_repository(repo, self.trans) - + repo_ref = RepoRef() repo_ref.set_reference_handle(repo.handle) @@ -6373,7 +6373,7 @@ class GedcomParser(UpdateCallback): def __repo_ref_medi(self, line, state): name = line.data - mtype = MEDIA_MAP.get(name.lower(), + mtype = MEDIA_MAP.get(name.lower(), (SourceMediaType.CUSTOM, name)) state.repo_ref.set_media_type(mtype) @@ -6498,7 +6498,7 @@ class GedcomParser(UpdateCallback): # Add a default tag if provided self.__add_default_tag(media) - self.__check_msgs(_("OBJE (multi-media object) Gramps ID %s") % + self.__check_msgs(_("OBJE (multi-media object) Gramps ID %s") % media.get_gramps_id(), state, media) # commit the person to the database self.dbase.commit_media_object(media, self.trans, media.change) @@ -6531,7 +6531,7 @@ class GedcomParser(UpdateCallback): path = filename[0].replace('\\', os.path.sep) else: path = line.data - + state.media.set_path(path) state.media.set_mime_type(get_type(path)) if not state.media.get_description(): @@ -6679,7 +6679,7 @@ class GedcomParser(UpdateCallback): state.level = 1 self.__parse_level(state, self.repo_parse_tbl, self.__ignore) - self.__check_msgs(_("REPO (repository) Gramps ID %s") % + self.__check_msgs(_("REPO (repository) Gramps ID %s") % repo.get_gramps_id(), state, repo) self.dbase.commit_repository(repo, self.trans, repo.change) @@ -6704,8 +6704,8 @@ class GedcomParser(UpdateCallback): def __repo_addr(self, line, state): """ Parses the REPOsitory and HEADer COPR - - n ADDR {0:1} + + n ADDR {0:1} +1 CONT {0:M} +1 ADR1 {0:1} (Street) +1 ADR2 {0:1} (Locality) @@ -6715,7 +6715,7 @@ class GedcomParser(UpdateCallback): +1 CTRY {0:1} n PHON {0:3} - Some repositories do not try to break up the address, + Some repositories do not try to break up the address, instead they put everything on a single line. Try to determine if this happened, and try to fix it. """ @@ -6726,7 +6726,7 @@ class GedcomParser(UpdateCallback): self.__parse_level(sub_state, self.parse_addr_tbl, self.__ignore) state.msg += sub_state.msg - + self.__merge_address(free_form, sub_state.addr, line, state) state.repo.add_address(sub_state.addr) @@ -6875,7 +6875,7 @@ class GedcomParser(UpdateCallback): def __parse_header(self): """ Handling of the lines subordinate to the HEAD GEDCOM tag - + n HEAD {1:1} +1 SOUR {1:1} +2 VERS {0:1} @@ -6906,7 +6906,7 @@ class GedcomParser(UpdateCallback): * NOTE: Submissions to the Family History Department for Ancestral File submission or for clearing temple ordinances must use a DESTination of ANSTFILE or TempleReady. - + """ state = CurrentState(level=1) self.__parse_level(state, self.head_parse_tbl, self.__undefined) @@ -6926,7 +6926,7 @@ class GedcomParser(UpdateCallback): # Book/RootsMagic-for-PAF-Users-Printable.pdf) use the Addr fields for # 'Place Details (address, hospital, cemetary)' if line.data.strip().lower() in ['rootsmagic']: - self.addr_is_detail = True + self.addr_is_detail = True # We will use the approved system ID as the name of the generating # software, in case we do not get the name in the proper place self.genby = line.data @@ -6963,7 +6963,7 @@ class GedcomParser(UpdateCallback): sattr.set_type(_("Name of software product")) sattr.set_value(self.genby) self.def_src.add_attribute(sattr) - + def __header_sour_vers(self, line, state): """ @param line: The current line in GedLine format @@ -6977,7 +6977,7 @@ class GedcomParser(UpdateCallback): sattr.set_type(_("Version number of software product")) sattr.set_value(self.genvers) self.def_src.add_attribute(sattr) - + def __header_sour_corp(self, line, state): """ @param line: The current line in GedLine format @@ -6992,7 +6992,7 @@ class GedcomParser(UpdateCallback): state.msg += sub_state.msg if self.use_def_src: - repo.set_name(_("Business that produced the product: %s") % + repo.set_name(_("Business that produced the product: %s") % line.data) rtype = RepositoryType() rtype.set((RepositoryType.CUSTOM, _('GEDCOM data'))) @@ -7004,7 +7004,7 @@ class GedcomParser(UpdateCallback): mtype.set((SourceMediaType.UNKNOWN, '')) repo_ref.set_media_type(mtype) self.def_src.add_repo_reference(repo_ref) - + def __header_sour_data(self, line, state): """ @param line: The current line in GedLine format @@ -7021,7 +7021,7 @@ class GedcomParser(UpdateCallback): self.__parse_level(sub_state, self.header_sour_data, self.__undefined) state.msg += sub_state.msg - + def __header_sour_copr(self, line, state): """ @param line: The current line in GedLine format @@ -7051,7 +7051,7 @@ class GedcomParser(UpdateCallback): sattr.set_type(_("Publication date of source data")) sattr.set_value(text_date) self.def_src.add_attribute(sattr) - + def __header_file(self, line, state): """ @param line: The current line in GedLine format @@ -7080,10 +7080,10 @@ class GedcomParser(UpdateCallback): @type line: GedLine @param state: The current state @type state: CurrentState - + +1 SUBM @@ {1:1} - This should be simply be a cross-reference to the correct Submitter - record. Note that there can be multiple Submitter records, so it is + This should be simply be a cross-reference to the correct Submitter + record. Note that there can be multiple Submitter records, so it is necessary to remember which one should be applied. """ @@ -7145,7 +7145,7 @@ class GedcomParser(UpdateCallback): % {'filename': fname, 'by': self.genby}, _("Look for nameless events.") ) - + def __header_char(self, line, state): """ @param line: The current line in GedLine format @@ -7163,7 +7163,7 @@ class GedcomParser(UpdateCallback): break elif line.token == TOKEN_VERS: version = line.data - + if self.use_def_src: if version == "": sattr = SrcAttribute() @@ -7189,7 +7189,7 @@ class GedcomParser(UpdateCallback): break elif line.token == TOKEN_VERS: if line.data[0] != "5": - self.__add_msg(_("GEDCOM version not supported"), + self.__add_msg(_("GEDCOM version not supported"), line, state) if self.use_def_src: sattr = SrcAttribute() @@ -7209,7 +7209,7 @@ class GedcomParser(UpdateCallback): sattr.set_type(_('GEDCOM form')) sattr.set_value(line.data) self.def_src.add_attribute(sattr) - + def __header_plac(self, line, state): """ @param line: The current line in GedLine format @@ -7236,9 +7236,9 @@ class GedcomParser(UpdateCallback): @type line: GedLine @param state: The current state @type state: CurrentState - + This processes the , i.e. the date when this [GEDCOM] - transmission was created (as opposed to the date when the source data + transmission was created (as opposed to the date when the source data that was used to create the transmission was published or created """ # Because there is a DATE tag, line.data is automatically converted to a @@ -7251,7 +7251,7 @@ class GedcomParser(UpdateCallback): pass elif line.token == TOKEN_TIME: tx_time = str(line.data) - + if self.use_def_src: if tx_time == "": sattr = SrcAttribute() @@ -7263,7 +7263,7 @@ class GedcomParser(UpdateCallback): sattr.set_type(_('Creation date and time of GEDCOM')) sattr.set_value("%s %s" % (tx_date, tx_time)) self.def_src.add_attribute(sattr) - + def __header_note(self, line, state): """ @param line: The current line in GedLine format @@ -7307,7 +7307,7 @@ class GedcomParser(UpdateCallback): sub_state = CurrentState(level=state.level+1) sub_state.note = new_note - self.__parse_level(sub_state, self.note_parse_tbl, + self.__parse_level(sub_state, self.note_parse_tbl, self.__undefined) state.msg += sub_state.msg @@ -7326,7 +7326,7 @@ class GedcomParser(UpdateCallback): def __parse_inline_note(self, line, level): """ Handling of lines subordinate to the NOTE GEDCOM tag - + n @@ NOTE {1:1} +1 [ CONC | CONT] {0:M} +1 <> {0:M} @@ -7353,13 +7353,13 @@ class GedcomParser(UpdateCallback): state.msg += sub_state.msg self.dbase.commit_note(new_note, self.trans, new_note.change) - self.__check_msgs(_("NOTE Gramps ID %s") % new_note.get_gramps_id(), + self.__check_msgs(_("NOTE Gramps ID %s") % new_note.get_gramps_id(), state, None) def __note_chan(self, line, state): if state.note: self.__parse_change(line, state.note, state.level+1, state) - + def __parse_source_reference(self, citation, level, handle, state): """ Read the data associated with a SOUR reference. @@ -7369,7 +7369,7 @@ class GedcomParser(UpdateCallback): sub_state.handle = handle self.__parse_level(sub_state, self.citation_parse_tbl, self.__ignore) state.msg += sub_state.msg - + def __parse_header_head(self): """ Validate that this is a valid GEDCOM file. @@ -7377,17 +7377,17 @@ class GedcomParser(UpdateCallback): line = self.__get_next_line() if line.token != TOKEN_HEAD: raise GedcomError("%s is not a GEDCOM file" % self.filename) - + def __parse_submission(self, line, state): """ @param line: The current line in GedLine format @type line: GedLine @param state: The current state @type state: CurrentState - - Handling of lines subordinate to the level 0 SUMN (Submission) GEDCOM + + Handling of lines subordinate to the level 0 SUMN (Submission) GEDCOM tag - + n @@ SUBN {1:1] +1 SUBM @@ {0:1} +1 FAMF {0:1} @@ -7417,14 +7417,14 @@ class GedcomParser(UpdateCallback): else: self.__not_recognized(line, state.level+1, state) continue - + if self.use_def_src and msg != "": sattr = SrcAttribute() sattr.set_type(msg) sattr.set_value(line.data) self.def_src.add_attribute(sattr) self.dbase.commit_source(self.def_src, self.trans) - + def handle_source(self, line, level, state): """ Handle the specified source, building a source reference to @@ -7472,7 +7472,7 @@ class GedcomParser(UpdateCallback): """ tstr = None dstr = None - dobj = None + dobj = None while True: line = self.__get_next_line() if self.__level_is_finished(line, level): @@ -7512,7 +7512,7 @@ class GedcomParser(UpdateCallback): # library; for Unix, it is typically in 2038." If the time is # too far in the future, this gives OverflowError. pass - + def build_media_object(self, obj, form, filename, title, note): if isinstance(form, str) and form.lower() == "url": url = Url() @@ -7584,13 +7584,13 @@ class GedcomParser(UpdateCallback): state.msg += sub_state.msg self.__add_place(event, sub_state) - + self.dbase.commit_event(event, self.trans) event_ref.set_reference_handle(event.handle) return event_ref - def __build_family_event_pair(self, state, event_type, event_map, + def __build_family_event_pair(self, state, event_type, event_map, description): event = Event() event_ref = EventRef() @@ -7612,7 +7612,7 @@ class GedcomParser(UpdateCallback): state.msg += sub_state.msg self.__add_place(event, sub_state) - + self.dbase.commit_event(event, self.trans) event_ref.set_reference_handle(event.handle) return event_ref @@ -7623,14 +7623,14 @@ class GedcomParser(UpdateCallback): return code elif TEMPLES.is_valid_name(code): return TEMPLES.code(code) - + code = get_code(line.data) - if code: + if code: return code - + ## Not sure why we do this. Kind of ugly. code = get_code(line.data.split()[0]) - if code: + if code: return code ## Okay we have no clue which temple this is. @@ -7672,7 +7672,7 @@ class GedcomParser(UpdateCallback): @type state: CurrentState """ free_form = line.data - + sub_state = CurrentState(level=state.level + 1) sub_state.location = state.res @@ -7720,14 +7720,14 @@ class GedcomStageOne(object): 1. Character set encoding 2. Number of people and families in the list - 3. Child to family references, since Ancestry.com creates GEDCOM files + 3. Child to family references, since Ancestry.com creates GEDCOM files without the FAMC references. """ __BAD_UTF16 = _("Your GEDCOM file is corrupted. " "The file appears to be encoded using the UTF16 " "character set, but is missing the BOM marker.") __EMPTY_GED = _("Your GEDCOM file is empty.") - + @staticmethod def __is_xref_value(value): """ @@ -7735,7 +7735,7 @@ class GedcomStageOne(object): if we have a leading '@' character, then we are okay. """ return value and value[0] == '@' - + def __init__(self, ifile): self.ifile = ifile self.famc = defaultdict(list) @@ -7746,7 +7746,7 @@ class GedcomStageOne(object): def __detect_file_decoder(self, input_file): """ - Detects the file encoding of the file by looking for a BOM + Detects the file encoding of the file by looking for a BOM (byte order marker) in the GEDCOM file. If we detect a UTF-16 encoded file, we must connect to a wrapper using the codecs package. @@ -7773,7 +7773,7 @@ class GedcomStageOne(object): Parse the input file. """ current_family_id = "" - + reader = self.__detect_file_decoder(self.ifile) for line in reader: diff --git a/gramps/plugins/lib/libgrampsxml.py b/gramps/plugins/lib/libgrampsxml.py index 1b9928a44..a184ba74c 100644 --- a/gramps/plugins/lib/libgrampsxml.py +++ b/gramps/plugins/lib/libgrampsxml.py @@ -7,7 +7,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. diff --git a/gramps/plugins/lib/libholiday.py b/gramps/plugins/lib/libholiday.py index 3ab5d46dc..567f300be 100644 --- a/gramps/plugins/lib/libholiday.py +++ b/gramps/plugins/lib/libholiday.py @@ -142,37 +142,37 @@ def dow(y, m, d): # #------------------------------------------------------------------------ class HolidayTable(object): - """ - HolidayTable is a class which provides holidays for various + """ + HolidayTable is a class which provides holidays for various countries and years. """ __holiday_files = [] __countries = [] def __init__(self): - """ - Find the holiday files and load the countries if it has not already + """ + Find the holiday files and load the countries if it has not already been done. - """ + """ if( not HolidayTable.__holiday_files ): self.__find_holiday_files() - + if( not HolidayTable.__countries ): self.__build_country_list() # Initialize the holiday table to be empty self.__holidays = {} - self.__init_table() - + self.__init_table() + def __find_holiday_files(self): """ - Looks in multiple places for holidays.xml files + Looks in multiple places for holidays.xml files It will search for the file in user;s plugin directories first, then it will search in program's plugins directories. """ holiday_file = 'holidays.xml' - + # Look for holiday files in the user plugins directory and all # subdirectories. for (dirpath, dirnames, filenames) in os.walk(USER_PLUGINS): @@ -186,7 +186,7 @@ class HolidayTable(object): holiday_full_path = os.path.join(dirpath, holiday_file) if os.path.exists(holiday_full_path): HolidayTable.__holiday_files.append(holiday_full_path) - + def __build_country_list(self): """ Generate the list of countries that have holiday information. """ for holiday_file_path in HolidayTable.__holiday_files: @@ -197,27 +197,27 @@ class HolidayTable(object): country_name = country_element.get_attribute("name") if country_name not in HolidayTable.__countries: HolidayTable.__countries.append(_(country_name)) - + def __init_table(self): """ Initialize the holiday table structure. """ for month in range(1, 13): self.__holidays[month] = {} for day in range(1, 32): - self.__holidays[month][day] = [] + self.__holidays[month][day] = [] def get_countries(self): - """ + """ Get all the country names that holidays are available for. - + @return: nothing """ return HolidayTable.__countries def load_holidays(self, year, country): - """ - Load the holiday table for the specified year and country. + """ + Load the holiday table for the specified year and country. This must be called before get_holidays(). - + @param year: The year for which the holidays should be loaded. Example: 2010 @type year: int @@ -229,7 +229,7 @@ class HolidayTable(object): self.__init_table() for holiday_file_path in HolidayTable.__holiday_files: parser = _Xml2Obj() - element = parser.parse(holiday_file_path) + element = parser.parse(holiday_file_path) calendar = _Holidays(element, country) date = datetime.date(year, 1, 1) while date.year == year: @@ -237,11 +237,11 @@ class HolidayTable(object): for text in holidays: self.__holidays[date.month][date.day].append(_(text)) date = date.fromordinal(date.toordinal() + 1) - + def get_holidays(self, month, day): - """ + """ Get the holidays for the given day of the year. - + @param month: The month for the requested holidays. Example: 1 @type month: int @@ -268,23 +268,23 @@ class _Element: self.__attributes = attributes # The element's child element list (sequence) self.__children = [] - + def add_child(self, element): 'Add a reference to a child element' self.__children.append(element) - + def get_attribute(self, key): 'Get an attribute value' return self.__attributes.get(key) - + def get_attributes(self): 'Get all the attributes' return self.__attributes - + def get_name(self): """ Get the name of this element. """ return self.__name - + def get_children(self): """ Get the children elements for this element. """ return self.__children @@ -299,7 +299,7 @@ class _Xml2Obj: def __init__(self): self.root = None self.nodeStack = [] - + def start_element(self, name, attributes): 'SAX start element even handler' # Instantiate an Element object @@ -311,7 +311,7 @@ class _Xml2Obj: else: self.root = element self.nodeStack.append(element) - + def end_element(self, name): 'SAX end element event handler' self.nodeStack = self.nodeStack[:-1] @@ -333,7 +333,7 @@ class _Xml2Obj: #------------------------------------------------------------------------ class _Holidays: """ Class used to read XML holidays to add to calendar. """ - MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', + MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] WORKDAY = list(range(5)) # indexes into above @@ -344,13 +344,13 @@ class _Holidays: self.country = country self.dates = [] self.initialize() - + def set_country(self, country): """ Set the contry of holidays to read """ self.country = country self.dates = [] self.initialize() - + def initialize(self): """ Parse the holiday date XML items """ for country_set in self.elements.get_children(): @@ -358,21 +358,21 @@ class _Holidays: _(country_set.get_attribute("name")) == self.country: for date in country_set.get_children(): if date.get_name() == "date": - data = {"value" : "", - "name" : "", - "offset": "", - "type": "", + data = {"value" : "", + "name" : "", + "offset": "", + "type": "", "if": "", } # defaults for attr in date.get_attributes(): data[attr] = date.get_attribute(attr) self.dates.append(data) - + def get_daynames(self, year, month, dayname): """ Get the items for a particular year/month and day of week """ - if self.debug: + if self.debug: print("%s's in %d %d..." % (dayname, month, year)) - + retval = [0] day_of_week = self.DAYS.index(dayname) for day in range(1, 32): @@ -382,20 +382,20 @@ class _Holidays: continue if date.weekday() == day_of_week: retval.append(day) - - if self.debug: + + if self.debug: print("day_of_week=", day_of_week, "days=", retval) - + return retval - + def check_date(self, date): """ Return items that match rules """ retval = [] for rule in self.dates: - - if self.debug: + + if self.debug: print("Checking ", rule["name"], "...") - + offset = 0 if rule["offset"] != "": if rule["offset"].isdigit(): @@ -412,7 +412,7 @@ class _Holidays: y, m, d = date.year, date.month, date.day rule["value"] = eval(rule["value"][1:]) - if self.debug: + if self.debug: print("rule['value']:", rule["value"]) if rule["value"].count("/") == 3: # year/num/day/month, "3rd wednesday in april" y, num, dayname, mon = rule["value"].split("/") @@ -427,12 +427,12 @@ class _Holidays: elif mon in self.MONTHS: m = self.MONTHS.index(mon) + 1 dates_of_dayname = self.get_daynames(y, m, dayname) - - if self.debug: + + if self.debug: print("num =", num) - + d = dates_of_dayname[int(num)] - + elif rule["value"].count("/") == 2: # year/month/day y, m, d = rule["value"].split("/") if y == "*": @@ -450,10 +450,10 @@ class _Holidays: else: d = int(d) ndate = datetime.date(y, m, d) - - if self.debug: + + if self.debug: print(ndate, offset, type(offset)) - + if isinstance(offset, int): if offset != 0: ndate = ndate.fromordinal(ndate.toordinal() + offset) @@ -488,9 +488,9 @@ class _Holidays: ordinal += direction ndate = ndate.fromordinal(ordinal) - if self.debug: + if self.debug: print("ndate:", ndate, "date:", date) - + if ndate == date: if rule["if"] != "": if not eval(rule["if"]): diff --git a/gramps/plugins/lib/libhtml.py b/gramps/plugins/lib/libhtml.py index a3933b312..edb7b6676 100644 --- a/gramps/plugins/lib/libhtml.py +++ b/gramps/plugins/lib/libhtml.py @@ -70,7 +70,7 @@ _HTML5 = "" #------------------------------------------------------------------------ # -# XML Namespace constant for use in tags +# XML Namespace constant for use in tags # #------------------------------------------------------------------------ @@ -85,15 +85,15 @@ _XMLNS = "http://www.w3.org/1999/xhtml" # Set of html tags that do not use a complementary closing tag, but close with # /> instead _START_CLOSE = set([ - 'area', - 'base', - 'br', - 'frame', + 'area', + 'base', + 'br', + 'frame', 'hr', - 'img', - 'input', - 'link', - 'meta', + 'img', + 'input', + 'link', + 'meta', 'param' ]) @@ -137,16 +137,16 @@ class Html(list): :type public: string :param public: class of this DOCTYPE. Defaults to 'PUBLIC :type external_id: string - :param external_id: external identifier of this DOCTYPE. + :param external_id: external identifier of this DOCTYPE. Defaults to XHTML 1.0 STRICT :type args: object - :param args: 0 or more positional parameters to be added to this + :param args: 0 or more positional parameters to be added to this DOCTYPE. """ return ( '' @@ -162,7 +162,7 @@ class Html(list): :param lang: language to be used. Defaul = 'en' :rtype: reference to new Html instance :returns: reference to the newly-created Html instances for object - """ + """ return Html('html', indent=False, xmlns=xmlns, @@ -174,9 +174,9 @@ class Html(list): def head(title=None, encoding='utf-8', html5=True, *args, **keywargs): """ Build and return a properly-formated object - + :type title: string or None - :param title: title for HTML page. Default=None. If None no + :param title: title for HTML page. Default=None. If None no title tag is written :type encoding: string :param encoding: encoding to be used. Default = 'utf-8' @@ -184,10 +184,10 @@ class Html(list): if pre-html5 syntax required :rtype: reference to new Html instance :returns: reference to the newly-created Html instances for object - """ + """ - head = Html('head', *args, **keywargs) - if title is not None: + head = Html('head', *args, **keywargs) + if title is not None: head += (Html('title', title, inline=True, indent=True)) if html5: head += Html('meta', charset=encoding, indent=True) @@ -202,7 +202,7 @@ class Html(list): def page(title=None, encoding='utf-8', lang='en', html5=True, *args, **keywargs): """ This function prepares a new Html class based page and returns - + :type title: string :param title: title for HTML page. Default=None :type encoding: string @@ -227,7 +227,7 @@ class Html(list): lang=lang, html5=html5, indent=False, - *args, **keywargs + *args, **keywargs ) # body = Html('body', indent=False, *args, **keywargs) @@ -237,7 +237,7 @@ class Html(list): def __init__(self, tag='html', *args, **keywargs): """ Class Constructor: Returns a new instance of the Html class - + :type tag: string :param tag: The HTML tag. Default is 'html' :type args: optional positional parameters @@ -266,7 +266,7 @@ class Html(list): attributes :rtype: object reference :returns: reference to the newly-created Html instance - + For full usage of the Html class with examples, please see the wiki page at: http://www.gramps-project.org/wiki/index.php?title=Libhtml """ @@ -277,8 +277,8 @@ class Html(list): self.indent, self.close, self.inline = True, True, False # # Handle keyword arguments passed to this constructor. -# Keywords that we process directly are handled. -# Keywords we don't recognize are saved for later +# Keywords that we process directly are handled. +# Keywords we don't recognize are saved for later # addition to the opening tag as attributes. # for keyw, arg in keywargs.items(): @@ -295,7 +295,7 @@ class Html(list): if tag[0] == '<': # if caller provided preformatted tag? self[0:] = [tag] # add it in self.close = None # caller must close the tag - else: + else: if tag in _START_CLOSE: # if tag in special list self.close = False # it needs no closing tag begin = '<%s%s%s>' % ( # build opening tag with attributes @@ -402,7 +402,7 @@ class Html(list): """ if self.indent is None: tabs = '' - elif self.indent: + elif self.indent: tabs += indent if self.inline: # if inline, write all list and method(str('%s%s' % (tabs, self))) # nested list elements @@ -440,10 +440,10 @@ class Html(list): :type name: string :param name: name of this DOCTYPE. Defaults to "html" :type external_id: string - :param external_id: external identifier of this DOCTYPE. + :param external_id: external identifier of this DOCTYPE. Defaults to XHTML 1.0 STRICT :type args: object - :param args: 0 or more positional parameters to be added to this + :param args: 0 or more positional parameters to be added to this DOCTYPE. """ doctype = ( @@ -478,9 +478,9 @@ class Html(list): :param name: new HTML tag """ curtag = self.tag - + # Replace closing tag, if any - + if self[-1] == '' % curtag: self[-1] = '' % newtag @@ -509,9 +509,9 @@ class Html(list): beg = len(self.tag) + 1 # See if self-closed or normal - + end = -2 if self.close is False else -1 - self[0] = self[0][:beg] + ' ' + value + self[0][end:] + self[0] = self[0][:beg] + ' ' + value + self[0][end:] # def __delattr(self): """ @@ -520,7 +520,7 @@ class Html(list): self[0] = '<' + self.tag + ( # Set correct closing delimiter(s) - + ' />' if self.close is False else '>' ) # @@ -531,7 +531,7 @@ class Html(list): Returns list of items between opening and closing tags :rtype: list - :returns: list of items between opening and closing HTML tags + :returns: list of items between opening and closing HTML tags """ return self[1:-1] # @@ -582,4 +582,4 @@ def htmltest(): if __name__ == '__main__': from libhtmltest import htmltest - htmltest() + htmltest() diff --git a/gramps/plugins/lib/libhtmlbackend.py b/gramps/plugins/lib/libhtmlbackend.py index cd53e22f8..f237693f6 100644 --- a/gramps/plugins/lib/libhtmlbackend.py +++ b/gramps/plugins/lib/libhtmlbackend.py @@ -18,7 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -"""Html and Html format management for the different reports +"""Html and Html format management for the different reports """ #------------------------------------------------------------------------ @@ -59,13 +59,13 @@ def process_spaces(intext, format): Function to process spaces in text lines for pre-formatted notes. line : text to process format : = 0 : Flowed, = 1 : Preformatted - + If the text is pre-formatted (format==1), then leading spaces (after ignoring XML) are replaced by alternating non-breaking spaces and ordinary spaces. After the first non-space character, single spaces are left but multiple spaces are replaced by alternating NBSP and space If the text is flowed, the text is unchanged. - + Returns the processed text, and the number of significant (i.e. non-xml non-white-space) chars. """ @@ -74,7 +74,7 @@ def process_spaces(intext, format): NBSP=3 XML=4 SPACEHOLD=5 - + sigcount = 0 state = NORMAL outtext = "" @@ -129,7 +129,7 @@ def process_spaces(intext, format): outtext += " "+char sigcount += 1 state = NORMAL - + else: # format == 0 flowed for char in intext: @@ -159,7 +159,7 @@ class HtmlBackend(DocBackend): Contrary to other backends, we do not write to file but to a Html object instead, writing out the file on close. """ - + STYLETAG_TO_PROPERTY = { DocBackend.FONTCOLOR : 'color:%s;', DocBackend.HIGHLIGHT : 'background-color:%s;', @@ -176,18 +176,18 @@ class HtmlBackend(DocBackend): DocBackend.FONTSIZE, DocBackend.FONTCOLOR, DocBackend.HIGHLIGHT, - DocBackend.SUPERSCRIPT, + DocBackend.SUPERSCRIPT, DocBackend.LINK, ] STYLETAG_MARKUP = { DocBackend.BOLD : ("", ""), DocBackend.ITALIC : ("", ""), - DocBackend.UNDERLINE : ('', + DocBackend.UNDERLINE : ('', ""), DocBackend.SUPERSCRIPT : ("", ""), } - + ESCAPE_FUNC = lambda self: escape def __init__(self, filename=None): @@ -201,7 +201,7 @@ class HtmlBackend(DocBackend): self._subdir = None self.title = None self.build_link = None - + def _create_xmltag(self, tagtype, value): """ overwrites the method in DocBackend @@ -218,7 +218,7 @@ class HtmlBackend(DocBackend): #fonts can have strange symbols in them, ' needs to be escaped value = value.replace("'", "\\'") if value else "" return ('' % (self.STYLETAG_TO_PROPERTY[tagtype] % - (value)), + (value)), '') def _checkfilename(self): @@ -226,7 +226,7 @@ class HtmlBackend(DocBackend): Check to make sure filename satisfies the standards for this filetype """ fparts = os.path.basename(self._filename).split('.') - if not len(fparts) >= 2 and not (fparts[-1] == 'html' or + if not len(fparts) >= 2 and not (fparts[-1] == 'html' or fparts[-1] == 'htm' or fparts[-1] == 'php'): self._filename = self._filename + ".htm" fparts = os.path.basename(self._filename).split('.') @@ -252,7 +252,7 @@ class HtmlBackend(DocBackend): except: raise ReportError(_("Could not create %s") % self._filename) - if not os.path.isdir(self.datadirfull()): + if not os.path.isdir(self.datadirfull()): try: os.mkdir(self.datadirfull()) except IOError as msg: @@ -274,20 +274,20 @@ class HtmlBackend(DocBackend): """ write to the html page. One can pass a html object, or a string """ self.html_body += obj - + def close(self): """ write out the html to the page """ self.html_page.write(self.__write, indent=' ') DocBackend.close(self) - + def datadir(self): """ the directory where to save extra files """ return self._subdir - + def datadirfull(self): """ full path of the datadir directory @@ -309,6 +309,6 @@ class HtmlBackend(DocBackend): return self.STYLETAG_MARKUP[DocBackend.UNDERLINE] else: return self.STYLETAG_MARKUP[DocBackend.UNDERLINE] - return ('' % self.ESCAPE_FUNC()(value), + return ('' % self.ESCAPE_FUNC()(value), '') - + diff --git a/gramps/plugins/lib/libmapservice.py b/gramps/plugins/lib/libmapservice.py index ac83eb174..0a497ed0e 100644 --- a/gramps/plugins/lib/libmapservice.py +++ b/gramps/plugins/lib/libmapservice.py @@ -39,7 +39,7 @@ from gramps.gui.display import display_url class MapService(): """Generic base class for map services A service is a singleton, we only need one to exist - Usage is as a callable when used + Usage is as a callable when used """ def __init__(self): self.database = None @@ -49,7 +49,7 @@ class MapService(): def __call__(self, database, items): """Callable class, usable as a function. This guarantees the class is instantiated once when a service is registered. Afterward only calls - occur + occur database: Database to work on items: list of tuples (place_handle, description), where description is None or a string to use for marker (eg 'birth John Doe') @@ -65,10 +65,10 @@ class MapService(): def _get_first_place(self): """Obtain the first place object""" place_handle = self.items[0][0] - + return self.database.get_place_from_handle(place_handle), \ self.items[0][1] - + def _all_places(self): """Obtain a list generator of all place objects Usage as an iterator: @@ -76,12 +76,12 @@ class MapService(): """ for handle, descr in self.items: yield self.database.get_place_from_handle(handle), descr - + def _lat_lon(self, place, format="D.D8"): """return the lat, lon value of place in the requested format None, None if invalid """ - return conv_lat_lon(place.get_latitude(), + return conv_lat_lon(place.get_latitude(), place.get_longitude(), format) def calc_url(self): @@ -92,7 +92,7 @@ class MapService(): """Show the url in an external browser""" if self.url: display_url(self.url) - + def _free(self): """Allow garbage collection to do it's work""" self.items = None diff --git a/gramps/plugins/lib/libmetadata.py b/gramps/plugins/lib/libmetadata.py index 2ff3d5b09..ab47a8754 100644 --- a/gramps/plugins/lib/libmetadata.py +++ b/gramps/plugins/lib/libmetadata.py @@ -101,7 +101,7 @@ CAMERA = _('Camera') GPS = _('GPS') ADVANCED = _('Advanced') -TAGS = [(DESCRIPTION, 'Exif.Image.ImageDescription', None, None), +TAGS = [(DESCRIPTION, 'Exif.Image.ImageDescription', None, None), (DESCRIPTION, 'Exif.Image.Artist', None, None), (DESCRIPTION, 'Exif.Image.Copyright', None, None), (DESCRIPTION, 'Exif.Photo.DateTimeOriginal', None, format_datetime), @@ -113,7 +113,7 @@ TAGS = [(DESCRIPTION, 'Exif.Image.ImageDescription', None, None), (DESCRIPTION, 'Exif.Image.XPKeywords', None, None), (DESCRIPTION, 'Exif.Image.Rating', None, None), (IMAGE, 'Exif.Image.DocumentName', None, None), - (IMAGE, 'Exif.Photo.PixelXDimension', None, None), + (IMAGE, 'Exif.Photo.PixelXDimension', None, None), (IMAGE, 'Exif.Photo.PixelYDimension', None, None), (IMAGE, 'Exif.Image.XResolution', 'Exif.Image.ResolutionUnit', None), (IMAGE, 'Exif.Image.YResolution', 'Exif.Image.ResolutionUnit', None), @@ -124,15 +124,15 @@ TAGS = [(DESCRIPTION, 'Exif.Image.ImageDescription', None, None), (IMAGE, 'Exif.Image.Compression', None, None), (IMAGE, 'Exif.Photo.CompressedBitsPerPixel', None, None), (IMAGE, 'Exif.Image.PhotometricInterpretation', None, None), - (CAMERA, 'Exif.Image.Make', None, None), - (CAMERA, 'Exif.Image.Model', None, None), - (CAMERA, 'Exif.Photo.FNumber', None, None), - (CAMERA, 'Exif.Photo.ExposureTime', None, None), - (CAMERA, 'Exif.Photo.ISOSpeedRatings', None, None), + (CAMERA, 'Exif.Image.Make', None, None), + (CAMERA, 'Exif.Image.Model', None, None), + (CAMERA, 'Exif.Photo.FNumber', None, None), + (CAMERA, 'Exif.Photo.ExposureTime', None, None), + (CAMERA, 'Exif.Photo.ISOSpeedRatings', None, None), (CAMERA, 'Exif.Photo.FocalLength', None, None), (CAMERA, 'Exif.Photo.FocalLengthIn35mmFilm', None, None), - (CAMERA, 'Exif.Photo.MaxApertureValue', None, None), - (CAMERA, 'Exif.Photo.MeteringMode', None, None), + (CAMERA, 'Exif.Photo.MaxApertureValue', None, None), + (CAMERA, 'Exif.Photo.MeteringMode', None, None), (CAMERA, 'Exif.Photo.ExposureProgram', None, None), (CAMERA, 'Exif.Photo.ExposureBiasValue', None, None), (CAMERA, 'Exif.Photo.Flash', None, None), @@ -146,7 +146,7 @@ TAGS = [(DESCRIPTION, 'Exif.Image.ImageDescription', None, None), (CAMERA, 'Exif.Photo.WhiteBalance', None, None), (CAMERA, 'Exif.Photo.DigitalZoomRatio', None, None), (GPS, 'Exif.GPSInfo.GPSLatitude', - 'Exif.GPSInfo.GPSLatitudeRef', format_gps), + 'Exif.GPSInfo.GPSLatitudeRef', format_gps), (GPS, 'Exif.GPSInfo.GPSLongitude', 'Exif.GPSInfo.GPSLongitudeRef', format_gps), (GPS, 'Exif.GPSInfo.GPSAltitude', @@ -167,7 +167,7 @@ class MetadataView(Gtk.TreeView): def __init__(self): Gtk.TreeView.__init__(self) self.sections = {} - titles = [(_('Key'), 1, 235), + titles = [(_('Key'), 1, 235), (_('Value'), 2, 325)] self.model = ListModel(self, titles, list_mode="tree") diff --git a/gramps/plugins/lib/libmixin.py b/gramps/plugins/lib/libmixin.py index 21e2ffe5b..684326cac 100644 --- a/gramps/plugins/lib/libmixin.py +++ b/gramps/plugins/lib/libmixin.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -27,7 +27,7 @@ Mixin for DbDir to enable find_from_handle and check_from_handle methods. # Gramps Modules # #------------------------------------------------------------------------------ -from gramps.gen.lib import (Person, Family, Event, Place, Source, +from gramps.gen.lib import (Person, Family, Event, Place, Source, MediaObject, Repository, Note, Tag) #------------------------------------------------------------------------------ @@ -54,9 +54,9 @@ class DbMixin(object): """ Find a primary object of class_type in the database from the passed handle. - + If no object exists, a new object is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple @@ -80,9 +80,9 @@ class DbMixin(object): """ Find a table object of class_type in the database from the passed handle. - + If no object exists, a new object is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple @@ -103,7 +103,7 @@ class DbMixin(object): """ Check whether a primary object of class_type with the passed handle exists in the database. - + If no such object exists, a new object is added to the database. If set_gid then a new gramps_id is created, if not, None is used. """ @@ -118,7 +118,7 @@ class DbMixin(object): """ Check whether a table object of class_type with the passed handle exists in the database. - + If no such object exists, a new object is added to the database. """ handle = str(handle) @@ -130,48 +130,48 @@ class DbMixin(object): def find_person_from_handle(self, handle, transaction): """ Find a Person in the database from the passed handle. - + If no such Person exists, a new Person is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple """ - return self.__find_primary_from_handle(handle, transaction, Person, + return self.__find_primary_from_handle(handle, transaction, Person, self.get_raw_person_data, self.add_person) def find_source_from_handle(self, handle, transaction): """ Find a Source in the database from the passed handle. - + If no such Source exists, a new Source is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple """ - return self.__find_primary_from_handle(handle, transaction, Source, + return self.__find_primary_from_handle(handle, transaction, Source, self.get_raw_source_data, self.add_source) def find_event_from_handle(self, handle, transaction): """ Find a Event in the database from the passed handle. - + If no such Event exists, a new Event is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple """ - return self.__find_primary_from_handle(handle, transaction, Event, + return self.__find_primary_from_handle(handle, transaction, Event, self.get_raw_event_data, self.add_event) def find_object_from_handle(self, handle, transaction): """ Find a MediaObject in the database from the passed handle. - + If no such MediaObject exists, a new Object is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple @@ -182,164 +182,164 @@ class DbMixin(object): def find_place_from_handle(self, handle, transaction): """ Find a Place in the database from the passed handle. - + If no such Place exists, a new Place is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple """ - return self.__find_primary_from_handle(handle, transaction, Place, + return self.__find_primary_from_handle(handle, transaction, Place, self.get_raw_place_data, self.add_place) def find_family_from_handle(self, handle, transaction): """ Find a Family in the database from the passed handle. - + If no such Family exists, a new Family is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple """ - return self.__find_primary_from_handle(handle, transaction, Family, + return self.__find_primary_from_handle(handle, transaction, Family, self.get_raw_family_data, self.add_family) def find_repository_from_handle(self, handle, transaction): """ Find a Repository in the database from the passed handle. - + If no such Repository exists, a new Repository is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple """ - return self.__find_primary_from_handle(handle, transaction, Repository, + return self.__find_primary_from_handle(handle, transaction, Repository, self.get_raw_repository_data, self.add_repository) def find_note_from_handle(self, handle, transaction): """ Find a Note in the database from the passed handle. - + If no such Note exists, a new Note is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple """ - return self.__find_primary_from_handle(handle, transaction, Note, + return self.__find_primary_from_handle(handle, transaction, Note, self.get_raw_note_data, self.add_note) def find_tag_from_handle(self, handle, transaction): """ Find a Tag in the database from the passed handle. - + If no such Tag exists, a new Tag is added to the database. - + @return: Returns a tuple, first the object, second a bool which is True if the object is new @rtype: tuple """ - return self.__find_table_from_handle(handle, transaction, Tag, + return self.__find_table_from_handle(handle, transaction, Tag, self.get_raw_tag_data, self.add_tag) def check_person_from_handle(self, handle, transaction, set_gid=True): """ Check whether a Person with the passed handle exists in the database. - + If no such Person exists, a new Person is added to the database. If set_gid then a new gramps_id is created, if not, None is used. """ - self.__check_primary_from_handle(handle, transaction, Person, - self.has_person_handle, self.add_person, + self.__check_primary_from_handle(handle, transaction, Person, + self.has_person_handle, self.add_person, set_gid = set_gid) def check_source_from_handle(self, handle, transaction, set_gid=True): """ Check whether a Source with the passed handle exists in the database. - + If no such Source exists, a new Source is added to the database. If set_gid then a new gramps_id is created, if not, None is used. """ - self.__check_primary_from_handle(handle, transaction, Source, - self.has_source_handle, self.add_source, + self.__check_primary_from_handle(handle, transaction, Source, + self.has_source_handle, self.add_source, set_gid=set_gid) - + def check_event_from_handle(self, handle, transaction, set_gid=True): """ Check whether an Event with the passed handle exists in the database. - + If no such Event exists, a new Event is added to the database. If set_gid then a new gramps_id is created, if not, None is used. """ - self.__check_primary_from_handle(handle, transaction, Event, - self.has_event_handle, self.add_event, + self.__check_primary_from_handle(handle, transaction, Event, + self.has_event_handle, self.add_event, set_gid=set_gid) def check_object_from_handle(self, handle, transaction, set_gid=True): """ - Check whether a MediaObject with the passed handle exists in the - database. - + Check whether a MediaObject with the passed handle exists in the + database. + If no such MediaObject exists, a new Object is added to the database. If set_gid then a new gramps_id is created, if not, None is used. """ - self.__check_primary_from_handle(handle, transaction, MediaObject, - self.has_object_handle, self.add_object, + self.__check_primary_from_handle(handle, transaction, MediaObject, + self.has_object_handle, self.add_object, set_gid=set_gid) def check_place_from_handle(self, handle, transaction, set_gid=True): """ Check whether a Place with the passed handle exists in the database. - + If no such Place exists, a new Place is added to the database. If set_gid then a new gramps_id is created, if not, None is used. """ - self.__check_primary_from_handle(handle, transaction, Place, - self.has_place_handle, self.add_place, + self.__check_primary_from_handle(handle, transaction, Place, + self.has_place_handle, self.add_place, set_gid=set_gid) def check_family_from_handle(self, handle, transaction, set_gid=True): """ Check whether a Family with the passed handle exists in the database. - + If no such Family exists, a new Family is added to the database. If set_gid then a new gramps_id is created, if not, None is used. """ - self.__check_primary_from_handle(handle, transaction, Family, - self.has_family_handle, self.add_family, + self.__check_primary_from_handle(handle, transaction, Family, + self.has_family_handle, self.add_family, set_gid=set_gid) def check_repository_from_handle(self, handle, transaction, set_gid=True): """ Check whether a Repository with the passed handle exists in the - database. - + database. + If no such Repository exists, a new Repository is added to the database. If set_gid then a new gramps_id is created, if not, None is used. """ - self.__check_primary_from_handle(handle, transaction, Repository, - self.has_repository_handle, self.add_repository, + self.__check_primary_from_handle(handle, transaction, Repository, + self.has_repository_handle, self.add_repository, set_gid=set_gid) def check_note_from_handle(self, handle, transaction, set_gid=True): """ - Check whether a Note with the passed handle exists in the database. - + Check whether a Note with the passed handle exists in the database. + If no such Note exists, a new Note is added to the database. If set_gid then a new gramps_id is created, if not, None is used. """ - self.__check_primary_from_handle(handle, transaction, Note, - self.has_note_handle, self.add_note, + self.__check_primary_from_handle(handle, transaction, Note, + self.has_note_handle, self.add_note, set_gid=set_gid) def check_tag_from_handle(self, handle, transaction): """ - Check whether a Tag with the passed handle exists in the database. - + Check whether a Tag with the passed handle exists in the database. + If no such Tag exists, a new Tag is added to the database. """ - self.__check_table_from_handle(handle, transaction, Tag, + self.__check_table_from_handle(handle, transaction, Tag, self.has_tag_handle, self.add_tag) diff --git a/gramps/plugins/lib/libnarrate.py b/gramps/plugins/lib/libnarrate.py index 1a0375565..aa747a35a 100644 --- a/gramps/plugins/lib/libnarrate.py +++ b/gramps/plugins/lib/libnarrate.py @@ -14,7 +14,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -49,7 +49,7 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale # Private constants # #------------------------------------------------------------------------- -# In string arrays, the first strings should include the name, the second +# In string arrays, the first strings should include the name, the second # strings should not include the name. _NAME_INDEX_INCLUDE_NAME = 0 _NAME_INDEX_EXCLUDE_NAME = 1 @@ -85,101 +85,101 @@ def _(message): return message #------------------------------------------------------------------------ born_full_date_with_place = [ { - Person.UNKNOWN : _("%(unknown_gender_name)s was born on %(birth_date)s in %(birth_place)s."), - Person.MALE : _("%(male_name)s was born on %(birth_date)s in %(birth_place)s."), - Person.FEMALE : _("%(female_name)s was born on %(birth_date)s in %(birth_place)s."), + Person.UNKNOWN : _("%(unknown_gender_name)s was born on %(birth_date)s in %(birth_place)s."), + Person.MALE : _("%(male_name)s was born on %(birth_date)s in %(birth_place)s."), + Person.FEMALE : _("%(female_name)s was born on %(birth_date)s in %(birth_place)s."), }, { - Person.UNKNOWN : _("This person was born on %(birth_date)s in %(birth_place)s."), - Person.MALE : _("He was born on %(birth_date)s in %(birth_place)s."), - Person.FEMALE : _("She was born on %(birth_date)s in %(birth_place)s."), - }, - _("Born %(birth_date)s in %(birth_place)s."), + Person.UNKNOWN : _("This person was born on %(birth_date)s in %(birth_place)s."), + Person.MALE : _("He was born on %(birth_date)s in %(birth_place)s."), + Person.FEMALE : _("She was born on %(birth_date)s in %(birth_place)s."), + }, + _("Born %(birth_date)s in %(birth_place)s."), ] born_modified_date_with_place = [ { - Person.UNKNOWN : _("%(unknown_gender_name)s was born %(modified_date)s in %(birth_place)s."), - Person.MALE : _("%(male_name)s was born %(modified_date)s in %(birth_place)s."), - Person.FEMALE : _("%(female_name)s was born %(modified_date)s in %(birth_place)s."), + Person.UNKNOWN : _("%(unknown_gender_name)s was born %(modified_date)s in %(birth_place)s."), + Person.MALE : _("%(male_name)s was born %(modified_date)s in %(birth_place)s."), + Person.FEMALE : _("%(female_name)s was born %(modified_date)s in %(birth_place)s."), }, { - Person.UNKNOWN : _("This person was born %(modified_date)s in %(birth_place)s."), - Person.MALE : _("He was born %(modified_date)s in %(birth_place)s."), - Person.FEMALE : _("She was born %(modified_date)s in %(birth_place)s."), - }, - _("Born %(modified_date)s in %(birth_place)s."), + Person.UNKNOWN : _("This person was born %(modified_date)s in %(birth_place)s."), + Person.MALE : _("He was born %(modified_date)s in %(birth_place)s."), + Person.FEMALE : _("She was born %(modified_date)s in %(birth_place)s."), + }, + _("Born %(modified_date)s in %(birth_place)s."), ] born_full_date_no_place = [ { - Person.UNKNOWN : _("%(unknown_gender_name)s was born on %(birth_date)s."), - Person.MALE : _("%(male_name)s was born on %(birth_date)s."), - Person.FEMALE : _("%(female_name)s was born on %(birth_date)s."), + Person.UNKNOWN : _("%(unknown_gender_name)s was born on %(birth_date)s."), + Person.MALE : _("%(male_name)s was born on %(birth_date)s."), + Person.FEMALE : _("%(female_name)s was born on %(birth_date)s."), }, { - Person.UNKNOWN : _("This person was born on %(birth_date)s."), - Person.MALE : _("He was born on %(birth_date)s."), - Person.FEMALE : _("She was born on %(birth_date)s."), - }, - _("Born %(birth_date)s."), -] + Person.UNKNOWN : _("This person was born on %(birth_date)s."), + Person.MALE : _("He was born on %(birth_date)s."), + Person.FEMALE : _("She was born on %(birth_date)s."), + }, + _("Born %(birth_date)s."), +] born_modified_date_no_place = [ { - Person.UNKNOWN : _("%(unknown_gender_name)s was born %(modified_date)s."), - Person.MALE : _("%(male_name)s was born %(modified_date)s."), - Person.FEMALE : _("%(female_name)s was born %(modified_date)s."), - }, + Person.UNKNOWN : _("%(unknown_gender_name)s was born %(modified_date)s."), + Person.MALE : _("%(male_name)s was born %(modified_date)s."), + Person.FEMALE : _("%(female_name)s was born %(modified_date)s."), + }, { - Person.UNKNOWN : _("This person was born %(modified_date)s."), - Person.MALE : _("He was born %(modified_date)s."), - Person.FEMALE : _("She was born %(modified_date)s."), - }, + Person.UNKNOWN : _("This person was born %(modified_date)s."), + Person.MALE : _("He was born %(modified_date)s."), + Person.FEMALE : _("She was born %(modified_date)s."), + }, _("Born %(modified_date)s."), -] +] born_partial_date_with_place = [ { - Person.UNKNOWN : _("%(unknown_gender_name)s was born in %(month_year)s in %(birth_place)s."), - Person.MALE : _("%(male_name)s was born in %(month_year)s in %(birth_place)s."), - Person.FEMALE : _("%(female_name)s was born in %(month_year)s in %(birth_place)s."), - }, + Person.UNKNOWN : _("%(unknown_gender_name)s was born in %(month_year)s in %(birth_place)s."), + Person.MALE : _("%(male_name)s was born in %(month_year)s in %(birth_place)s."), + Person.FEMALE : _("%(female_name)s was born in %(month_year)s in %(birth_place)s."), + }, { - Person.UNKNOWN : _("This person was born in %(month_year)s in %(birth_place)s."), - Person.MALE : _("He was born in %(month_year)s in %(birth_place)s."), - Person.FEMALE : _("She was born in %(month_year)s in %(birth_place)s."), - }, + Person.UNKNOWN : _("This person was born in %(month_year)s in %(birth_place)s."), + Person.MALE : _("He was born in %(month_year)s in %(birth_place)s."), + Person.FEMALE : _("She was born in %(month_year)s in %(birth_place)s."), + }, _("Born %(month_year)s in %(birth_place)s."), -] +] born_partial_date_no_place = [ { - Person.UNKNOWN : _("%(unknown_gender_name)s was born in %(month_year)s."), - Person.MALE : _("%(male_name)s was born in %(month_year)s."), - Person.FEMALE : _("%(female_name)s was born in %(month_year)s."), + Person.UNKNOWN : _("%(unknown_gender_name)s was born in %(month_year)s."), + Person.MALE : _("%(male_name)s was born in %(month_year)s."), + Person.FEMALE : _("%(female_name)s was born in %(month_year)s."), }, { - Person.UNKNOWN : _("This person was born in %(month_year)s."), - Person.MALE : _("He was born in %(month_year)s."), - Person.FEMALE : _("She was born in %(month_year)s."), - }, + Person.UNKNOWN : _("This person was born in %(month_year)s."), + Person.MALE : _("He was born in %(month_year)s."), + Person.FEMALE : _("She was born in %(month_year)s."), + }, _("Born %(month_year)s."), -] +] born_no_date_with_place = [ { - Person.UNKNOWN : _("%(unknown_gender_name)s was born in %(birth_place)s."), - Person.MALE : _("%(male_name)s was born in %(birth_place)s."), - Person.FEMALE : _("%(female_name)s was born in %(birth_place)s."), + Person.UNKNOWN : _("%(unknown_gender_name)s was born in %(birth_place)s."), + Person.MALE : _("%(male_name)s was born in %(birth_place)s."), + Person.FEMALE : _("%(female_name)s was born in %(birth_place)s."), }, { - Person.UNKNOWN : _("This person was born in %(birth_place)s."), - Person.MALE : _("He was born in %(birth_place)s."), - Person.FEMALE : _("She was born in %(birth_place)s."), - }, + Person.UNKNOWN : _("This person was born in %(birth_place)s."), + Person.MALE : _("He was born in %(birth_place)s."), + Person.FEMALE : _("She was born in %(birth_place)s."), + }, _("Born in %(birth_place)s."), -] +] #------------------------------------------------------------------------ # @@ -188,267 +188,267 @@ born_no_date_with_place = [ #------------------------------------------------------------------------ died_full_date_with_place = [ { Person.UNKNOWN : [ - _("%(unknown_gender_name)s died on %(death_date)s in %(death_place)s."), - _("%(unknown_gender_name)s died on %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("%(unknown_gender_name)s died on %(death_date)s in %(death_place)s."), + _("%(unknown_gender_name)s died on %(death_date)s in %(death_place)s at the age of %(age)s."), + ], Person.MALE : [ - _("%(male_name)s died on %(death_date)s in %(death_place)s."), - _("%(male_name)s died on %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("%(male_name)s died on %(death_date)s in %(death_place)s."), + _("%(male_name)s died on %(death_date)s in %(death_place)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("%(female_name)s died on %(death_date)s in %(death_place)s."), - _("%(female_name)s died on %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("%(female_name)s died on %(death_date)s in %(death_place)s."), + _("%(female_name)s died on %(death_date)s in %(death_place)s at the age of %(age)s."), + ], }, { Person.UNKNOWN : [ - _("This person died on %(death_date)s in %(death_place)s."), - _("This person died on %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("This person died on %(death_date)s in %(death_place)s."), + _("This person died on %(death_date)s in %(death_place)s at the age of %(age)s."), + ], Person.MALE : [ - _("He died on %(death_date)s in %(death_place)s."), - _("He died on %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("He died on %(death_date)s in %(death_place)s."), + _("He died on %(death_date)s in %(death_place)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("She died on %(death_date)s in %(death_place)s."), - _("She died on %(death_date)s in %(death_place)s at the age of %(age)s."), - ], - }, + _("She died on %(death_date)s in %(death_place)s."), + _("She died on %(death_date)s in %(death_place)s at the age of %(age)s."), + ], + }, [ _("Died %(death_date)s in %(death_place)s."), _("Died %(death_date)s in %(death_place)s (%(age)s)."), - ], + ], ] died_modified_date_with_place = [ { Person.UNKNOWN : [ - _("%(unknown_gender_name)s died %(death_date)s in %(death_place)s."), - _("%(unknown_gender_name)s died %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("%(unknown_gender_name)s died %(death_date)s in %(death_place)s."), + _("%(unknown_gender_name)s died %(death_date)s in %(death_place)s at the age of %(age)s."), + ], Person.MALE : [ - _("%(male_name)s died %(death_date)s in %(death_place)s."), - _("%(male_name)s died %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("%(male_name)s died %(death_date)s in %(death_place)s."), + _("%(male_name)s died %(death_date)s in %(death_place)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("%(female_name)s died %(death_date)s in %(death_place)s."), - _("%(female_name)s died %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("%(female_name)s died %(death_date)s in %(death_place)s."), + _("%(female_name)s died %(death_date)s in %(death_place)s at the age of %(age)s."), + ], }, { Person.UNKNOWN : [ - _("This person died %(death_date)s in %(death_place)s."), - _("This person died %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("This person died %(death_date)s in %(death_place)s."), + _("This person died %(death_date)s in %(death_place)s at the age of %(age)s."), + ], Person.MALE : [ - _("He died %(death_date)s in %(death_place)s."), - _("He died %(death_date)s in %(death_place)s at the age of %(age)s."), - ], + _("He died %(death_date)s in %(death_place)s."), + _("He died %(death_date)s in %(death_place)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("She died %(death_date)s in %(death_place)s."), - _("She died %(death_date)s in %(death_place)s at the age of %(age)s."), - ], - }, + _("She died %(death_date)s in %(death_place)s."), + _("She died %(death_date)s in %(death_place)s at the age of %(age)s."), + ], + }, [ _("Died %(death_date)s in %(death_place)s."), _("Died %(death_date)s in %(death_place)s (%(age)s)."), - ], + ], ] died_full_date_no_place = [ { Person.UNKNOWN : [ - _("%(unknown_gender_name)s died on %(death_date)s."), - _("%(unknown_gender_name)s died on %(death_date)s at the age of %(age)s."), - ], + _("%(unknown_gender_name)s died on %(death_date)s."), + _("%(unknown_gender_name)s died on %(death_date)s at the age of %(age)s."), + ], Person.MALE : [ - _("%(male_name)s died on %(death_date)s."), - _("%(male_name)s died on %(death_date)s at the age of %(age)s."), - ], + _("%(male_name)s died on %(death_date)s."), + _("%(male_name)s died on %(death_date)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("%(female_name)s died on %(death_date)s."), - _("%(female_name)s died on %(death_date)s at the age of %(age)s."), - ], + _("%(female_name)s died on %(death_date)s."), + _("%(female_name)s died on %(death_date)s at the age of %(age)s."), + ], }, { Person.UNKNOWN : [ - _("This person died on %(death_date)s."), - _("This person died on %(death_date)s at the age of %(age)s."), - ], + _("This person died on %(death_date)s."), + _("This person died on %(death_date)s at the age of %(age)s."), + ], Person.MALE : [ - _("He died on %(death_date)s."), - _("He died on %(death_date)s at the age of %(age)s."), - ], + _("He died on %(death_date)s."), + _("He died on %(death_date)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("She died on %(death_date)s."), - _("She died on %(death_date)s at the age of %(age)s."), - ], - }, + _("She died on %(death_date)s."), + _("She died on %(death_date)s at the age of %(age)s."), + ], + }, [ _("Died %(death_date)s."), _("Died %(death_date)s (%(age)s)."), - ], -] + ], +] died_modified_date_no_place = [ { Person.UNKNOWN : [ - _("%(unknown_gender_name)s died %(death_date)s."), - _("%(unknown_gender_name)s died %(death_date)s at the age of %(age)s."), - ], + _("%(unknown_gender_name)s died %(death_date)s."), + _("%(unknown_gender_name)s died %(death_date)s at the age of %(age)s."), + ], Person.MALE : [ - _("%(male_name)s died %(death_date)s."), - _("%(male_name)s died %(death_date)s at the age of %(age)s."), - ], + _("%(male_name)s died %(death_date)s."), + _("%(male_name)s died %(death_date)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("%(female_name)s died %(death_date)s."), - _("%(female_name)s died %(death_date)s at the age of %(age)s."), - ], + _("%(female_name)s died %(death_date)s."), + _("%(female_name)s died %(death_date)s at the age of %(age)s."), + ], }, { Person.UNKNOWN : [ - _("This person died %(death_date)s."), - _("This person died %(death_date)s at the age of %(age)s."), - ], + _("This person died %(death_date)s."), + _("This person died %(death_date)s at the age of %(age)s."), + ], Person.MALE : [ - _("He died %(death_date)s."), - _("He died %(death_date)s at the age of %(age)s."), - ], + _("He died %(death_date)s."), + _("He died %(death_date)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("She died %(death_date)s."), - _("She died %(death_date)s at the age of %(age)s."), - ], - }, + _("She died %(death_date)s."), + _("She died %(death_date)s at the age of %(age)s."), + ], + }, [ _("Died %(death_date)s."), _("Died %(death_date)s (%(age)s)."), - ], -] + ], +] died_partial_date_with_place = [ { Person.UNKNOWN : [ - _("%(unknown_gender_name)s died in %(month_year)s in %(death_place)s."), - _("%(unknown_gender_name)s died in %(month_year)s in %(death_place)s at the age of %(age)s."), - ], + _("%(unknown_gender_name)s died in %(month_year)s in %(death_place)s."), + _("%(unknown_gender_name)s died in %(month_year)s in %(death_place)s at the age of %(age)s."), + ], Person.MALE : [ - _("%(male_name)s died in %(month_year)s in %(death_place)s."), - _("%(male_name)s died in %(month_year)s in %(death_place)s at the age of %(age)s."), - ], + _("%(male_name)s died in %(month_year)s in %(death_place)s."), + _("%(male_name)s died in %(month_year)s in %(death_place)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("%(female_name)s died in %(month_year)s in %(death_place)s."), - _("%(female_name)s died in %(month_year)s in %(death_place)s at the age of %(age)s."), - ], + _("%(female_name)s died in %(month_year)s in %(death_place)s."), + _("%(female_name)s died in %(month_year)s in %(death_place)s at the age of %(age)s."), + ], }, { Person.UNKNOWN : [ - _("This person died in %(month_year)s in %(death_place)s."), - _("This person died in %(month_year)s in %(death_place)s at the age of %(age)s."), - ], + _("This person died in %(month_year)s in %(death_place)s."), + _("This person died in %(month_year)s in %(death_place)s at the age of %(age)s."), + ], Person.MALE : [ - _("He died in %(month_year)s in %(death_place)s."), - _("He died in %(month_year)s in %(death_place)s at the age of %(age)s."), - ], + _("He died in %(month_year)s in %(death_place)s."), + _("He died in %(month_year)s in %(death_place)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("She died in %(month_year)s in %(death_place)s."), - _("She died in %(month_year)s in %(death_place)s at the age of %(age)s."), + _("She died in %(month_year)s in %(death_place)s."), + _("She died in %(month_year)s in %(death_place)s at the age of %(age)s."), ] - }, + }, [ _("Died %(month_year)s in %(death_place)s."), _("Died %(month_year)s in %(death_place)s (%(age)s)."), - ], -] + ], +] died_partial_date_no_place = [ { Person.UNKNOWN : [ - _("%(unknown_gender_name)s died in %(month_year)s."), - _("%(unknown_gender_name)s died in %(month_year)s at the age of %(age)s."), - ], + _("%(unknown_gender_name)s died in %(month_year)s."), + _("%(unknown_gender_name)s died in %(month_year)s at the age of %(age)s."), + ], Person.MALE : [ - _("%(male_name)s died in %(month_year)s."), - _("%(male_name)s died in %(month_year)s at the age of %(age)s."), - ], + _("%(male_name)s died in %(month_year)s."), + _("%(male_name)s died in %(month_year)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("%(female_name)s died in %(month_year)s."), - _("%(female_name)s died in %(month_year)s at the age of %(age)s."), - ], + _("%(female_name)s died in %(month_year)s."), + _("%(female_name)s died in %(month_year)s at the age of %(age)s."), + ], }, { Person.UNKNOWN : [ - _("This person died in %(month_year)s."), - _("This person died in %(month_year)s at the age of %(age)s."), - ], + _("This person died in %(month_year)s."), + _("This person died in %(month_year)s at the age of %(age)s."), + ], Person.MALE : [ - _("He died in %(month_year)s."), - _("He died in %(month_year)s at the age of %(age)s."), - ], + _("He died in %(month_year)s."), + _("He died in %(month_year)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("She died in %(month_year)s."), - _("She died in %(month_year)s at the age of %(age)s."), - ], - }, + _("She died in %(month_year)s."), + _("She died in %(month_year)s at the age of %(age)s."), + ], + }, [ _("Died %(month_year)s."), _("Died %(month_year)s (%(age)s)."), ], -] +] died_no_date_with_place = [ { Person.UNKNOWN : [ - _("%(unknown_gender_name)s died in %(death_place)s."), - _("%(unknown_gender_name)s died in %(death_place)s at the age of %(age)s."), - ], + _("%(unknown_gender_name)s died in %(death_place)s."), + _("%(unknown_gender_name)s died in %(death_place)s at the age of %(age)s."), + ], Person.MALE : [ - _("%(male_name)s died in %(death_place)s."), - _("%(male_name)s died in %(death_place)s at the age of %(age)s."), - ], + _("%(male_name)s died in %(death_place)s."), + _("%(male_name)s died in %(death_place)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("%(female_name)s died in %(death_place)s."), - _("%(female_name)s died in %(death_place)s at the age of %(age)s."), - ], + _("%(female_name)s died in %(death_place)s."), + _("%(female_name)s died in %(death_place)s at the age of %(age)s."), + ], }, { Person.UNKNOWN : [ - _("This person died in %(death_place)s."), - _("This person died in %(death_place)s at the age of %(age)s."), - ], + _("This person died in %(death_place)s."), + _("This person died in %(death_place)s at the age of %(age)s."), + ], Person.MALE : [ - _("He died in %(death_place)s."), - _("He died in %(death_place)s at the age of %(age)s."), - ], + _("He died in %(death_place)s."), + _("He died in %(death_place)s at the age of %(age)s."), + ], Person.FEMALE : [ - _("She died in %(death_place)s."), - _("She died in %(death_place)s at the age of %(age)s."), - ], - }, + _("She died in %(death_place)s."), + _("She died in %(death_place)s at the age of %(age)s."), + ], + }, [ _("Died in %(death_place)s."), _("Died in %(death_place)s (%(age)s)."), ], -] +] died_no_date_no_place = [ { Person.UNKNOWN : [ - "", - _("%(unknown_gender_name)s died at the age of %(age)s."), - ], + "", + _("%(unknown_gender_name)s died at the age of %(age)s."), + ], Person.MALE : [ - "", - _("%(male_name)s died at the age of %(age)s."), - ], + "", + _("%(male_name)s died at the age of %(age)s."), + ], Person.FEMALE : [ - "", - _("%(female_name)s died at the age of %(age)s."), - ], + "", + _("%(female_name)s died at the age of %(age)s."), + ], }, { Person.UNKNOWN : [ - "", - _("This person died at the age of %(age)s."), - ], + "", + _("This person died at the age of %(age)s."), + ], Person.MALE : [ - "", - _("He died at the age of %(age)s."), - ], + "", + _("He died at the age of %(age)s."), + ], Person.FEMALE : [ - "", - _("She died at the age of %(age)s."), - ], - }, + "", + _("She died at the age of %(age)s."), + ], + }, [ "", _("Died (%(age)s)."), - ], + ], ] #------------------------------------------------------------------------ @@ -458,131 +458,131 @@ died_no_date_no_place = [ #------------------------------------------------------------------------ buried_full_date_place = { Person.MALE: [ - _("%(male_name)s was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), - _("He was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), - ], + _("%(male_name)s was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), + _("He was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), + ], Person.FEMALE: [ - _("%(female_name)s was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), - _("She was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), - ], + _("%(female_name)s was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), + _("She was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), + ], Person.UNKNOWN: [ - _("%(unknown_gender_name)s was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), - _("This person was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), - ], + _("%(unknown_gender_name)s was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), + _("This person was buried on %(burial_date)s in %(burial_place)s%(endnotes)s."), + ], 'succinct' : _("Buried %(burial_date)s in %(burial_place)s%(endnotes)s."), } buried_full_date_no_place = { Person.MALE: [ - _("%(male_name)s was buried on %(burial_date)s%(endnotes)s."), - _("He was buried on %(burial_date)s%(endnotes)s."), - ], + _("%(male_name)s was buried on %(burial_date)s%(endnotes)s."), + _("He was buried on %(burial_date)s%(endnotes)s."), + ], Person.FEMALE: [ - _("%(female_name)s was buried on %(burial_date)s%(endnotes)s."), - _("She was buried on %(burial_date)s%(endnotes)s."), - ], + _("%(female_name)s was buried on %(burial_date)s%(endnotes)s."), + _("She was buried on %(burial_date)s%(endnotes)s."), + ], Person.UNKNOWN: [ - _("%(unknown_gender_name)s was buried on %(burial_date)s%(endnotes)s."), - _("This person was buried on %(burial_date)s%(endnotes)s."), - ], + _("%(unknown_gender_name)s was buried on %(burial_date)s%(endnotes)s."), + _("This person was buried on %(burial_date)s%(endnotes)s."), + ], 'succinct' : _("Buried %(burial_date)s%(endnotes)s."), } buried_partial_date_place = { Person.MALE: [ - _("%(male_name)s was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), - _("He was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), - ], + _("%(male_name)s was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), + _("He was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), + ], Person.FEMALE: [ - _("%(female_name)s was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), - _("She was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), - ], + _("%(female_name)s was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), + _("She was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), + ], Person.UNKNOWN: [ - _("%(unknown_gender_name)s was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), - _("This person was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), - ], + _("%(unknown_gender_name)s was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), + _("This person was buried in %(month_year)s in %(burial_place)s%(endnotes)s."), + ], 'succinct' : _("Buried %(month_year)s in %(burial_place)s%(endnotes)s."), } buried_partial_date_no_place = { Person.MALE: [ - _("%(male_name)s was buried in %(month_year)s%(endnotes)s."), - _("He was buried in %(month_year)s%(endnotes)s."), - ], + _("%(male_name)s was buried in %(month_year)s%(endnotes)s."), + _("He was buried in %(month_year)s%(endnotes)s."), + ], Person.FEMALE: [ - _("%(female_name)s was buried in %(month_year)s%(endnotes)s."), - _("She was buried in %(month_year)s%(endnotes)s."), - ], + _("%(female_name)s was buried in %(month_year)s%(endnotes)s."), + _("She was buried in %(month_year)s%(endnotes)s."), + ], Person.UNKNOWN: [ - _("%(unknown_gender_name)s was buried in %(month_year)s%(endnotes)s."), - _("This person was buried in %(month_year)s%(endnotes)s."), - ], + _("%(unknown_gender_name)s was buried in %(month_year)s%(endnotes)s."), + _("This person was buried in %(month_year)s%(endnotes)s."), + ], 'succinct' : _("Buried %(month_year)s%(endnotes)s."), } buried_modified_date_place = { Person.MALE: [ - _("%(male_name)s was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), - _("He was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), - ], + _("%(male_name)s was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), + _("He was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), + ], Person.FEMALE: [ - _("%(female_name)s was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), - _("She was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), - ], + _("%(female_name)s was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), + _("She was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), + ], Person.UNKNOWN: [ - _("%(unknown_gender_name)s was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), - _("This person was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), - ], + _("%(unknown_gender_name)s was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), + _("This person was buried %(modified_date)s in %(burial_place)s%(endnotes)s."), + ], 'succinct' : _("Buried %(modified_date)s in %(burial_place)s%(endnotes)s."), } buried_modified_date_no_place = { Person.MALE: [ - _("%(male_name)s was buried %(modified_date)s%(endnotes)s."), - _("He was buried %(modified_date)s%(endnotes)s."), - ], + _("%(male_name)s was buried %(modified_date)s%(endnotes)s."), + _("He was buried %(modified_date)s%(endnotes)s."), + ], Person.FEMALE: [ - _("%(female_name)s was buried %(modified_date)s%(endnotes)s."), - _("She was buried %(modified_date)s%(endnotes)s."), - ], + _("%(female_name)s was buried %(modified_date)s%(endnotes)s."), + _("She was buried %(modified_date)s%(endnotes)s."), + ], Person.UNKNOWN: [ - _("%(unknown_gender_name)s was buried %(modified_date)s%(endnotes)s."), - _("This person was buried %(modified_date)s%(endnotes)s."), - ], + _("%(unknown_gender_name)s was buried %(modified_date)s%(endnotes)s."), + _("This person was buried %(modified_date)s%(endnotes)s."), + ], 'succinct' : _("Buried %(modified_date)s%(endnotes)s."), } buried_no_date_place = { Person.MALE : [ - _("%(male_name)s was buried in %(burial_place)s%(endnotes)s."), - _("He was buried in %(burial_place)s%(endnotes)s."), - ], + _("%(male_name)s was buried in %(burial_place)s%(endnotes)s."), + _("He was buried in %(burial_place)s%(endnotes)s."), + ], Person.FEMALE : [ - _("%(female_name)s was buried in %(burial_place)s%(endnotes)s."), - _("She was buried in %(burial_place)s%(endnotes)s."), - ], + _("%(female_name)s was buried in %(burial_place)s%(endnotes)s."), + _("She was buried in %(burial_place)s%(endnotes)s."), + ], Person.UNKNOWN : [ - _("%(unknown_gender_name)s was buried in %(burial_place)s%(endnotes)s."), - _("This person was buried in %(burial_place)s%(endnotes)s."), - ], + _("%(unknown_gender_name)s was buried in %(burial_place)s%(endnotes)s."), + _("This person was buried in %(burial_place)s%(endnotes)s."), + ], 'succinct' : _("Buried in %(burial_place)s%(endnotes)s."), } buried_no_date_no_place = { Person.MALE : [ - _("%(male_name)s was buried%(endnotes)s."), - _("He was buried%(endnotes)s."), - ], + _("%(male_name)s was buried%(endnotes)s."), + _("He was buried%(endnotes)s."), + ], Person.FEMALE : [ - _("%(female_name)s was buried%(endnotes)s."), - _("She was buried%(endnotes)s."), - ], + _("%(female_name)s was buried%(endnotes)s."), + _("She was buried%(endnotes)s."), + ], Person.UNKNOWN : [ - _("%(unknown_gender_name)s was buried%(endnotes)s."), - _("This person was buried%(endnotes)s."), + _("%(unknown_gender_name)s was buried%(endnotes)s."), + _("This person was buried%(endnotes)s."), ], 'succinct' : _("Buried%(endnotes)s."), - + } #------------------------------------------------------------------------ # @@ -591,128 +591,128 @@ buried_no_date_no_place = { #------------------------------------------------------------------------ baptised_full_date_place = { Person.MALE: [ - _("%(male_name)s was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), - _("He was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), - _("She was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), - _("This person was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), + _("%(male_name)s was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), + _("He was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), ], - 'succinct' : _("Baptized %(baptism_date)s in %(baptism_place)s%(endnotes)s."), + Person.FEMALE: [ + _("%(female_name)s was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), + _("She was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), + _("This person was baptized on %(baptism_date)s in %(baptism_place)s%(endnotes)s."), + ], + 'succinct' : _("Baptized %(baptism_date)s in %(baptism_place)s%(endnotes)s."), } baptised_full_date_no_place = { Person.MALE: [ - _("%(male_name)s was baptized on %(baptism_date)s%(endnotes)s."), - _("He was baptized on %(baptism_date)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was baptized on %(baptism_date)s%(endnotes)s."), - _("She was baptized on %(baptism_date)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was baptized on %(baptism_date)s%(endnotes)s."), - _("This person was baptized on %(baptism_date)s%(endnotes)s."), + _("%(male_name)s was baptized on %(baptism_date)s%(endnotes)s."), + _("He was baptized on %(baptism_date)s%(endnotes)s."), ], - 'succinct' : _("Baptized %(baptism_date)s%(endnotes)s.") + Person.FEMALE: [ + _("%(female_name)s was baptized on %(baptism_date)s%(endnotes)s."), + _("She was baptized on %(baptism_date)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was baptized on %(baptism_date)s%(endnotes)s."), + _("This person was baptized on %(baptism_date)s%(endnotes)s."), + ], + 'succinct' : _("Baptized %(baptism_date)s%(endnotes)s.") } baptised_partial_date_place = { Person.MALE: [ - _("%(male_name)s was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), - _("He was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), - ], -Person.FEMALE: [ - _("%(female_name)s was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), - _("She was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), - ], -Person.UNKNOWN: [ - _("%(unknown_gender_name)s was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), - _("This person was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), + _("%(male_name)s was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), + _("He was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), ], - 'succinct' : _("Baptized %(month_year)s in %(baptism_place)s%(endnotes)s."), +Person.FEMALE: [ + _("%(female_name)s was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), + _("She was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), + ], +Person.UNKNOWN: [ + _("%(unknown_gender_name)s was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), + _("This person was baptized in %(month_year)s in %(baptism_place)s%(endnotes)s."), + ], + 'succinct' : _("Baptized %(month_year)s in %(baptism_place)s%(endnotes)s."), } baptised_partial_date_no_place = { Person.MALE: [ - _("%(male_name)s was baptized in %(month_year)s%(endnotes)s."), - _("He was baptized in %(month_year)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was baptized in %(month_year)s%(endnotes)s."), - _("She was baptized in %(month_year)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was baptized in %(month_year)s%(endnotes)s."), - _("This person was baptized in %(month_year)s%(endnotes)s."), + _("%(male_name)s was baptized in %(month_year)s%(endnotes)s."), + _("He was baptized in %(month_year)s%(endnotes)s."), ], - 'succinct' : _("Baptized %(month_year)s%(endnotes)s."), + Person.FEMALE: [ + _("%(female_name)s was baptized in %(month_year)s%(endnotes)s."), + _("She was baptized in %(month_year)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was baptized in %(month_year)s%(endnotes)s."), + _("This person was baptized in %(month_year)s%(endnotes)s."), + ], + 'succinct' : _("Baptized %(month_year)s%(endnotes)s."), } baptised_modified_date_place = { Person.MALE: [ - _("%(male_name)s was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), - _("He was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), - _("She was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), - _("This person was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), + _("%(male_name)s was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), + _("He was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), ], - 'succinct' : _("Baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), + Person.FEMALE: [ + _("%(female_name)s was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), + _("She was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), + _("This person was baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), + ], + 'succinct' : _("Baptized %(modified_date)s in %(baptism_place)s%(endnotes)s."), } baptised_modified_date_no_place = { Person.MALE: [ - _("%(male_name)s was baptized %(modified_date)s%(endnotes)s."), - _("He was baptized %(modified_date)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was baptized %(modified_date)s%(endnotes)s."), - _("She was baptized %(modified_date)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was baptized %(modified_date)s%(endnotes)s."), - _("This person was baptized %(modified_date)s%(endnotes)s."), + _("%(male_name)s was baptized %(modified_date)s%(endnotes)s."), + _("He was baptized %(modified_date)s%(endnotes)s."), ], - 'succinct' : _("Baptized %(modified_date)s%(endnotes)s."), + Person.FEMALE: [ + _("%(female_name)s was baptized %(modified_date)s%(endnotes)s."), + _("She was baptized %(modified_date)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was baptized %(modified_date)s%(endnotes)s."), + _("This person was baptized %(modified_date)s%(endnotes)s."), + ], + 'succinct' : _("Baptized %(modified_date)s%(endnotes)s."), } baptised_no_date_place = { Person.MALE : [ - _("%(male_name)s was baptized in %(baptism_place)s%(endnotes)s."), - _("He was baptized in %(baptism_place)s%(endnotes)s."), - ], - Person.FEMALE : [ - _("%(female_name)s was baptized in %(baptism_place)s%(endnotes)s."), - _("She was baptized in %(baptism_place)s%(endnotes)s."), - ], - Person.UNKNOWN : [ - _("%(unknown_gender_name)s was baptized in %(baptism_place)s%(endnotes)s."), - _("This person was baptized in %(baptism_place)s%(endnotes)s."), + _("%(male_name)s was baptized in %(baptism_place)s%(endnotes)s."), + _("He was baptized in %(baptism_place)s%(endnotes)s."), ], - 'succinct' : _("Baptized in %(baptism_place)s%(endnotes)s."), + Person.FEMALE : [ + _("%(female_name)s was baptized in %(baptism_place)s%(endnotes)s."), + _("She was baptized in %(baptism_place)s%(endnotes)s."), + ], + Person.UNKNOWN : [ + _("%(unknown_gender_name)s was baptized in %(baptism_place)s%(endnotes)s."), + _("This person was baptized in %(baptism_place)s%(endnotes)s."), + ], + 'succinct' : _("Baptized in %(baptism_place)s%(endnotes)s."), } baptised_no_date_no_place = { Person.MALE : [ - _("%(male_name)s was baptized%(endnotes)s."), - _("He was baptized%(endnotes)s."), - ], + _("%(male_name)s was baptized%(endnotes)s."), + _("He was baptized%(endnotes)s."), + ], Person.FEMALE : [ - _("%(female_name)s was baptized%(endnotes)s."), - _("She was baptized%(endnotes)s."), - ], + _("%(female_name)s was baptized%(endnotes)s."), + _("She was baptized%(endnotes)s."), + ], Person.UNKNOWN : [ - _("%(unknown_gender_name)s was baptized%(endnotes)s."), - _("This person was baptized%(endnotes)s."), + _("%(unknown_gender_name)s was baptized%(endnotes)s."), + _("This person was baptized%(endnotes)s."), ], 'succinct' : _("Baptized%(endnotes)s."), } @@ -724,128 +724,128 @@ baptised_no_date_no_place = { #------------------------------------------------------------------------ christened_full_date_place = { Person.MALE: [ - _("%(male_name)s was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), - _("He was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), - _("She was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), - _("This person was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), + _("%(male_name)s was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), + _("He was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), ], - 'succinct' : _("Christened %(christening_date)s in %(christening_place)s%(endnotes)s."), + Person.FEMALE: [ + _("%(female_name)s was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), + _("She was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), + _("This person was christened on %(christening_date)s in %(christening_place)s%(endnotes)s."), + ], + 'succinct' : _("Christened %(christening_date)s in %(christening_place)s%(endnotes)s."), } christened_full_date_no_place = { Person.MALE: [ - _("%(male_name)s was christened on %(christening_date)s%(endnotes)s."), - _("He was christened on %(christening_date)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was christened on %(christening_date)s%(endnotes)s."), - _("She was christened on %(christening_date)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was christened on %(christening_date)s%(endnotes)s."), - _("This person was christened on %(christening_date)s%(endnotes)s."), + _("%(male_name)s was christened on %(christening_date)s%(endnotes)s."), + _("He was christened on %(christening_date)s%(endnotes)s."), ], - 'succinct' : _("Christened %(christening_date)s%(endnotes)s.") + Person.FEMALE: [ + _("%(female_name)s was christened on %(christening_date)s%(endnotes)s."), + _("She was christened on %(christening_date)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was christened on %(christening_date)s%(endnotes)s."), + _("This person was christened on %(christening_date)s%(endnotes)s."), + ], + 'succinct' : _("Christened %(christening_date)s%(endnotes)s.") } christened_partial_date_place = { Person.MALE: [ - _("%(male_name)s was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), - _("He was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), - ], -Person.FEMALE: [ - _("%(female_name)s was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), - _("She was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), - ], -Person.UNKNOWN: [ - _("%(unknown_gender_name)s was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), - _("This person was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), + _("%(male_name)s was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), + _("He was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), ], - 'succinct' : _("Christened %(month_year)s in %(christening_place)s%(endnotes)s."), +Person.FEMALE: [ + _("%(female_name)s was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), + _("She was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), + ], +Person.UNKNOWN: [ + _("%(unknown_gender_name)s was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), + _("This person was christened in %(month_year)s in %(christening_place)s%(endnotes)s."), + ], + 'succinct' : _("Christened %(month_year)s in %(christening_place)s%(endnotes)s."), } christened_partial_date_no_place = { Person.MALE: [ - _("%(male_name)s was christened in %(month_year)s%(endnotes)s."), - _("He was christened in %(month_year)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was christened in %(month_year)s%(endnotes)s."), - _("She was christened in %(month_year)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was christened in %(month_year)s%(endnotes)s."), - _("This person was christened in %(month_year)s%(endnotes)s."), + _("%(male_name)s was christened in %(month_year)s%(endnotes)s."), + _("He was christened in %(month_year)s%(endnotes)s."), ], - 'succinct' : _("Christened %(month_year)s%(endnotes)s."), + Person.FEMALE: [ + _("%(female_name)s was christened in %(month_year)s%(endnotes)s."), + _("She was christened in %(month_year)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was christened in %(month_year)s%(endnotes)s."), + _("This person was christened in %(month_year)s%(endnotes)s."), + ], + 'succinct' : _("Christened %(month_year)s%(endnotes)s."), } christened_modified_date_place = { Person.MALE: [ - _("%(male_name)s was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), - _("He was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), - _("She was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), - _("This person was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), + _("%(male_name)s was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), + _("He was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), ], - 'succinct' : _("Christened %(modified_date)s in %(christening_place)s%(endnotes)s."), + Person.FEMALE: [ + _("%(female_name)s was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), + _("She was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), + _("This person was christened %(modified_date)s in %(christening_place)s%(endnotes)s."), + ], + 'succinct' : _("Christened %(modified_date)s in %(christening_place)s%(endnotes)s."), } christened_modified_date_no_place = { Person.MALE: [ - _("%(male_name)s was christened %(modified_date)s%(endnotes)s."), - _("He was christened %(modified_date)s%(endnotes)s."), - ], - Person.FEMALE: [ - _("%(female_name)s was christened %(modified_date)s%(endnotes)s."), - _("She was christened %(modified_date)s%(endnotes)s."), - ], - Person.UNKNOWN: [ - _("%(unknown_gender_name)s was christened %(modified_date)s%(endnotes)s."), - _("This person was christened %(modified_date)s%(endnotes)s."), + _("%(male_name)s was christened %(modified_date)s%(endnotes)s."), + _("He was christened %(modified_date)s%(endnotes)s."), ], - 'succinct' : _("Christened %(modified_date)s%(endnotes)s."), + Person.FEMALE: [ + _("%(female_name)s was christened %(modified_date)s%(endnotes)s."), + _("She was christened %(modified_date)s%(endnotes)s."), + ], + Person.UNKNOWN: [ + _("%(unknown_gender_name)s was christened %(modified_date)s%(endnotes)s."), + _("This person was christened %(modified_date)s%(endnotes)s."), + ], + 'succinct' : _("Christened %(modified_date)s%(endnotes)s."), } christened_no_date_place = { Person.MALE : [ - _("%(male_name)s was christened in %(christening_place)s%(endnotes)s."), - _("He was christened in %(christening_place)s%(endnotes)s."), - ], - Person.FEMALE : [ - _("%(female_name)s was christened in %(christening_place)s%(endnotes)s."), - _("She was christened in %(christening_place)s%(endnotes)s."), - ], - Person.UNKNOWN : [ - _("%(unknown_gender_name)s was christened in %(christening_place)s%(endnotes)s."), - _("This person was christened in %(christening_place)s%(endnotes)s."), + _("%(male_name)s was christened in %(christening_place)s%(endnotes)s."), + _("He was christened in %(christening_place)s%(endnotes)s."), ], - 'succinct' : _("Christened in %(christening_place)s%(endnotes)s."), + Person.FEMALE : [ + _("%(female_name)s was christened in %(christening_place)s%(endnotes)s."), + _("She was christened in %(christening_place)s%(endnotes)s."), + ], + Person.UNKNOWN : [ + _("%(unknown_gender_name)s was christened in %(christening_place)s%(endnotes)s."), + _("This person was christened in %(christening_place)s%(endnotes)s."), + ], + 'succinct' : _("Christened in %(christening_place)s%(endnotes)s."), } christened_no_date_no_place = { Person.MALE : [ - _("%(male_name)s was christened%(endnotes)s."), - _("He was christened%(endnotes)s."), - ], + _("%(male_name)s was christened%(endnotes)s."), + _("He was christened%(endnotes)s."), + ], Person.FEMALE : [ - _("%(female_name)s was christened%(endnotes)s."), - _("She was christened%(endnotes)s."), - ], + _("%(female_name)s was christened%(endnotes)s."), + _("She was christened%(endnotes)s."), + ], Person.UNKNOWN : [ - _("%(unknown_gender_name)s was christened%(endnotes)s."), - _("This person was christened%(endnotes)s."), + _("%(unknown_gender_name)s was christened%(endnotes)s."), + _("This person was christened%(endnotes)s."), ], 'succinct' : _("Christened%(endnotes)s."), } @@ -858,109 +858,109 @@ christened_no_date_no_place = { child_father_mother = { Person.UNKNOWN: [ [ - _("%(male_name)s is the child of %(father)s and %(mother)s."), - _("%(male_name)s was the child of %(father)s and %(mother)s."), + _("%(male_name)s is the child of %(father)s and %(mother)s."), + _("%(male_name)s was the child of %(father)s and %(mother)s."), ], [ - _("This person is the child of %(father)s and %(mother)s."), - _("This person was the child of %(father)s and %(mother)s."), - ], - _("Child of %(father)s and %(mother)s."), - ], + _("This person is the child of %(father)s and %(mother)s."), + _("This person was the child of %(father)s and %(mother)s."), + ], + _("Child of %(father)s and %(mother)s."), + ], Person.MALE : [ [ - _("%(male_name)s is the son of %(father)s and %(mother)s."), - _("%(male_name)s was the son of %(father)s and %(mother)s."), + _("%(male_name)s is the son of %(father)s and %(mother)s."), + _("%(male_name)s was the son of %(father)s and %(mother)s."), ], [ - _("He is the son of %(father)s and %(mother)s."), - _("He was the son of %(father)s and %(mother)s."), - ], + _("He is the son of %(father)s and %(mother)s."), + _("He was the son of %(father)s and %(mother)s."), + ], _("Son of %(father)s and %(mother)s."), - ], + ], Person.FEMALE : [ [ - _("%(female_name)s is the daughter of %(father)s and %(mother)s."), - _("%(female_name)s was the daughter of %(father)s and %(mother)s."), + _("%(female_name)s is the daughter of %(father)s and %(mother)s."), + _("%(female_name)s was the daughter of %(father)s and %(mother)s."), ], [ - _("She is the daughter of %(father)s and %(mother)s."), - _("She was the daughter of %(father)s and %(mother)s."), - ], - _("Daughter of %(father)s and %(mother)s."), + _("She is the daughter of %(father)s and %(mother)s."), + _("She was the daughter of %(father)s and %(mother)s."), + ], + _("Daughter of %(father)s and %(mother)s."), ] } child_father = { Person.UNKNOWN : [ [ - _("%(male_name)s is the child of %(father)s."), - _("%(male_name)s was the child of %(father)s."), + _("%(male_name)s is the child of %(father)s."), + _("%(male_name)s was the child of %(father)s."), ], [ - _("This person is the child of %(father)s."), - _("This person was the child of %(father)s."), - ], - _("Child of %(father)s."), - ], + _("This person is the child of %(father)s."), + _("This person was the child of %(father)s."), + ], + _("Child of %(father)s."), + ], Person.MALE : [ [ - _("%(male_name)s is the son of %(father)s."), - _("%(male_name)s was the son of %(father)s."), + _("%(male_name)s is the son of %(father)s."), + _("%(male_name)s was the son of %(father)s."), ], [ - _("He is the son of %(father)s."), - _("He was the son of %(father)s."), - ], - _("Son of %(father)s."), - ], + _("He is the son of %(father)s."), + _("He was the son of %(father)s."), + ], + _("Son of %(father)s."), + ], Person.FEMALE : [ [ - _("%(female_name)s is the daughter of %(father)s."), - _("%(female_name)s was the daughter of %(father)s."), + _("%(female_name)s is the daughter of %(father)s."), + _("%(female_name)s was the daughter of %(father)s."), ], [ - _("She is the daughter of %(father)s."), - _("She was the daughter of %(father)s."), - ], - _("Daughter of %(father)s."), - ], + _("She is the daughter of %(father)s."), + _("She was the daughter of %(father)s."), + ], + _("Daughter of %(father)s."), + ], } child_mother = { Person.UNKNOWN : [ [ - _("%(male_name)s is the child of %(mother)s."), - _("%(male_name)s was the child of %(mother)s."), + _("%(male_name)s is the child of %(mother)s."), + _("%(male_name)s was the child of %(mother)s."), ], [ - _("This person is the child of %(mother)s."), - _("This person was the child of %(mother)s."), - ], - _("Child of %(mother)s."), - ], + _("This person is the child of %(mother)s."), + _("This person was the child of %(mother)s."), + ], + _("Child of %(mother)s."), + ], Person.MALE : [ [ - _("%(male_name)s is the son of %(mother)s."), - _("%(male_name)s was the son of %(mother)s."), + _("%(male_name)s is the son of %(mother)s."), + _("%(male_name)s was the son of %(mother)s."), ], [ - _("He is the son of %(mother)s."), - _("He was the son of %(mother)s."), - ], - _("Son of %(mother)s."), - ], + _("He is the son of %(mother)s."), + _("He was the son of %(mother)s."), + ], + _("Son of %(mother)s."), + ], Person.FEMALE : [ [ - _("%(female_name)s is the daughter of %(mother)s."), - _("%(female_name)s was the daughter of %(mother)s."), + _("%(female_name)s is the daughter of %(mother)s."), + _("%(female_name)s was the daughter of %(mother)s."), ], [ - _("She is the daughter of %(mother)s."), - _("She was the daughter of %(mother)s."), - ], - _("Daughter of %(mother)s."), - ], + _("She is the daughter of %(mother)s."), + _("She was the daughter of %(mother)s."), + ], + _("Daughter of %(mother)s."), + ], } #------------------------------------------------------------------------ @@ -970,122 +970,122 @@ child_mother = { #------------------------------------------------------------------------ marriage_first_date_place = { Person.UNKNOWN : [ - _('This person married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('This person married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('This person married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('This person married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('This person married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('This person married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.MALE : [ - _('He married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('He married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('He married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('He married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('He married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('He married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('She married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('She married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + _('She married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('She married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('She married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), ], 'succinct' : [ _('Married %(spouse)s %(partial_date)s in %(place)s%(endnotes)s.'), _('Married %(spouse)s %(full_date)s in %(place)s%(endnotes)s.'), _('Married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + ], } marriage_also_date_place = { Person.UNKNOWN : [ - _('This person also married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('This person also married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('This person also married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('This person also married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('This person also married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('This person also married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.MALE : [ - _('He also married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('He also married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('He also married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('He also married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('He also married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('He also married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She also married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('She also married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('She also married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + _('She also married %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('She also married %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('She also married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), ], 'succinct' : [ _('Also married %(spouse)s %(partial_date)s in %(place)s%(endnotes)s.'), _('Also married %(spouse)s %(full_date)s in %(place)s%(endnotes)s.'), _('Also married %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + ], } marriage_first_date = { Person.UNKNOWN : [ - _('This person married %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('This person married %(spouse)s on %(full_date)s%(endnotes)s.'), - _('This person married %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('This person married %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('This person married %(spouse)s on %(full_date)s%(endnotes)s.'), + _('This person married %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.MALE : [ - _('He married %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('He married %(spouse)s on %(full_date)s%(endnotes)s.'), - _('He married %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('He married %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('He married %(spouse)s on %(full_date)s%(endnotes)s.'), + _('He married %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She married %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('She married %(spouse)s on %(full_date)s%(endnotes)s.'), - _('She married %(spouse)s %(modified_date)s%(endnotes)s.'), + _('She married %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('She married %(spouse)s on %(full_date)s%(endnotes)s.'), + _('She married %(spouse)s %(modified_date)s%(endnotes)s.'), ], 'succinct' : [ _('Married %(spouse)s %(partial_date)s%(endnotes)s.'), _('Married %(spouse)s %(full_date)s%(endnotes)s.'), _('Married %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + ], } marriage_also_date = { Person.UNKNOWN : [ - _('This person also married %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('This person also married %(spouse)s on %(full_date)s%(endnotes)s.'), - _('This person also married %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('This person also married %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('This person also married %(spouse)s on %(full_date)s%(endnotes)s.'), + _('This person also married %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.MALE : [ - _('He also married %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('He also married %(spouse)s on %(full_date)s%(endnotes)s.'), - _('He also married %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('He also married %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('He also married %(spouse)s on %(full_date)s%(endnotes)s.'), + _('He also married %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She also married %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('She also married %(spouse)s on %(full_date)s%(endnotes)s.'), - _('She also married %(spouse)s %(modified_date)s%(endnotes)s.'), + _('She also married %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('She also married %(spouse)s on %(full_date)s%(endnotes)s.'), + _('She also married %(spouse)s %(modified_date)s%(endnotes)s.'), ], 'succinct' : [ _('Also married %(spouse)s %(partial_date)s%(endnotes)s.'), _('Also married %(spouse)s %(full_date)s%(endnotes)s.'), _('Also married %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + ], } marriage_first_place = { - Person.UNKNOWN : _('This person married %(spouse)s in %(place)s%(endnotes)s.'), - Person.MALE : _('He married %(spouse)s in %(place)s%(endnotes)s.'), + Person.UNKNOWN : _('This person married %(spouse)s in %(place)s%(endnotes)s.'), + Person.MALE : _('He married %(spouse)s in %(place)s%(endnotes)s.'), Person.FEMALE : _('She married %(spouse)s in %(place)s%(endnotes)s.'), - 'succinct' : _('Married %(spouse)s in %(place)s%(endnotes)s.'), + 'succinct' : _('Married %(spouse)s in %(place)s%(endnotes)s.'), } marriage_also_place = { - Person.UNKNOWN : _('This person also married %(spouse)s in %(place)s%(endnotes)s.'), - Person.MALE : _('He also married %(spouse)s in %(place)s%(endnotes)s.'), + Person.UNKNOWN : _('This person also married %(spouse)s in %(place)s%(endnotes)s.'), + Person.MALE : _('He also married %(spouse)s in %(place)s%(endnotes)s.'), Person.FEMALE : _('She also married %(spouse)s in %(place)s%(endnotes)s.'), - 'succinct' : _('Also married %(spouse)s in %(place)s%(endnotes)s.'), + 'succinct' : _('Also married %(spouse)s in %(place)s%(endnotes)s.'), } marriage_first_only = { - Person.UNKNOWN : _('This person married %(spouse)s%(endnotes)s.'), - Person.MALE : _('He married %(spouse)s%(endnotes)s.'), + Person.UNKNOWN : _('This person married %(spouse)s%(endnotes)s.'), + Person.MALE : _('He married %(spouse)s%(endnotes)s.'), Person.FEMALE : _('She married %(spouse)s%(endnotes)s.'), - 'succinct' : _('Married %(spouse)s%(endnotes)s.'), + 'succinct' : _('Married %(spouse)s%(endnotes)s.'), } marriage_also_only = { - Person.UNKNOWN : _('This person also married %(spouse)s%(endnotes)s.'), - Person.MALE : _('He also married %(spouse)s%(endnotes)s.'), + Person.UNKNOWN : _('This person also married %(spouse)s%(endnotes)s.'), + Person.MALE : _('He also married %(spouse)s%(endnotes)s.'), Person.FEMALE : _('She also married %(spouse)s%(endnotes)s.'), - 'succinct' : _('Also married %(spouse)s%(endnotes)s.'), + 'succinct' : _('Also married %(spouse)s%(endnotes)s.'), } #------------------------------------------------------------------------ @@ -1095,122 +1095,122 @@ marriage_also_only = { #------------------------------------------------------------------------ unmarried_first_date_place = { Person.UNKNOWN : [ - _('This person had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('This person had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('This person had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('This person had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('This person had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('This person had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.MALE : [ - _('He had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('He had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('He had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('He had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('He had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('He had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('She had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('She had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + _('She had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('She had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('She had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), ], 'succinct' : [ _('Unmarried relationship with %(spouse)s %(partial_date)s in %(place)s%(endnotes)s.'), _('Unmarried relationship with %(spouse)s %(full_date)s in %(place)s%(endnotes)s.'), _('Unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + ], } unmarried_also_date_place = { Person.UNKNOWN : [ - _('This person also had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('This person also had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('This person also had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('This person also had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('This person also had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('This person also had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.MALE : [ - _('He also had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('He also had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('He also had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('He also had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('He also had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('He also had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She also had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('She also had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('She also had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + _('She also had an unmarried relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('She also had an unmarried relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('She also had an unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), ], 'succinct' : [ _('Unmarried relationship with %(spouse)s %(partial_date)s in %(place)s%(endnotes)s.'), _('Unmarried relationship with %(spouse)s %(full_date)s in %(place)s%(endnotes)s.'), _('Unmarried relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + ], } unmarried_first_date = { Person.UNKNOWN : [ - _('This person had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('This person had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('This person had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('This person had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('This person had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('This person had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.MALE : [ - _('He had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('He had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('He had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('He had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('He had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('He had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('She had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('She had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + _('She had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('She had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('She had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), ], 'succinct' : [ _('Unmarried relationship with %(spouse)s %(partial_date)s%(endnotes)s.'), _('Unmarried relationship with %(spouse)s %(full_date)s%(endnotes)s.'), _('Unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + ], } unmarried_also_date = { Person.UNKNOWN : [ - _('This person also had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('This person also had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('This person also had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('This person also had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('This person also had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('This person also had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.MALE : [ - _('He also had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('He also had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('He also had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('He also had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('He also had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('He also had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She also had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('She also had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('She also had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + _('She also had an unmarried relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('She also had an unmarried relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('She also had an unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), ], 'succinct' : [ _('Also unmarried relationship with %(spouse)s %(partial_date)s%(endnotes)s.'), _('Also unmarried relationship with %(spouse)s %(full_date)s%(endnotes)s.'), _('Also unmarried relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + ], } unmarried_first_place = { - Person.UNKNOWN : _('This person had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), - Person.MALE : _('He had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), - Person.FEMALE : _('She had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), - 'succinct' : _('Unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.UNKNOWN : _('This person had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.MALE : _('He had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.FEMALE : _('She had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), + 'succinct' : _('Unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), } unmarried_also_place = { - Person.UNKNOWN : _('This person also had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), - Person.MALE : _('He also had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), - Person.FEMALE : _('She also had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), - 'succinct' : _('Unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.UNKNOWN : _('This person also had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.MALE : _('He also had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.FEMALE : _('She also had an unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), + 'succinct' : _('Unmarried relationship with %(spouse)s in %(place)s%(endnotes)s.'), } unmarried_first_only = { - Person.UNKNOWN : _('This person had an unmarried relationship with %(spouse)s%(endnotes)s.'), - Person.MALE : _('He had an unmarried relationship with %(spouse)s%(endnotes)s.'), + Person.UNKNOWN : _('This person had an unmarried relationship with %(spouse)s%(endnotes)s.'), + Person.MALE : _('He had an unmarried relationship with %(spouse)s%(endnotes)s.'), Person.FEMALE : _('She had an unmarried relationship with %(spouse)s%(endnotes)s.'), - 'succinct' : _('Unmarried relationship with %(spouse)s%(endnotes)s.'), + 'succinct' : _('Unmarried relationship with %(spouse)s%(endnotes)s.'), } unmarried_also_only = { - Person.UNKNOWN : _('This person also had an unmarried relationship with %(spouse)s%(endnotes)s.'), - Person.MALE : _('He also had an unmarried relationship with %(spouse)s%(endnotes)s.'), - Person.FEMALE : _('She also had an unmarried relationship with %(spouse)s%(endnotes)s.'), - 'succinct' : _('Unmarried relationship with %(spouse)s%(endnotes)s.'), + Person.UNKNOWN : _('This person also had an unmarried relationship with %(spouse)s%(endnotes)s.'), + Person.MALE : _('He also had an unmarried relationship with %(spouse)s%(endnotes)s.'), + Person.FEMALE : _('She also had an unmarried relationship with %(spouse)s%(endnotes)s.'), + 'succinct' : _('Unmarried relationship with %(spouse)s%(endnotes)s.'), } #------------------------------------------------------------------------ @@ -1221,122 +1221,122 @@ unmarried_also_only = { #------------------------------------------------------------------------ relationship_first_date_place = { Person.UNKNOWN : [ - _('This person had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('This person had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('This person had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('This person had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('This person had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('This person had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.MALE : [ - _('He had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('He had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('He had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('He had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('He had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('He had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('She had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('She had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + _('She had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('She had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('She had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), ], 'succinct' : [ _('Relationship with %(spouse)s %(partial_date)s in %(place)s%(endnotes)s.'), _('Relationship with %(spouse)s %(full_date)s in %(place)s%(endnotes)s.'), _('Relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + ], } relationship_also_date_place = { Person.UNKNOWN : [ - _('This person also had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('This person also had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('This person also had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('This person also had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('This person also had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('This person also had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.MALE : [ - _('He also had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('He also had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('He also had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + _('He also had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('He also had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('He also had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She also had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), - _('She also had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), - _('She also had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), + _('She also had a relationship with %(spouse)s in %(partial_date)s in %(place)s%(endnotes)s.'), + _('She also had a relationship with %(spouse)s on %(full_date)s in %(place)s%(endnotes)s.'), + _('She also had a relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), ], 'succinct' : [ _('Also relationship with %(spouse)s %(partial_date)s in %(place)s%(endnotes)s.'), _('Also relationship with %(spouse)s %(full_date)s in %(place)s%(endnotes)s.'), _('Also relationship with %(spouse)s %(modified_date)s in %(place)s%(endnotes)s.'), - ], + ], } relationship_first_date = { Person.UNKNOWN : [ - _('This person had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('This person had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('This person had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('This person had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('This person had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('This person had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.MALE : [ - _('He had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('He had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('He had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('He had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('He had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('He had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('She had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('She had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + _('She had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('She had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('She had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), ], 'succinct' : [ _('Relationship with %(spouse)s %(partial_date)s%(endnotes)s.'), _('Relationship with %(spouse)s %(full_date)s%(endnotes)s.'), _('Relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + ], } relationship_also_date = { Person.UNKNOWN : [ - _('This person also had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('This person also had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('This person also had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('This person also had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('This person also had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('This person also had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.MALE : [ - _('He also had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('He also had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('He also had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + _('He also had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('He also had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('He also had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + ], Person.FEMALE : [ - _('She also had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), - _('She also had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), - _('She also had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), + _('She also had a relationship with %(spouse)s in %(partial_date)s%(endnotes)s.'), + _('She also had a relationship with %(spouse)s on %(full_date)s%(endnotes)s.'), + _('She also had a relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), ], 'succinct' : [ _('Also relationship with %(spouse)s %(partial_date)s%(endnotes)s.'), _('Also relationship with %(spouse)s %(full_date)s%(endnotes)s.'), _('Also relationship with %(spouse)s %(modified_date)s%(endnotes)s.'), - ], + ], } relationship_first_place = { - Person.UNKNOWN : _('This person had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), - Person.MALE : _('He had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), - Person.FEMALE : _('She had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), - 'succinct' : _('Relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.UNKNOWN : _('This person had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.MALE : _('He had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.FEMALE : _('She had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), + 'succinct' : _('Relationship with %(spouse)s in %(place)s%(endnotes)s.'), } relationship_also_place = { - Person.UNKNOWN : _('This person also had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), - Person.MALE : _('He also had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), - Person.FEMALE : _('She also had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), - 'succinct' : _('Also relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.UNKNOWN : _('This person also had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.MALE : _('He also had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), + Person.FEMALE : _('She also had a relationship with %(spouse)s in %(place)s%(endnotes)s.'), + 'succinct' : _('Also relationship with %(spouse)s in %(place)s%(endnotes)s.'), } relationship_first_only = { - Person.UNKNOWN : _('This person had a relationship with %(spouse)s%(endnotes)s.'), - Person.MALE : _('He had a relationship with %(spouse)s%(endnotes)s.'), + Person.UNKNOWN : _('This person had a relationship with %(spouse)s%(endnotes)s.'), + Person.MALE : _('He had a relationship with %(spouse)s%(endnotes)s.'), Person.FEMALE : _('She had a relationship with %(spouse)s%(endnotes)s.'), - 'succinct' : _('Relationship with %(spouse)s%(endnotes)s.'), + 'succinct' : _('Relationship with %(spouse)s%(endnotes)s.'), } relationship_also_only = { - Person.UNKNOWN : _('This person also had a relationship with %(spouse)s%(endnotes)s.'), - Person.MALE : _('He also had a relationship with %(spouse)s%(endnotes)s.'), - Person.FEMALE : _('She also had a relationship with %(spouse)s%(endnotes)s.'), - 'succinct' : _('Also relationship with %(spouse)s%(endnotes)s.'), + Person.UNKNOWN : _('This person also had a relationship with %(spouse)s%(endnotes)s.'), + Person.MALE : _('He also had a relationship with %(spouse)s%(endnotes)s.'), + Person.FEMALE : _('She also had a relationship with %(spouse)s%(endnotes)s.'), + 'succinct' : _('Also relationship with %(spouse)s%(endnotes)s.'), } #------------------------------------------------------------------------ @@ -1345,18 +1345,18 @@ relationship_also_only = { # #------------------------------------------------------------------------ class Narrator(object): - """ + """ Narrator is a class which provides narration text. """ def __init__(self, dbase, verbose=True, - use_call_name=False, use_fulldate=False, + use_call_name=False, use_fulldate=False, empty_date="", empty_place="", nlocale=glocale, get_endnote_numbers=_get_empty_endnote_numbers): - """ + """ Initialize the narrator class. - + If nlocale is passed in (a GrampsLocale), then the translated values will be returned instead. @@ -1364,23 +1364,23 @@ class Narrator(object): :type dbase: :class:`~gen.db.base,DbBase` :param verbose: Specifies whether complete sentences should be used. :type verbose: bool - :param use_call_name: Specifies whether a person's call name should be + :param use_call_name: Specifies whether a person's call name should be used for the first name. :type use_call_name: bool :param empty_date: String to use when a date is not known. :type empty_date: str :param empty_place: String to use when a place is not known. :type empty_place: str - :param get_endnote_numbers: A callable to use for getting a string - representing endnote numbers. + :param get_endnote_numbers: A callable to use for getting a string + representing endnote numbers. The function takes a :class:`~gen.lib.CitationBase` instance. - A typical return value from get_endnote_numbers() would be "2a" and + A typical return value from get_endnote_numbers() would be "2a" and would represent a reference to an endnote in a document. - :type get_endnote_numbers: + :type get_endnote_numbers: callable( :class:`~gen.lib.CitationBase` ) :param nlocale: allow deferred translation of dates and strings :type nlocale: a GrampsLocale instance - """ + """ self.__db = dbase self.__verbose = verbose self.__use_call = use_call_name @@ -1398,14 +1398,14 @@ class Narrator(object): def set_subject(self, person): """ - Start a new story about this person. The person's first name will be - used in the first sentence. A pronoun will be used as the subject for + Start a new story about this person. The person's first name will be + used in the first sentence. A pronoun will be used as the subject for each subsequent sentence. :param person: The person to be the subject of the story. :type person: :class:`~gen.lib.person,Person` - """ + """ self.__person = person - + if self.__use_call and person.get_primary_name().get_call_name(): self.__first_name = person.get_primary_name().get_call_name() else: @@ -1417,14 +1417,14 @@ class Narrator(object): self.__first_name_used = True # but use a pronoun if no name def get_born_string(self): - """ + """ Get a string narrating the birth of the subject. Example sentences: Person was born on Date. Person was born on Date in Place. Person was born in Place. '' - + :returns: A sentence about the subject's birth. :rtype: unicode """ @@ -1433,15 +1433,15 @@ class Narrator(object): self.__first_name_used = True else: name_index = _NAME_INDEX_EXCLUDE_NAME - + text = "" - + bplace = self.__empty_place bdate = self.__empty_date birth_event = None bdate_full = False bdate_mod = False - + birth_ref = self.__person.get_birth_ref() if birth_ref and birth_ref.ref: birth_event = self.__db.get_event_from_handle(birth_ref.ref) @@ -1458,20 +1458,20 @@ class Narrator(object): bdate_full = bdate_obj and bdate_obj.get_day_valid() bdate_mod = bdate_obj and \ bdate_obj.get_modifier() != Date.MOD_NONE - + value_map = { - 'name' : self.__first_name, - 'male_name' : self.__first_name, - 'unknown_gender_name' : self.__first_name, - 'female_name' : self.__first_name, - 'birth_date' : bdate, - 'birth_place' : bplace, - 'month_year' : bdate, - 'modified_date' : bdate, + 'name' : self.__first_name, + 'male_name' : self.__first_name, + 'unknown_gender_name' : self.__first_name, + 'female_name' : self.__first_name, + 'birth_date' : bdate, + 'birth_place' : bplace, + 'month_year' : bdate, + 'modified_date' : bdate, } - + gender = self.__person.get_gender() - + if bdate: if bdate_mod: if bplace and self.__verbose: @@ -1507,16 +1507,16 @@ class Narrator(object): text = born_no_date_with_place[2] else: text = "" - + if text: text = self.__translate_text(text) % value_map - + if birth_event: text = text.rstrip(". ") text = text + self.__get_endnote_numbers(birth_event) + ". " text = text + " " - + return text def get_died_string(self, include_age=False): @@ -1532,19 +1532,19 @@ class Narrator(object): Person died '' where 'age' string is an advanced age calculation. - + :returns: A sentence about the subject's death. :rtype: unicode """ - + if not self.__first_name_used: name_index = _NAME_INDEX_INCLUDE_NAME self.__first_name_used = True else: name_index = _NAME_INDEX_EXCLUDE_NAME - + text = "" - + dplace = self.__empty_place ddate = self.__empty_date death_event = None @@ -1567,27 +1567,27 @@ class Narrator(object): ddate_full = ddate_obj and ddate_obj.get_day_valid() ddate_mod = ddate_obj and \ ddate_obj.get_modifier() != Date.MOD_NONE - - if include_age: + + if include_age: age, age_index = self.__get_age_at_death() else: age = 0 age_index = _AGE_INDEX_NO_AGE value_map = { - 'name' : self.__first_name, - 'unknown_gender_name' : self.__first_name, - 'male_name' : self.__first_name, - 'female_name' : self.__first_name, - 'death_date' : ddate, - 'modified_date' : ddate, - 'death_place' : dplace, - 'age' : age, - 'month_year' : ddate, + 'name' : self.__first_name, + 'unknown_gender_name' : self.__first_name, + 'male_name' : self.__first_name, + 'female_name' : self.__first_name, + 'death_date' : ddate, + 'modified_date' : ddate, + 'death_place' : dplace, + 'age' : age, + 'month_year' : ddate, } - + gender = self.__person.get_gender() - + if ddate and ddate_mod: if dplace and self.__verbose: text = died_modified_date_with_place[name_index][gender][age_index] @@ -1623,20 +1623,20 @@ class Narrator(object): text = died_no_date_no_place[name_index][gender][age_index] else: text = died_no_date_no_place[2][age_index] - + if text: text = self.__translate_text(text) % value_map - + if death_event: text = text.rstrip(". ") text = text + self.__get_endnote_numbers(death_event) + ". " - + text = text + " " - + return text def get_buried_string(self): - """ + """ Get a string narrating the burial of the subject. Example sentences: Person was buried on Date. @@ -1645,26 +1645,26 @@ class Narrator(object): Person was buried in Month_Year in Place. Person was buried in Place. '' - + :returns: A sentence about the subject's burial. :rtype: unicode """ - + if not self.__first_name_used: name_index = _NAME_INDEX_INCLUDE_NAME self.__first_name_used = True else: name_index = _NAME_INDEX_EXCLUDE_NAME - + gender = self.__person.get_gender() - + text = "" - + bplace = self.__empty_place bdate = self.__empty_date bdate_full = False bdate_mod = False - + burial = None for event_ref in self.__person.get_event_ref_list(): event = self.__db.get_event_from_handle(event_ref.ref) @@ -1672,7 +1672,7 @@ class Narrator(object): and event_ref.role.value == EventRoleType.PRIMARY: burial = event break - + if burial: if self.__use_fulldate : bdate = self.__get_date(burial.get_date_object()) @@ -1687,19 +1687,19 @@ class Narrator(object): bdate_mod = bdate_obj and bdate_obj.get_modifier() != Date.MOD_NONE else: return text - + value_map = { - 'unknown_gender_name' : self.__first_name, - 'male_name' : self.__first_name, - 'name' : self.__first_name, - 'female_name' : self.__first_name, - 'burial_date' : bdate, - 'burial_place' : bplace, - 'month_year' : bdate, + 'unknown_gender_name' : self.__first_name, + 'male_name' : self.__first_name, + 'name' : self.__first_name, + 'female_name' : self.__first_name, + 'burial_date' : bdate, + 'burial_place' : bplace, + 'month_year' : bdate, 'modified_date' : bdate, - 'endnotes' : self.__get_endnote_numbers(event), + 'endnotes' : self.__get_endnote_numbers(event), } - + if bdate and bdate_mod and self.__verbose: if bplace: #male, date, place text = buried_modified_date_place[gender][name_index] @@ -1738,15 +1738,15 @@ class Narrator(object): text = buried_no_date_no_place[gender][name_index] else: #male, no date, no place text = buried_no_date_no_place['succinct'] - + if text: text = self.__translate_text(text) % value_map text = text + " " - + return text def get_baptised_string(self): - """ + """ Get a string narrating the baptism of the subject. Example sentences: Person was baptized on Date. @@ -1755,7 +1755,7 @@ class Narrator(object): Person was baptized in Month_Year in Place. Person was baptized in Place. '' - + :returns: A sentence about the subject's baptism. :rtype: unicode """ @@ -1765,16 +1765,16 @@ class Narrator(object): self.__first_name_used = True else: name_index = _NAME_INDEX_EXCLUDE_NAME - + gender = self.__person.get_gender() - + text = "" - + bplace = self.__empty_place bdate = self.__empty_date bdate_full = False bdate_mod = False - + baptism = None for event_ref in self.__person.get_event_ref_list(): event = self.__db.get_event_from_handle(event_ref.ref) @@ -1782,7 +1782,7 @@ class Narrator(object): and event_ref.role.value == EventRoleType.PRIMARY: baptism = event break - + if baptism: if self.__use_fulldate : bdate = self.__get_date(baptism.get_date_object()) @@ -1797,19 +1797,19 @@ class Narrator(object): bdate_mod = bdate_obj and bdate_obj.get_modifier() != Date.MOD_NONE else: return text - + value_map = { - 'unknown_gender_name' : self.__first_name, - 'male_name' : self.__first_name, - 'name' : self.__first_name, - 'female_name' : self.__first_name, - 'baptism_date' : bdate, - 'baptism_place' : bplace, - 'month_year' : bdate, + 'unknown_gender_name' : self.__first_name, + 'male_name' : self.__first_name, + 'name' : self.__first_name, + 'female_name' : self.__first_name, + 'baptism_date' : bdate, + 'baptism_place' : bplace, + 'month_year' : bdate, 'modified_date' : bdate, - 'endnotes' : self.__get_endnote_numbers(event), + 'endnotes' : self.__get_endnote_numbers(event), } - + if bdate and bdate_mod and self.__verbose: if bplace: #male, date, place text = baptised_modified_date_place[gender][name_index] @@ -1848,15 +1848,15 @@ class Narrator(object): text = baptised_no_date_no_place[gender][name_index] else: #male, no date, no place text = baptised_no_date_no_place['succinct'] - + if text: text = self.__translate_text(text) % value_map text = text + " " - + return text def get_christened_string(self): - """ + """ Get a string narrating the christening of the subject. Example sentences: Person was christened on Date. @@ -1875,16 +1875,16 @@ class Narrator(object): self.__first_name_used = True else: name_index = _NAME_INDEX_EXCLUDE_NAME - + gender = self.__person.get_gender() - + text = "" - + cplace = self.__empty_place cdate = self.__empty_date cdate_full = False cdate_mod = False - + christening = None for event_ref in self.__person.get_event_ref_list(): event = self.__db.get_event_from_handle(event_ref.ref) @@ -1892,7 +1892,7 @@ class Narrator(object): and event_ref.role.value == EventRoleType.PRIMARY: christening = event break - + if christening: if self.__use_fulldate : cdate = self.__get_date(christening.get_date_object()) @@ -1907,19 +1907,19 @@ class Narrator(object): cdate_mod = cdate_obj and cdate_obj.get_modifier() != Date.MOD_NONE else: return text - + value_map = { - 'unknown_gender_name' : self.__first_name, - 'male_name' : self.__first_name, - 'name' : self.__first_name, - 'female_name' : self.__first_name, - 'christening_date' : cdate, - 'christening_place' : cplace, - 'month_year' : cdate, + 'unknown_gender_name' : self.__first_name, + 'male_name' : self.__first_name, + 'name' : self.__first_name, + 'female_name' : self.__first_name, + 'christening_date' : cdate, + 'christening_place' : cplace, + 'month_year' : cdate, 'modified_date' : cdate, - 'endnotes' : self.__get_endnote_numbers(event), + 'endnotes' : self.__get_endnote_numbers(event), } - + if cdate and cdate_mod and self.__verbose: if cplace: #male, date, place text = christened_modified_date_place[gender][name_index] @@ -1958,11 +1958,11 @@ class Narrator(object): text = christened_no_date_no_place[gender][name_index] else: #male, no date, no place text = christened_no_date_no_place['succinct'] - + if text: text = self.__translate_text(text) % value_map text = text + " " - + return text def get_married_string(self, family, is_first=True, name_display=None): @@ -1974,11 +1974,11 @@ class Narrator(object): Person was also married to Spouse on Date. Person was also married to Spouse. "" - + :param family: The family that contains the Spouse for this marriage. :type family: :class:`~gen.lib.family,Family` - :param is_first: Indicates whether this sentence represents the first - marriage. If it is not the first marriage, the sentence will + :param is_first: Indicates whether this sentence represents the first + marriage. If it is not the first marriage, the sentence will include "also". :type is_first: bool :param name_display: An object to be used for displaying names @@ -1986,7 +1986,7 @@ class Narrator(object): :returns: A sentence about the subject's marriage. :rtype: unicode """ - + spouse_handle = ReportUtils.find_spouse(self.__person, family) spouse = self.__db.get_person_from_handle(spouse_handle) event = ReportUtils.find_marriage(self.__db, family) @@ -2016,28 +2016,28 @@ class Narrator(object): place_obj = self.__db.get_place_from_handle(place_handle) place = _pd.display_event(self.__db, event) relationship = family.get_relationship() - + value_map = { - 'spouse' : spouse_name, - 'endnotes' : self.__get_endnote_numbers(event), - 'full_date' : date, - 'modified_date' : date, - 'partial_date' : date, - 'place' : place, + 'spouse' : spouse_name, + 'endnotes' : self.__get_endnote_numbers(event), + 'full_date' : date, + 'modified_date' : date, + 'partial_date' : date, + 'place' : place, } date_full = 0 if event: dobj = event.get_date_object() - + if dobj.get_modifier() != Date.MOD_NONE: date_full = 2 elif dobj and dobj.get_day_valid(): date_full = 1 - + gender = self.__person.get_gender() - + # This would be much simpler, excepting for translation considerations # Currently support FamilyRelType's: # MARRIED : civil and/or religious @@ -2046,11 +2046,11 @@ class Narrator(object): # UNKNOWN : also described as a relationship # CUSTOM : also described as a relationship # - # In the future, there may be a need to distinguish between + # In the future, there may be a need to distinguish between # CIVIL UNION, UNKNOWN and CUSTOM relationship types - # CUSTOM will be difficult as user can supply any arbitrary string to + # CUSTOM will be difficult as user can supply any arbitrary string to # describe type - + if is_first: if date and place and self.__verbose: if relationship == FamilyRelType.MARRIED: @@ -2165,7 +2165,7 @@ class Narrator(object): text = unmarried_also_only['succinct'] else: text = relationship_also_only['succinct'] - + if text: text = self.__translate_text(text) % value_map text = text + " " @@ -2179,7 +2179,7 @@ class Narrator(object): Person was the son of father_name and mother_name. Person was the daughter of father_name and mother_name. "" - + :param father_name: The name of the Subjects' father. :type father_name: unicode :param mother_name: The name of the Subjects' mother. @@ -2187,26 +2187,26 @@ class Narrator(object): :returns: A sentence about the subject's parents. :rtype: unicode """ - + value_map = { - 'father' : father_name, - 'mother' : mother_name, - 'male_name' : self.__first_name, - 'name' : self.__first_name, - 'female_name' : self.__first_name, - 'unknown_gender_name' : self.__first_name, + 'father' : father_name, + 'mother' : mother_name, + 'male_name' : self.__first_name, + 'name' : self.__first_name, + 'female_name' : self.__first_name, + 'unknown_gender_name' : self.__first_name, } - + dead = not probably_alive(self.__person, self.__db) - + if not self.__first_name_used: index = _NAME_INDEX_INCLUDE_NAME self.__first_name_used = True else: index = _NAME_INDEX_EXCLUDE_NAME - + gender = self.__person.get_gender() - + text = "" if mother_name and father_name and self.__verbose: text = child_father_mother[gender][index][dead] @@ -2220,17 +2220,17 @@ class Narrator(object): text = child_father[gender][index][dead] elif father_name: text = child_father[gender][2] - + if text: text = self.__translate_text(text) % value_map text = text + " " - + return text - + def __get_age_at_death(self): """ - Calculate the age the person died. - + Calculate the age the person died. + Returns a tuple representing (age, age_index). """ birth_ref = self.__person.get_birth_ref() @@ -2247,7 +2247,7 @@ class Narrator(object): death_year_valid = death.get_year_valid() else: death_year_valid = False - + # without at least a year for each event no age can be calculated if birth_year_valid and death_year_valid: span = death - birth @@ -2264,5 +2264,5 @@ class Narrator(object): else: age = 0 age_index = _AGE_INDEX_NO_AGE - + return age, age_index diff --git a/gramps/plugins/lib/libodfbackend.py b/gramps/plugins/lib/libodfbackend.py index bfa18600a..6cc47917b 100644 --- a/gramps/plugins/lib/libodfbackend.py +++ b/gramps/plugins/lib/libodfbackend.py @@ -72,7 +72,7 @@ class OdfBackend(DocBackend): """ Implementation for open document format docs """ - + STYLETAG_TO_PROPERTY = { } @@ -90,20 +90,20 @@ class OdfBackend(DocBackend): ] STYLETAG_MARKUP = { - DocBackend.BOLD : + DocBackend.BOLD : ("", ""), - DocBackend.ITALIC : + DocBackend.ITALIC : ("", ""), - DocBackend.UNDERLINE : + DocBackend.UNDERLINE : ("", ""), - DocBackend.SUPERSCRIPT : + DocBackend.SUPERSCRIPT : ("", ""), } - + ESCAPE_FUNC = lambda x: _escape def __init__(self, filename=None): @@ -111,7 +111,7 @@ class OdfBackend(DocBackend): @param filename: path name of the file the backend works on """ DocBackend.__init__(self, filename) - + def _create_xmltag(self, tagtype, value): """ overwrites the method in DocBackend @@ -125,7 +125,7 @@ class OdfBackend(DocBackend): # without the leading hash, this can be replaced when used in the text- # property font colour if ( tagtype == DocBackend.FONTCOLOR ): - return ('' % + return ('' % value.replace("#", ""), '') elif ( tagtype == DocBackend.FONTFACE ): @@ -136,7 +136,7 @@ class OdfBackend(DocBackend): return ('' % value, '') else: #elif ( tagtype == DocBackend.HIGHLIGHT ): - return ('' % + return ('' % value.replace("#", ""), '') @@ -147,6 +147,6 @@ class OdfBackend(DocBackend): if value.startswith("gramps://"): return self.STYLETAG_MARKUP[DocBackend.UNDERLINE] else: - return ('' % self.ESCAPE_FUNC()(value), + return ('' % self.ESCAPE_FUNC()(value), '') diff --git a/gramps/plugins/lib/libpersonview.py b/gramps/plugins/lib/libpersonview.py index d64ad6ca1..855b43a6c 100644 --- a/gramps/plugins/lib/libpersonview.py +++ b/gramps/plugins/lib/libpersonview.py @@ -120,7 +120,7 @@ class BasePersonView(ListView): COL_TAGS, COL_CHAN]), ('columns.size', [250, 75, 75, 100, 175, 100, 175, 100, 30, 30, 30, 30, 30, 100, 100]) - ) + ) ADD_MSG = _("Add a new person") EDIT_MSG = _("Edit the selected person") DEL_MSG = _("Remove the selected person") @@ -140,14 +140,14 @@ class BasePersonView(ListView): 'person-groupname-rebuild' : self.object_build, 'no-database': self.no_database, } - + ListView.__init__( self, title, pdata, dbstate, uistate, model, signal_map, PersonBookmarks, nav_group, multiple=True, filter_class=PersonSidebarFilter) - + self.func_list.update({ 'J' : self.jump, 'BackSpace' : self.key_delete, @@ -168,7 +168,7 @@ class BasePersonView(ListView): Specify the drag type for a single selection """ return DdTargets.PERSON_LINK - + def exact_search(self): """ Returns a tuple indicating columns requiring an exact search @@ -222,7 +222,7 @@ class BasePersonView(ListView): - + @@ -249,7 +249,7 @@ class BasePersonView(ListView): def get_handle_from_gramps_id(self, gid): """ - Return the handle of the person having the given Gramps ID. + Return the handle of the person having the given Gramps ID. """ obj = self.dbstate.db.get_person_from_gramps_id(gid) if obj: @@ -265,12 +265,12 @@ class BasePersonView(ListView): #the editor requires a surname person.primary_name.add_surname(Surname()) person.primary_name.set_primary_surname(0) - + try: EditPerson(self.dbstate, self.uistate, [], person) except WindowActiveError: pass - + def edit(self, obj): """ Edit an existing person in the database. @@ -293,21 +293,21 @@ class BasePersonView(ListView): msg2 = self._message2_format(person) msg2 = "%s %s" % (msg2, data_recover_msg) # This gets person to delete deom self.active_person: - QuestionDialog(msg1, - msg2, - _('_Delete Person'), + QuestionDialog(msg1, + msg2, + _('_Delete Person'), self.delete_person_response) else: # Ask to delete; option to cancel, delete rest # This gets person to delete from parameter MultiSelectDialog(self._message1_format, - self._message2_format, + self._message2_format, handles, self._lookup_person, yes_func=self.delete_person_response) # Yes def _message1_format(self, person): - return _('Delete %s?') % (name_displayer.display(person) + + return _('Delete %s?') % (name_displayer.display(person) + (" [%s]" % person.gramps_id)) def _message2_format(self, person): @@ -331,13 +331,13 @@ class BasePersonView(ListView): # create the transaction with DbTxn('', self.dbstate.db) as trans: - + # create name to save person = self.active_person active_name = _("Delete Person (%s)") % name_displayer.display(person) # delete the person from the database - # Above will emit person-delete, which removes the person via + # Above will emit person-delete, which removes the person via # callback to the model, so row delete is signaled self.dbstate.db.delete_person_from_database(person, trans) trans.set_description(active_name) @@ -347,7 +347,7 @@ class BasePersonView(ListView): def define_actions(self): """ Required define_actions function for PageView. Builds the action - group information required. We extend beyond the normal here, + group information required. We extend beyond the normal here, since we want to have more than one action group for the PersonView. Most PageViews really won't care about this. @@ -367,9 +367,9 @@ class BasePersonView(ListView): ('FilterEdit', None, _('Person Filter Editor'), None, None, self.filter_editor), ('Edit', 'gtk-edit', _("action|_Edit..."), - "Return", self.EDIT_MSG, self.edit), - ('QuickReport', None, _("Quick View"), None, None, None), - ('WebConnect', None, _("Web Connection"), None, None, None), + "Return", self.EDIT_MSG, self.edit), + ('QuickReport', None, _("Quick View"), None, None, None), + ('WebConnect', None, _("Web Connection"), None, None, None), ]) @@ -396,7 +396,7 @@ class BasePersonView(ListView): self.all_action.set_visible(True) self.edit_action.set_visible(True) self.edit_action.set_sensitive(not self.dbstate.db.readonly) - + def disable_action_group(self): """ Turns off the visibility of the View's action group. @@ -414,7 +414,7 @@ class BasePersonView(ListView): if len(mlist) != 2: ErrorDialog( - _("Cannot merge people"), + _("Cannot merge people"), _("Exactly two people must be selected to perform a merge. " "A second person can be selected by holding down the " "control key while clicking on the desired person.")) @@ -440,7 +440,7 @@ class BasePersonView(ListView): person = self.dbstate.db.get_person_from_handle(person_handle) person.add_tag(tag_handle) self.dbstate.db.commit_person(person, transaction) - + def get_default_gramplets(self): """ Define the default gramplets for the sidebar and bottombar. diff --git a/gramps/plugins/lib/libplaceimport.py b/gramps/plugins/lib/libplaceimport.py index ff15acb5c..946d74f5b 100644 --- a/gramps/plugins/lib/libplaceimport.py +++ b/gramps/plugins/lib/libplaceimport.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -70,7 +70,7 @@ class PlaceImport(object): for type_num, name in enumerate(location): if name: break - + loc = list(location) loc[type_num] = '' diff --git a/gramps/plugins/lib/libplaceview.py b/gramps/plugins/lib/libplaceview.py index a1f9bfae4..d15f08b20 100644 --- a/gramps/plugins/lib/libplaceview.py +++ b/gramps/plugins/lib/libplaceview.py @@ -98,7 +98,7 @@ class PlaceBaseView(ListView): ('columns.rank', [COL_NAME, COL_TITLE, COL_ID, COL_TYPE, COL_CODE, COL_LAT, COL_LON, COL_PRIV, COL_TAGS, COL_CHAN]), ('columns.size', [250, 250, 75, 100, 100, 150, 150, 40, 100, 100]) - ) + ) ADD_MSG = _("Add a new place") EDIT_MSG = _("Edit the selected place") DEL_MSG = _("Delete the selected place") @@ -134,7 +134,7 @@ class PlaceBaseView(ListView): def navigation_type(self): return 'Place' - + def define_actions(self): ListView.define_actions(self) self._add_toolmenu_action('MapsList', _('Loading...'), @@ -158,7 +158,7 @@ class PlaceBaseView(ListView): tb = self.uistate.viewmanager.uimanager.get_widget('/ToolBar') tb.remove(self.maptoolbtn) ListView.set_inactive(self) - + def change_page(self): """ Called by viewmanager at end of realization when arriving on the page @@ -188,7 +188,7 @@ class PlaceBaseView(ListView): return self.mapslistlabel = [] - if not self.mapservice in self.mapservicedata: + if not self.mapservice in self.mapservicedata: #stored val no longer exists, use the first key instead self.set_mapservice(list(self.mapservicedata.keys())[0]) @@ -208,7 +208,7 @@ class PlaceBaseView(ListView): [], Gdk.DragAction.COPY) tglist = Gtk.TargetList.new([]) - tglist.add(self.drag_info().atom_drag_type, + tglist.add(self.drag_info().atom_drag_type, self.drag_info().target_flags, self.drag_info().app_id) tglist.add_text_targets (0) @@ -220,13 +220,13 @@ class PlaceBaseView(ListView): from the menutoolbutton """ menu = Gtk.Menu() - + #select the map services to show self.mapservicedata = {} servlist = GuiPluginManager.get_instance().get_reg_mapservices() for i, pdata in enumerate(servlist): key = pdata.id.replace(' ', '-') - add_menuitem(menu, pdata.name, None, + add_menuitem(menu, pdata.name, None, make_callback(self.set_mapservice, key)) self.mapservicedata[key] = pdata @@ -243,7 +243,7 @@ class PlaceBaseView(ListView): label.show() config.set('interface.mapservice', mapkey) config.save() - + def mapservice_label(self): """ return the current label for the menutoolbutton @@ -252,7 +252,7 @@ class PlaceBaseView(ListView): def gotomap(self, obj): """ - Run the map service + Run the map service """ #First test if any map service is available if not len(self.mapservicedata): @@ -260,7 +260,7 @@ class PlaceBaseView(ListView): msg2 = _("Check your installation.") ErrorDialog(msg, msg2) return - + place_handles = self.selected_handles() try: place_handle = self.selected_handles()[0] @@ -271,11 +271,11 @@ class PlaceBaseView(ListView): " selections.") ErrorDialog(msg, msg2) return - + #TODO: support for descriptions in some cases. For now, pass None #TODO: Later this might be 'Birth of William' .... places = [(x, None) for x in place_handles] - + #run the mapservice: pmgr = GuiPluginManager.get_instance() serv = self.mapservicedata[self.mapservice] @@ -325,8 +325,8 @@ class PlaceBaseView(ListView): - - + + @@ -365,7 +365,7 @@ class PlaceBaseView(ListView): "First remove the places it contains.") ErrorDialog(msg, msg2) return - self.remove_selected_objects() + self.remove_selected_objects() def remove_object_from_handle(self, handle): person_list = [ @@ -375,11 +375,11 @@ class PlaceBaseView(ListView): family_list = [ item[1] for item in self.dbstate.db.find_backlink_handles(handle,['Family'])] - + event_list = [ item[1] for item in self.dbstate.db.find_backlink_handles(handle,['Event'])] - + object = self.dbstate.db.get_place_from_handle(handle) query = DeletePlaceQuery(self.dbstate, self.uistate, object, person_list, family_list, event_list) @@ -400,7 +400,7 @@ class PlaceBaseView(ListView): Merge the selected places. """ mlist = self.selected_handles() - + if len(mlist) != 2: msg = _("Cannot merge places.") msg2 = _("Exactly two places must be selected to perform a merge. " @@ -451,7 +451,7 @@ class PlaceBaseView(ListView): place = self.dbstate.db.get_place_from_handle(place_handle) place.add_tag(tag_handle) self.dbstate.db.commit_place(place, transaction) - + def get_default_gramplets(self): """ Define the default gramplets for the sidebar and bottombar. diff --git a/gramps/plugins/lib/libplugins.gpr.py b/gramps/plugins/lib/libplugins.gpr.py index 8ecec38a8..3358128e0 100644 --- a/gramps/plugins/lib/libplugins.gpr.py +++ b/gramps/plugins/lib/libplugins.gpr.py @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # diff --git a/gramps/plugins/lib/librecords.py b/gramps/plugins/lib/librecords.py index 20e706e94..e6901f43b 100644 --- a/gramps/plugins/lib/librecords.py +++ b/gramps/plugins/lib/librecords.py @@ -35,7 +35,7 @@ import datetime #------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext -from gramps.gen.lib import (ChildRefType, Date, Span, Name, StyledText, +from gramps.gen.lib import (ChildRefType, Date, Span, Name, StyledText, StyledTextTag, StyledTextTagType) from gramps.gen.display.name import displayer as name_displayer from gramps.gen.utils.alive import probably_alive @@ -165,12 +165,12 @@ def find_records(db, filter, top_size, callname, divorce_date = None for event_ref in family.get_event_ref_list(): event = db.get_event_from_handle(event_ref.ref) - if (event.get_type().is_marriage() and - (event_ref.get_role().is_family() or + if (event.get_type().is_marriage() and + (event_ref.get_role().is_family() or event_ref.get_role().is_primary())): marriage_date = event.get_date_object() - elif (event.get_type().is_divorce() and - (event_ref.get_role().is_family() or + elif (event.get_type().is_divorce() and + (event_ref.get_role().is_family() or event_ref.get_role().is_primary())): divorce_date = event.get_date_object() @@ -281,12 +281,12 @@ def find_records(db, filter, top_size, callname, divorce_date = None for event_ref in family.get_event_ref_list(): event = db.get_event_from_handle(event_ref.ref) - if (event.get_type().is_marriage() and - (event_ref.get_role().is_family() or + if (event.get_type().is_marriage() and + (event_ref.get_role().is_family() or event_ref.get_role().is_primary())): marriage_date = event.get_date_object() - if (event and event.get_type().is_divorce() and - (event_ref.get_role().is_family() or + if (event and event.get_type().is_divorce() and + (event_ref.get_role().is_family() or event_ref.get_role().is_primary())): divorce = event divorce_date = event.get_date_object() @@ -310,16 +310,16 @@ def find_records(db, filter, top_size, callname, # Mother died but death date unknown or inexact continue - if (divorce_date is None - and father_death_date is None + if (divorce_date is None + and father_death_date is None and mother_death_date is None): # Still married and alive if probably_alive(father, db) and probably_alive(mother, db): _record(family_youngestmarried, family_oldestmarried, today_date - marriage_date, name, 'Family', family.handle, top_size) - elif (_good_date(divorce_date) or - _good_date(father_death_date) or + elif (_good_date(divorce_date) or + _good_date(father_death_date) or _good_date(mother_death_date)): end = None if _good_date(father_death_date) and _good_date(mother_death_date): @@ -339,7 +339,7 @@ def find_records(db, filter, top_size, callname, duration, name, 'Family', family.handle, top_size) #python 3 workaround: assign locals to tmp so we work with runtime version tmp = locals() - return [(trans_text(text), varname, tmp[varname]) + return [(trans_text(text), varname, tmp[varname]) for (text, varname, default) in RECORDS] def _record(lowest, highest, value, text, handle_type, handle, top_size): diff --git a/gramps/plugins/lib/libsubstkeyword.py b/gramps/plugins/lib/libsubstkeyword.py index 7481fee28..3850c195b 100644 --- a/gramps/plugins/lib/libsubstkeyword.py +++ b/gramps/plugins/lib/libsubstkeyword.py @@ -297,10 +297,10 @@ class DateFormat(GenericFormat): return year(date.get_stop_year(), self.__count_chars("z", 4)) def e_month(): - return month(date.get_stop_month(), self.__count_chars("n", 4)) + return month(date.get_stop_month(), self.__count_chars("n", 4)) def eu_month(): - return month(date.get_stop_month(), + return month(date.get_stop_month(), self.__count_chars("N", 4)).upper() def e_day(): diff --git a/gramps/plugins/lib/libtreebase.py b/gramps/plugins/lib/libtreebase.py index ab27b14a2..4d3fca717 100644 --- a/gramps/plugins/lib/libtreebase.py +++ b/gramps/plugins/lib/libtreebase.py @@ -42,7 +42,7 @@ PT2CM = ReportUtils.pt2cm class CalcLines(object): """ wrapper for libsubstkeyword and added functionality for replacements. - + Receive: Individual and family handle, and display format [string] return: [Text] ready for a box. """ @@ -75,7 +75,7 @@ class CalcLines(object): repl = pair.split("/", 1) line = line.replace(repl[0], repl[1]) lns.append(line) - + return lns @@ -93,7 +93,7 @@ class Page(object): #parts from canvas #self.doc = doc self.canvas = canvas - + #parts about the page self.page_x_offset = 0 self.page_y_offset = 0 @@ -102,20 +102,20 @@ class Page(object): self.boxes = [] #All object must derive from BoxBase self.lines = [] #All must derive form Linebase self.note = None - + def is_blank(self): """ Am I a blank page? Notes and Titles are boxes too """ return self.boxes == [] and self.lines == [] - + def add_box(self, box): """ The box must derive from class Box_Base(Object): """ self.boxes.append(box) box.page = self - + def add_line(self, line): """ Add a line onto this page """ self.lines.append(line) - + def draw_border(self, line_name): doc = self.canvas.doc if self.y_page_num == 0: @@ -133,7 +133,7 @@ class Page(object): doc.draw_line(line_name, doc.get_usable_width(), 0, doc.get_usable_width(), doc.get_usable_height()) - + def display(self): """ Display all boxes and lines that are on this page """ for box in self.boxes: @@ -141,7 +141,7 @@ class Page(object): for line in self.lines: line.display(self) - + class Canvas(Page): """ The Canvas is two things. The all in one canvas. a canvas is a page of unlimited size @@ -152,7 +152,7 @@ class Canvas(Page): Page.__init__(self, self) self.doc = doc self.report_opts = report_opts - + #How many pages are there in the report. one more than real. self.x_pages = 1 self.y_pages = 1 @@ -160,9 +160,9 @@ class Canvas(Page): self.__fonts = {} #keep a list of fonts so we don't have to lookup. self.title = None self.note = None - + def __new_page(self, x_page, y_page, x_offset, y_offset): - """ Make a new page. This will only happen if we are + """ Make a new page. This will only happen if we are paginating (making new pages to hold parts of the canvas) """ if x_page >= self.x_pages: self.x_pages = x_page + 1 @@ -173,21 +173,21 @@ class Canvas(Page): new_page.page_y_offset = y_offset self.__pages[x_page, y_page] = new_page return new_page - + def sort_boxes_on_y_cm(self): """ sorts the list of boxes on the canvas by .y_cm (top down) """ self.boxes.sort( key=lambda box: box.y_cm) - + def add_title(self, title): """ The title must derive from class TitleBox(BoxBase): """ self.title = title self.title.cm_y = self.report_opts.littleoffset - + def add_note(self, note): """ The note must derive from class NoteBox(BoxBase, NoteType) """ self.note = note self.set_box_height_width(self.note) - + def __get_font(self, box): """ returns the font used by a box. makes a list of all seen fonts to be faster. If a new is found, run through the process to get it """ @@ -197,9 +197,9 @@ class Canvas(Page): style_name = style_name.get_paragraph_style() self.__fonts[box.boxstr] = \ style_sheet.get_paragraph_style(style_name).get_font() - + return self.__fonts[box.boxstr] - + def get_report_height_width(self): """ returns the (max width, max height) of the report This does not take into account any shadows """ @@ -217,32 +217,32 @@ class Canvas(Page): max_height += self.report_opts.box_shadow max_height += self.report_opts.littleoffset return (max_width, max_height) - + def __scale_canvas(self, scale_amount): """ scales everything up/down depending upon scale_amount """ self.report_opts.scale_everything(scale_amount) self.title.scale(scale_amount) if self.note is not None: self.note.scale(scale_amount) - #scale down everyone! - for box in self.boxes: + #scale down everyone! + for box in self.boxes: box.scale(scale_amount) - + def set_box_height_width(self, box): """ Sets the .width and .height of a box. """ if box.boxstr == "None": box.height = box.width = 0 return - + font = self.__get_font(box) ##################### #Get the width for line in box.text: - width = self.doc.string_width(font, line) + width = self.doc.string_width(font, line) width = PT2CM(width) if width > box.width: box.width = width - + ##################### #Get the height height = len(box.text) * font.get_size() * 1.5 @@ -259,7 +259,7 @@ class Canvas(Page): if (x_p, y_p) in self.__pages: count += 1 return count - + def page_iter_gen(self, incblank): """ generate the pages of the report. do so in a left to right up down approach. incblank asks to include blank pages """ @@ -272,34 +272,34 @@ class Canvas(Page): if incblank: blank.x_page_num = x_p blank.y_page_num = y_p - yield blank - + yield blank + def __add_box_to_page(self, x_page, y_page, x_offset, y_offset, box): """ adds a box to a page. If the page is not there, make it first """ if (x_page, y_page) not in self.__pages: #Add the new page into the dictionary self.__new_page(x_page, y_page, x_offset, y_offset) - + #Add the box into the page self.__pages[x_page, self.y_pages-1].add_box(box) - + def scale_report(self, one_page, scale_to_width, scale_to_height): """ We have a report in its full size (on the canvas and pages to print on. scale one or both as needed/desired. - + - one_page, boolean. Whether to make the page(or parts of) the size of the report - scale_to_width, boolean. Scale the report width to the page size? - scale_to_height, boolean. Scale the report height to page size? """ - + if scale_to_width or scale_to_height: max_width, max_height = self.canvas.get_report_height_width() #max_width += self.report_opts.littleoffset #max_height += self.report_opts.littleoffset - + """ - calc - Calculate the scale amount (if any). + calc - Calculate the scale amount (if any). <1 everything is smaller to fit on the page 1 == no scaling >1 make everything bigger to fill out the page @@ -313,9 +313,9 @@ class Canvas(Page): #Check the width of the title title_width = self.title.width title_width += self.report_opts.littleoffset * 2 - + max_width = max(title_width, max_width) - + #This will be our base amount and #then we will decrease only as needed from here. @@ -329,11 +329,11 @@ class Canvas(Page): if not scale_to_width or tmp < scale: scale = tmp scaled_report_to = "height" - + #Now I have the scale amount if scale != 1: #scale everything on the canvas self.__scale_canvas(scale) - + ##################### #Scale the page option if one_page: @@ -344,32 +344,32 @@ class Canvas(Page): max_width, max_height = \ self.canvas.get_report_height_width() - + if scaled_report_to != "width": #calculate the width of the report #max_width += self.report_opts.littleoffset - max_width += self.doc.paper.get_left_margin() - max_width += self.doc.paper.get_right_margin() - + max_width += self.doc.paper.get_left_margin() + max_width += self.doc.paper.get_right_margin() + #calculate the width of the title title_width = self.canvas.title.width title_width += self.doc.paper.get_left_margin() - title_width += self.doc.paper.get_right_margin() + title_width += self.doc.paper.get_right_margin() title_width += self.report_opts.littleoffset max_width = max(title_width, max_width) - + size.set_width(max_width) - + if scaled_report_to != "height": #calculate the height of the report max_height += self.doc.paper.get_top_margin() max_height += self.doc.paper.get_bottom_margin() #max_height += self.report_opts.littleoffset size.set_height(max_height) - + return scale - + def __paginate_x_offsets(self, colsperpage): """ Go through the boxes and get the x page offsets """ #fix soon. should not use .level @@ -383,28 +383,28 @@ class Canvas(Page): if x_page >= self.x_pages: self.x_pages = x_page+1 return x_page_offsets - + def __paginate_y_pages(self, colsperpage, x_page_offsets): """ Go through the boxes and put each one in a page note that the self.boxes needs to be sorted by .y_cm """ page_y_top = [0] page_y_height = [self.doc.get_usable_height()] liloffset = self.report_opts.littleoffset - + for box in self.boxes: #check to see if this box cross over to the next (y) page height = box.y_cm + liloffset + box.height #+ box.shadow/2 - + if height > page_y_height[-1]: #we went off the end page_y_height.append(box.y_cm - liloffset + page_y_height[0]) page_y_top.append(box.y_cm - liloffset) self.y_pages = len(page_y_height) - + #Calculate my (x) page #fix soon. should not use .level x_page = box.level[0] // colsperpage - + self.__add_box_to_page(x_page, self.y_pages-1, x_page_offsets[x_page], page_y_top[self.y_pages-1], @@ -417,7 +417,7 @@ class Canvas(Page): ##Add the box into the page #self.__pages[x_page, self.y_pages-1].add_box(box) return page_y_top - + def __paginate_note(self, x_page_offsets, page_y_top): """ Put the note on first. it can be overwritten by other boxes but it CAN NOT overwrite a box. """ @@ -430,7 +430,7 @@ class Canvas(Page): self.__pages[x_page, y_page].boxes.insert(0, self.note) self.note.doc = self.doc self.note.page = self - + def __paginate_lines(self, x_page_offsets, page_y_top): """ Step three go through the lines and put each in page(s) """ for box1 in self.boxes: @@ -442,11 +442,11 @@ class Canvas(Page): pages = [box1.page.y_page_num] end = line.start + line.end - + x_page = box1.page.x_page_num start_y_page = end[0].page.y_page_num end_y_page = end[0].page.y_page_num - + for box in end: y_page = box.page.y_page_num if y_page not in pages: @@ -457,12 +457,12 @@ class Canvas(Page): page_y_top[y_page]) self.__pages[x_page, y_page].add_line(box1.line_to) pages.append(y_page) - + if y_page < start_y_page: start_y_page = y_page if y_page > end_y_page: end_y_page = y_page - + #if len(end) = 2 & end[0].y_page = 0 & end[1].y_page = 4 #the line will not print on y_pages 1,2,3. Fix that here. #x_page = start_x_page @@ -474,7 +474,7 @@ class Canvas(Page): x_page_offsets[x_page], page_y_top[y_page]) self.__pages[x_page, y_page].add_line(box1.line_to) - + def __paginate_title(self, x_page_offsets): #step four work with the title if self.title.boxstr == "None": @@ -488,14 +488,14 @@ class Canvas(Page): title_list = self.title.text.split(" ") title_font = self.__get_font(self.title) #space_width = PT2CM(self.doc.string_width(title_font," ")) - + list_title = [title_list.pop(0)] while len(title_list): tmp = list_title[-1] + " " + title_list[0] if PT2CM(self.doc.string_width(title_font, tmp)) > \ x_page_offsets[1]: list_title.append("") - if list_title[-1] != "": + if list_title[-1] != "": list_title[-1] += " " list_title[-1] += title_list.pop(0) @@ -505,7 +505,7 @@ class Canvas(Page): list_title.append("") #one extra for security. doesn't hurt. list_title.append("") - + x_page = 0 for title in list_title: if title == "": @@ -514,18 +514,18 @@ class Canvas(Page): if (x_page, 0) not in self.__pages: #Add the new page into the dictionary self.__new_page(x_page, 0, x_page_offsets[1], 0) - + title_part = TitleBox(self.doc, self.title.boxstr) title_part.text = list_title[x_page] title_part.width = x_page_offsets[1] - + #Add the box into the page self.__pages[x_page, 0].add_box(title_part) x_page = x_page + 1 else: self.title.width = self.doc.get_usable_width() self.__pages[0, 0].add_box(self.title) - + def __paginate(self, colsperpage): """ take the boxes on the canvas and put them into separate pages. The boxes need to be sorted by y_cm """ @@ -533,12 +533,12 @@ class Canvas(Page): self.__pages = {} x_page_offsets = self.__paginate_x_offsets(colsperpage) page_y_top = self.__paginate_y_pages(colsperpage, x_page_offsets) - + if self.note is not None: self.__paginate_note(x_page_offsets, page_y_top) self.__paginate_lines(x_page_offsets, page_y_top) self.__paginate_title(x_page_offsets) - + def paginate(self, colsperpage, one_page_report): """ self.boxes must be sorted by box.y_cm for this to work. """ @@ -548,7 +548,7 @@ class Canvas(Page): title_part.text = self.title.text title_part.width = self.doc.get_usable_width() self.add_box(title_part) - + if self.note is not None: self.note.set_on_page(self) self.boxes.insert(0, self.note) @@ -569,7 +569,7 @@ class BoxBase(object): """ def __init__(self): self.page = None - + #'None' will cause an error. Sub-classes will init self.boxstr = "None" self.text = "" @@ -586,17 +586,17 @@ class BoxBase(object): self.line_to = None #if text in TOC needs to be different from text, set mark_text self.mark_text = None - + def scale(self, scale_amount): """ Scale the amounts """ self.x_cm *= scale_amount self.y_cm *= scale_amount self.width *= scale_amount self.height *= scale_amount - + def add_mark(self, database, person): self.__mark = ReportUtils.get_person_mark(database, person) - + def display(self): """ display the box accounting for page x, y offsets Ignore any box with 'None' is boxstr """ @@ -608,10 +608,10 @@ class BoxBase(object): text = '\n'.join(self.text) xbegin = self.x_cm - self.page.page_x_offset ybegin = self.y_cm - self.page.page_y_offset - + doc.draw_box(self.boxstr, text, - xbegin, ybegin, + xbegin, ybegin, self.width, self.height, self.__mark) #I am responsible for my own lines. Do them here. @@ -626,7 +626,7 @@ class BoxBase(object): class TitleNoDisplay(BoxBase): """ - Holds information about the Title that will print on a TOC + Holds information about the Title that will print on a TOC and NOT on the report """ def __init__(self, doc, boxstr): @@ -634,7 +634,7 @@ class TitleNoDisplay(BoxBase): BoxBase.__init__(self) self.doc = doc self.boxstr = boxstr - + def set_box_height_width(self): self.width = self.height = 0 @@ -658,7 +658,7 @@ class TitleBox(BoxBase): self.boxstr = boxstr if boxstr == "None": return - + style_sheet = self.doc.get_style_sheet() style_name = style_sheet.get_draw_style(self.boxstr) style_name = style_name.get_paragraph_style() @@ -683,24 +683,24 @@ class TitleBox(BoxBase): #Set up the Table of Contents here mark = IndexMark(self.text, INDEX_TYPE_TOC, 1) - + if self.text: self.doc.center_text(self.boxstr, self.text, self.width/2, self.y_cm, mark) - + class PageNumberBox(BoxBase): """ Calculates information about the page numbers that will print on a page do not put in a value for PageNumberBox.text. this will be calculated for each page """ - + def __init__(self, doc, boxstr, locale): """ initialize the page number box """ BoxBase.__init__(self) self.doc = doc self.boxstr = boxstr self._ = locale.translation.sgettext - + def __calc_position(self, page): """ calculate where I am to print on the page(s) """ # translators: needed for Arabic, ignore otherwise @@ -710,7 +710,7 @@ class PageNumberBox(BoxBase): style_name = style_sheet.get_draw_style(self.boxstr) style_name = style_name.get_paragraph_style() font = style_sheet.get_paragraph_style(style_name).get_font() - + #calculate how much space is needed if page.canvas.x_pages > 10: tmp = "00" @@ -720,15 +720,15 @@ class PageNumberBox(BoxBase): tmp += "00" else: tmp += "0" - + width = self.doc.string_width(font, '(,)'+tmp) width = PT2CM(width) self.width = width - + height = font.get_size() * 1.4 height += 0.5/2.0 * font.get_size() #funny number(s) based upon font. self.height = PT2CM(height) - + self.x_cm = self.doc.get_usable_width() - self.width self.y_cm = self.doc.get_usable_height() - self.height @@ -737,43 +737,43 @@ class PageNumberBox(BoxBase): then display the page number """ if self.text == "": self.__calc_position(page) - + self.doc.draw_text(self.boxstr, self.text % (page.x_page_num+1, page.y_page_num+1), self.x_cm, self.y_cm) class NoteType(object): """ Provide the different options (corners) to place the note """ - + TOPLEFT = 0 TOPRIGHT = 1 BOTTOMLEFT = 2 BOTTOMRIGHT = 3 - + _DEFAULT = BOTTOMRIGHT - + _DATAMAP = [ (TOPLEFT, _("Top Left"), "Top Left"), (TOPRIGHT, _("Top Right"), "Top Right"), (BOTTOMLEFT, _("Bottom Left"), "Bottom Left"), (BOTTOMRIGHT, _("Bottom Right"), "Bottom Right"), ] - + def __init__(self, value, exclude=None): """ initialize GrampsType """ self.value = value self.exclude = exclude #GrampsType.__init__(self, value) - + def note_locals(self, start=0): """ generates an int of all the options """ for tuple in self._DATAMAP: if tuple[0] != self.exclude: yield tuple[0], tuple[1] - + class NoteBox(BoxBase, NoteType): """ Box that will hold the note to display on the page """ - + def __init__(self, doc, boxstr, box_corner, exclude=None): """ initialize the NoteBox """ BoxBase.__init__(self) @@ -784,7 +784,7 @@ class NoteBox(BoxBase, NoteType): def set_on_page(self, canvas): """ set the x_cm and y_cm given self.doc, leloffset, and title_height """ - + liloffset = canvas.report_opts.littleoffset #left or right side if self.value == NoteType.BOTTOMLEFT or \ @@ -798,7 +798,7 @@ class NoteBox(BoxBase, NoteType): self.y_cm = canvas.title.height + liloffset*2 else: self.y_cm = self.doc.get_usable_height() - self.height - liloffset - + """ helper function for canvas.paginate(). return the (x, y) page I want to print on """ if self.value == NoteType.TOPLEFT: @@ -809,7 +809,7 @@ class NoteBox(BoxBase, NoteType): return (0, canvas.y_pages-1) elif self.value == NoteType.BOTTOMRIGHT: return (canvas.x_pages-1, canvas.y_pages-1) - + def display(self): """ position the box and display """ title = self.page.canvas.title @@ -839,17 +839,17 @@ class LineBase(object): def add_from(self, person): self.start.append(person) - + def add_to(self, person): """ add destination boxes to draw this line to """ self.end.append(person) - + def display(self, page): """ display the line. left to right line. one start, multiple end. page will tell us what parts of the line we can print """ if self.end == [] and len(self.start) == 1: return - + # y_cm and x_cm start points - take into account page offsets #yme = self.start.y_cm + self.start.height/2 - page.page_y_offset #if type(self.start) != type([]): @@ -861,9 +861,9 @@ class LineBase(object): xbegin = start.x_cm + start.width - page.page_x_offset # out 3/4 of the way and x_cm end point(s) - x34 = xbegin + (report_opts.col_width * 3/4) + x34 = xbegin + (report_opts.col_width * 3/4) xend = xbegin + report_opts.col_width - + if x34 > 0: # > 0 tell us we are printing on this page. usable_height = doc.get_usable_height() #1 - Line from start box out @@ -872,7 +872,7 @@ class LineBase(object): if box.page.y_page_num == page.y_page_num: # and 0 < yme < usable_height and \ doc.draw_line(linestr, xbegin, yme, x34, yme) - + #2 - vertical line mid = [] for box in self.start + self.end: @@ -888,7 +888,7 @@ class LineBase(object): doc.draw_line(linestr, x34, mid[0], x34, mid[1]) else: x34 = 0 - + #3 - horizontal line(s) for box in self.end: if box.page.y_page_num == page.y_page_num: @@ -909,26 +909,26 @@ class ReportOptions(object): the column width, for lines, the left hand spacing for spouses (Descendant report only) """ - + def __init__(self, doc, normal_font, normal_line): """ initialize various report variables that are used """ self.box_pgap = PT2CM(1.25*normal_font.get_size()) #gap between persons self.box_mgap = self.box_pgap /2 #gap between marriage information self.box_shadow = PT2CM(normal_font.get_size()) * .6 #normal text self.spouse_offset = PT2CM(doc.string_width(normal_font, "0")) - + self.col_width = PT2CM(doc.string_width(normal_font, "(000,0)")) self.littleoffset = PT2CM(1) self.x_cm_cols = [self.littleoffset] self.line_str = normal_line - + #Things that will get added later self.max_box_width = 0 self.max_box_height = 0 - + self.scale = 1 - + def scale_everything(self, amount): """ Scale the amounts that are needed to generate a report """ self.scale = amount diff --git a/gramps/plugins/lib/maps/__init__.py b/gramps/plugins/lib/maps/__init__.py index ac3d53057..609e30a89 100644 --- a/gramps/plugins/lib/maps/__init__.py +++ b/gramps/plugins/lib/maps/__init__.py @@ -19,7 +19,7 @@ # """ -The gen module provides packages that are common to all gramps +The gen module provides packages that are common to all gramps interfaces (gui, cli and web). """ diff --git a/gramps/plugins/lib/maps/cairoprint.py b/gramps/plugins/lib/maps/cairoprint.py index 7af373867..657f86c3c 100644 --- a/gramps/plugins/lib/maps/cairoprint.py +++ b/gramps/plugins/lib/maps/cairoprint.py @@ -45,12 +45,12 @@ PRINT_SETTINGS = None #------------------------------------------------------------------------ class CairoPrintSave(): """Act as an abstract document that can render onto a cairo context. - + It can render the model onto cairo context pages, according to the received page style. - + """ - + def __init__(self, widthpx, heightpx, drawfunc, parent): """ This class provides the things needed so as to dump a cairo drawing on @@ -60,17 +60,17 @@ class CairoPrintSave(): widthpx += 30 heightpx += 30 self.scale = 100.0 - self.widthpx = widthpx + self.widthpx = widthpx self.heightpx = heightpx self.drawfunc = drawfunc self.parent = parent - + def run(self): """Create the physical output from the meta document. - + """ global PRINT_SETTINGS - + # set up a print operation operation = Gtk.PrintOperation() operation.connect("draw_page", self.on_draw_page) @@ -101,10 +101,10 @@ class CairoPrintSave(): else: page_setup.set_orientation(Gtk.PageOrientation.PORTRAIT) operation.set_default_page_setup(page_setup) - + if PRINT_SETTINGS is not None: operation.set_print_settings(PRINT_SETTINGS) - + # run print dialog while True: self.preview = None @@ -123,7 +123,7 @@ class CairoPrintSave(): # store print settings if printing was successful if res == Gtk.PrintOperationResult.APPLY: PRINT_SETTINGS = operation.get_print_settings() - + def on_draw_page(self, operation, context, page_nr): """Draw a page on a Cairo context. """ @@ -132,9 +132,9 @@ class CairoPrintSave(): def on_preview(self, operation, preview, context, parent): """Implement custom print preview functionality. - We provide a dummy holder here, because on_preview crashes if no + We provide a dummy holder here, because on_preview crashes if no default application is set with gir 3.3.2 (typically evince not installed)! """ operation.run(Gtk.PrintOperationAction.PREVIEW, None) - return False + return False diff --git a/gramps/plugins/lib/maps/geography.py b/gramps/plugins/lib/maps/geography.py index 8ccb736ad..014b071e2 100644 --- a/gramps/plugins/lib/maps/geography.py +++ b/gramps/plugins/lib/maps/geography.py @@ -154,7 +154,7 @@ class GeoGraphyView(OsmGps, NavigationView): self.select_fct = None self.geo_mainmap = None theme = Gtk.IconTheme.get_default() - self.geo_mainmap = theme.load_surface('gramps-geo-mainmap', 48, 1, + self.geo_mainmap = theme.load_surface('gramps-geo-mainmap', 48, 1, None, 0) self.geo_altmap = theme.load_surface('gramps-geo-altmap', 48, 1, None, 0) @@ -181,10 +181,10 @@ class GeoGraphyView(OsmGps, NavigationView): else: from gramps.gui.dialog import WarningDialog WarningDialog( - _("Could Not Set a Bookmark"), + _("Could Not Set a Bookmark"), _("A bookmark could not be set because " "no one was selected.")) - + def add_bookmark_from_popup(self, menu, handle): if handle: @@ -194,7 +194,7 @@ class GeoGraphyView(OsmGps, NavigationView): else: from gramps.gui.dialog import WarningDialog WarningDialog( - _("Could Not Set a Bookmark"), + _("Could Not Set a Bookmark"), _("A bookmark could not be set because " "no one was selected.")) @@ -216,7 +216,7 @@ class GeoGraphyView(OsmGps, NavigationView): requisition.height = 300 def do_get_preferred_width(self): - """ GTK3 uses width for height sizing model. This method will + """ GTK3 uses width for height sizing model. This method will override the virtual method """ req = Gtk.Requisition() @@ -224,7 +224,7 @@ class GeoGraphyView(OsmGps, NavigationView): return req.width, req.width def do_get_preferred_height(self): - """ GTK3 uses width for height sizing model. This method will + """ GTK3 uses width for height sizing model. This method will override the virtual method """ req = Gtk.Requisition() @@ -400,7 +400,7 @@ class GeoGraphyView(OsmGps, NavigationView): We need to clean the tiles cache for the current map """ import shutil - + path = "%s%c%s" % ( config.get('geography.path'), os.sep, the_map ) shutil.rmtree(path) pass @@ -720,9 +720,9 @@ class GeoGraphyView(OsmGps, NavigationView): signmaxlon = _get_sign(self.maxlon) signmaxlat = _get_sign(self.maxlat) current = osmgpsmap.MapPoint.new_degrees(self.minlat, self.minlon) - self.end_selection = current + self.end_selection = current current = osmgpsmap.MapPoint.new_degrees(self.maxlat, self.maxlon) - self.begin_selection = current + self.begin_selection = current if signminlon == signmaxlon: maxlong = abs(abs(self.minlon) - abs(self.maxlon)) else: @@ -1155,8 +1155,8 @@ class GeoGraphyView(OsmGps, NavigationView): _('The maximum number of places to show'), 4, 'geography.max_places', (1000, 10000)) - configdialog.add_checkbox(grid, - _('Use keypad for shortcuts :\n' + configdialog.add_checkbox(grid, + _('Use keypad for shortcuts :\n' 'Either we choose the + and - from the keypad if we select this,\n' 'or we use the characters from the keyboard.'), 5, 'geography.use-keypad', diff --git a/gramps/plugins/lib/maps/markerlayer.py b/gramps/plugins/lib/maps/markerlayer.py index eaba708e2..62f01fc73 100644 --- a/gramps/plugins/lib/maps/markerlayer.py +++ b/gramps/plugins/lib/maps/markerlayer.py @@ -121,7 +121,7 @@ class MarkerLayer(GObject.GObject, osmgpsmap.MapLayer): We use cairo to resize the marker. """ max_interval = self.max_value - self.nb_ref_by_places - min_interval = self.nb_ref_by_places - self.min_value + min_interval = self.nb_ref_by_places - self.min_value if max_interval == 0: # This to avoid divide by zero max_interval = 0.01 if min_interval == 0: # This to avoid divide by zero diff --git a/gramps/plugins/lib/maps/osmgps.py b/gramps/plugins/lib/maps/osmgps.py index fdb3501cf..784f178a8 100644 --- a/gramps/plugins/lib/maps/osmgps.py +++ b/gramps/plugins/lib/maps/osmgps.py @@ -100,7 +100,7 @@ class OsmGps(): def build_widget(self): """ - create the vbox + create the vbox """ self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) cache_path = config.get('geography.path') diff --git a/gramps/plugins/lib/maps/placeselection.py b/gramps/plugins/lib/maps/placeselection.py index 32ce3844d..0ca2c7476 100644 --- a/gramps/plugins/lib/maps/placeselection.py +++ b/gramps/plugins/lib/maps/placeselection.py @@ -153,7 +153,7 @@ class PlaceSelection(ManagedWindow, OsmGps): self.window.vbox.pack_start(self.scroll, True, True, 0) self.label2 = Gtk.Label() self.label2.set_markup('%s' % + '>%s' % _('The green values in the row correspond ' 'to the current place values.')) self.label2.set_valign(Gtk.Align.END) diff --git a/gramps/plugins/mapservices/eniroswedenmap.py b/gramps/plugins/mapservices/eniroswedenmap.py index 882fc9d5d..c4b5c6aa1 100644 --- a/gramps/plugins/mapservices/eniroswedenmap.py +++ b/gramps/plugins/mapservices/eniroswedenmap.py @@ -44,17 +44,17 @@ from gramps.gen.display.place import displayer as place_displayer from gramps.gen.lib import PlaceType # Make upper case of translaed country so string search works later -MAP_NAMES_SWEDEN = [_("Sweden").upper(), - "SVERIGE", +MAP_NAMES_SWEDEN = [_("Sweden").upper(), + "SVERIGE", "SWEDEN", - "SUEDOIS", + "SUEDOIS", "ROUTSI", "SCHWEDEN", ] -MAP_NAMES_DENMARK = [_("Denmark").upper(), - "DANMARK", - "DENMARK", - "DANOIS", - "TANSKA", +MAP_NAMES_DENMARK = [_("Denmark").upper(), + "DANMARK", + "DENMARK", + "DANOIS", + "TANSKA", "DÄNEMARK", ] @@ -83,7 +83,7 @@ def _build_title(db, place): if state: title_descr += ', ' + state.strip() + _(" state") return _strip_leading_comma(title_descr) - + def _build_city(db, place): """ Builds description string for city parameter in url """ location = get_main_location(db, place) @@ -102,9 +102,9 @@ def _build_area(db, place): # Build a title description string that will work for Eniro area_descr = "" if street: - area_descr += street.strip() + area_descr += street.strip() if city: - area_descr += ', ' + city + area_descr += ', ' + city return _strip_leading_comma(area_descr) @@ -131,12 +131,12 @@ class EniroSVMapService(MapService): country in MAP_NAMES_DENMARK) and (country != "") # if no country given, check if we might be in the vicinity defined by # 54 33' 0" < lat < 66 9' 0", 54.55 and 69.05 - # 8 3' 0" < long < 24 9' 0", 8.05 and 24.15 + # 8 3' 0" < long < 24 9' 0", 8.05 and 24.15 latitude, longitude = self._lat_lon(place) if latitude is None or longitude is None: coord_ok = False else: - latitude = float(latitude) + latitude = float(latitude) longitude = float(longitude) # Check if coordinates are inside Sweden and Denmark if (54.55 < latitude < 69.05) and (8.05 < longitude < 24.15): @@ -176,7 +176,7 @@ class EniroSVMapService(MapService): self.url = "" return - WarningDialog(_("Eniro map not available"), + WarningDialog(_("Eniro map not available"), _("Latitude and longitude,\n" \ "or street and city needed") ) return diff --git a/gramps/plugins/mapservices/googlemap.py b/gramps/plugins/mapservices/googlemap.py index 47ea4e986..c2a616611 100644 --- a/gramps/plugins/mapservices/googlemap.py +++ b/gramps/plugins/mapservices/googlemap.py @@ -43,7 +43,7 @@ class GoogleMapService(MapService): """Map service using http://maps.google.com""" def __init__(self): MapService.__init__(self) - + def calc_url(self): """ Determine the url to use on maps.google.com Logic: use lat lon if present @@ -53,17 +53,17 @@ class GoogleMapService(MapService): place = self._get_first_place()[0] latitude, longitude = self._lat_lon(place) if longitude and latitude: - self.url = "http://maps.google.com/maps/mm?sll=%s,%s&z=15" % (latitude, + self.url = "http://maps.google.com/maps/mm?sll=%s,%s&z=15" % (latitude, longitude) return - + location = get_main_location(self.database, place) city = location.get(PlaceType.CITY) country = location.get(PlaceType.COUNTRY) if city and country: self.url = "http://maps.google.com/maps?q=%s,%s" % (city, country) return - + titledescr = place_displayer.display(self.database, place) self.url = "http://maps.google.com/maps?q=%s" % \ '+'.join(titledescr.split()) diff --git a/gramps/plugins/mapservices/mapservice.gpr.py b/gramps/plugins/mapservices/mapservice.gpr.py index 77e797b63..2e3836e41 100644 --- a/gramps/plugins/mapservices/mapservice.gpr.py +++ b/gramps/plugins/mapservices/mapservice.gpr.py @@ -18,7 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # @@ -26,7 +26,7 @@ MODULE_VERSION="5.0" # #------------------------------------------------------------------------ -register(MAPSERVICE, +register(MAPSERVICE, id = 'EniroMaps', name = _("EniroMaps"), description = _("Opens on kartor.eniro.se"), @@ -45,7 +45,7 @@ mapservice = 'EniroSVMapService' # #------------------------------------------------------------------------ -register(MAPSERVICE, +register(MAPSERVICE, id = 'GoogleMaps', name = _("GoogleMaps"), description = _("Open on maps.google.com"), @@ -64,7 +64,7 @@ mapservice = 'GoogleMapService' # #------------------------------------------------------------------------ -register(MAPSERVICE, +register(MAPSERVICE, id = 'OpenStreetMap', name = _("OpenStreetMap"), description = _("Open on openstreetmap.org"), diff --git a/gramps/plugins/mapservices/openstreetmap.py b/gramps/plugins/mapservices/openstreetmap.py index 6d6d41ce7..64e76b3d7 100644 --- a/gramps/plugins/mapservices/openstreetmap.py +++ b/gramps/plugins/mapservices/openstreetmap.py @@ -45,9 +45,9 @@ class OpensStreetMapService(MapService): """ def __init__(self): MapService.__init__(self) - + def calc_url(self): - """ Determine the url to use + """ Determine the url to use Logic: use lat lon if present otherwise use city and country if present otherwise use description of the place @@ -57,9 +57,9 @@ class OpensStreetMapService(MapService): if longitude and latitude: self.url = "http://www.openstreetmap.org/" \ "?lat=%s&lon=%s&zoom=15" % (latitude, longitude) - + return - + location = get_main_location(self.database, place) city = location.get(PlaceType.CITY) country = location.get(PlaceType.COUNTRY) @@ -67,7 +67,7 @@ class OpensStreetMapService(MapService): self.url = "http://nominatim.openstreetmap.org/"\ "search.php?q=%s%%2C%s" % (city, country) return - + titledescr = place_displayer.display(self.database, place) self.url = "http://nominatim.openstreetmap.org/"\ "search.php?q=%s" % '+'.join(titledescr.split()) diff --git a/gramps/plugins/quickview/ageondate.py b/gramps/plugins/quickview/ageondate.py index a088f0840..0121b3f55 100644 --- a/gramps/plugins/quickview/ageondate.py +++ b/gramps/plugins/quickview/ageondate.py @@ -46,10 +46,10 @@ def run(database, document, date): return # display the title if date.get_day_valid(): - sdoc.title(_("People and their ages the %s") % + sdoc.title(_("People and their ages the %s") % displayer.display(date)) else: - sdoc.title(_("People and their ages on %s") % + sdoc.title(_("People and their ages on %s") % displayer.display(date)) stab.columns(_("Person"), _("Age"), _("Status")) # Actual Date makes column unicode alive_matches = 0 @@ -79,7 +79,7 @@ def run(database, document, date): document.has_data = (alive_matches + dead_matches) > 0 sdoc.paragraph(_("\nLiving matches: %(alive)d, " - "Deceased matches: %(dead)d\n") % + "Deceased matches: %(dead)d\n") % {'alive' : alive_matches, 'dead' : dead_matches}) stab.write(sdoc) sdoc.paragraph("") diff --git a/gramps/plugins/quickview/all_events.py b/gramps/plugins/quickview/all_events.py index a487053e7..af4d1ba80 100644 --- a/gramps/plugins/quickview/all_events.py +++ b/gramps/plugins/quickview/all_events.py @@ -32,10 +32,10 @@ _ = glocale.translation.gettext def run(database, document, person): """ Loops through the person events and the family events of any family - in which the person is a parent (to catch Marriage events), displaying + in which the person is a parent (to catch Marriage events), displaying the basic details of the event """ - + sdb = SimpleAccess(database) sdoc = SimpleDoc(document) stab = QuickTable(sdb) @@ -43,7 +43,7 @@ def run(database, document, person): # get the personal events event_list = sdb.events(person) - # get the events of each family in which the person is + # get the events of each family in which the person is # a parent for family in sdb.parent_in(person): event_list += sdb.events(family) @@ -60,41 +60,41 @@ def run(database, document, person): stab.columns(_("Event Type"), _("Event Date"), _("Event Place")) document.has_data = False for event in event_list: - stab.row(event, - sdb.event_date_obj(event), + stab.row(event, + sdb.event_date_obj(event), sdb.event_place(event)) document.has_data = True stab.write(sdoc) def run_fam(database, document, family): """ - Loops through the family events and the events of all parents, displaying + Loops through the family events and the events of all parents, displaying the basic details of the event """ - + sdb = SimpleAccess(database) sdoc = SimpleDoc(document) stab = QuickTable(sdb) - + # get the family events event_list = [(_('Family'), x) for x in sdb.events(family)] - + # get the events of father and mother #fathername = sdb.first_name(sdb.father(family)) event_list += [(sdb.father(family), x) for x in sdb.events(sdb.father(family))] #mothername = sdb.first_name(sdb.mother(family)) event_list += [(sdb.mother(family), x) for x in sdb.events(sdb.mother(family))] - + # children events event_list_children = [] for child in sdb.children(family) : #name = sdb.first_name(child) event_list_children += [(child, x) for x in sdb.events(child)] - + # Sort the events by their date event_list.sort(key=lambda x: x[1].get_date_object()) event_list_children.sort(key=lambda x: x[1].get_date_object()) - + # display the results sdoc.title(_("Sorted events of family\n %(father)s - %(mother)s") % { @@ -102,23 +102,23 @@ def run_fam(database, document, family): sdoc.paragraph("") document.has_data = False - stab.columns(_("Family Member"), _("Event Type"), + stab.columns(_("Family Member"), _("Event Type"), _("Event Date"), _("Event Place")) for (person, event) in event_list: - stab.row(person, sdb.event_type(event), - sdb.event_date_obj(event), + stab.row(person, sdb.event_type(event), + sdb.event_date_obj(event), sdb.event_place(event)) document.has_data = True stab.write(sdoc) stab = QuickTable(sdb) sdoc.header1(_("Personal events of the children")) - stab.columns(_("Family Member"), _("Event Type"), + stab.columns(_("Family Member"), _("Event Type"), _("Event Date"), _("Event Place")) for (person, event) in event_list_children: - stab.row(person, sdb.event_type(event), - sdb.event_date_obj(event), + stab.row(person, sdb.event_type(event), + sdb.event_date_obj(event), sdb.event_place(event)) document.has_data = True stab.write(sdoc) diff --git a/gramps/plugins/quickview/all_relations.py b/gramps/plugins/quickview/all_relations.py index c233d5c0f..9a44d70a6 100644 --- a/gramps/plugins/quickview/all_relations.py +++ b/gramps/plugins/quickview/all_relations.py @@ -41,17 +41,17 @@ _FMT_VOID = " %s" _FMT_DET1 = "%-3s %-15s" _FMT_DET2 = "%-30s %-15s\t%-10s %-2s" - + def run(database, document, person): - """ + """ Create the report class, and produce the quick report """ report = AllRelReport(database, document, person) report.run() - + class AllRelReport(): """ - Obtains all relationships, displays the relations, and in details, the + Obtains all relationships, displays the relations, and in details, the relation path """ def __init__(self, database, document, person): @@ -77,11 +77,11 @@ class AllRelReport(): if self.person.handle == self.home_person.handle : self.sdoc.paragraph(_FMT_VOID % ( _("%(person)s and %(active_person)s are the same person.")) % { - 'person' : p1, 'active_person' : p2 }) + 'person' : p1, 'active_person' : p2 }) return #check if not a family too: - is_spouse = self.rel_class.is_spouse(self.database, self.home_person, + is_spouse = self.rel_class.is_spouse(self.database, self.home_person, self.person) if is_spouse: rel_string = is_spouse @@ -94,13 +94,13 @@ class AllRelReport(): #obtain all relationships, assume home person has largest tree common, self.msg_list = self.rel_class.get_relationship_distance_new( self.database, self.person, self.home_person, - all_families=True, - all_dist=True, + all_families=True, + all_dist=True, only_birth=False) #all relations if (not common or common[0][0]== -1 ) and not is_spouse: rstr = _("%(person)s and %(active_person)s are not " - "directly related.") % {'person' : p2, + "directly related.") % {'person' : p2, 'active_person' : p1 } self.sdoc.paragraph(_FMT_VOID % (rstr)) self.sdoc.paragraph("") @@ -111,8 +111,8 @@ class AllRelReport(): skip_list_text=None) self.print_details_path(commonnew, self.home_person, self.person) self.print_details_path(commonnew, self.home_person, self.person, - first=False) - + first=False) + if not common or common[0][0]== -1 : self.remarks(self.msg_list) self.msg_list = [] @@ -120,7 +120,7 @@ class AllRelReport(): else: #stop return - + #we check the inlaw relationships if not partners. if is_spouse: return @@ -141,8 +141,8 @@ class AllRelReport(): common, msg = \ self.rel_class.get_relationship_distance_new( self.database, inlawpers, inlawhome, - all_families=True, - all_dist=True, + all_families=True, + all_dist=True, only_birth=False) if msg: self.msg_list += msg @@ -150,12 +150,12 @@ class AllRelReport(): if not inlawwritten: rstr = _("%(person)s and %(active_person)s have " "following in-law relations:" - ) % {'person' : p2, + ) % {'person' : p2, 'active_person' : p1 } self.sdoc.paragraph(_FMT_VOID % (rstr)) self.sdoc.paragraph("") inlawwritten = True - else: + else: continue inlawb = not inlawpers.handle == self.person.handle inlawa = not inlawhome.handle == self.home_person.handle @@ -165,10 +165,10 @@ class AllRelReport(): skip_text = [] count = 1 for inlawa, inlawb, inlawhome, inlawpers, commonrel in commonnew: - count = self.print_details_header(commonrel, + count = self.print_details_header(commonrel, inlawhome, inlawpers, inlawa = inlawa, inlawb = inlawb, - count=count, + count=count, skip_list=skip, skip_list_text = skip_text) count = 1 for inlawa, inlawb, inlawhome, inlawpers, commonrel in commonnew: @@ -206,15 +206,15 @@ class AllRelReport(): 'person' : p1 ,'active_person' : p2 }) self.sdoc.paragraph("") - def print_details_header(self, relations, pers1, pers2, - inlawa=False, inlawb=False, count=1, + def print_details_header(self, relations, pers1, pers2, + inlawa=False, inlawb=False, count=1, skip_list=[], skip_list_text = []): if not relations or relations[0][0] == -1: return count sdoc = self.sdoc rel_class = self.rel_class - for relation in relations: + for relation in relations: birth = self.rel_class.only_birth(relation[2])\ and self.rel_class.only_birth(relation[4]) distorig = len(relation[4]) @@ -223,15 +223,15 @@ class AllRelReport(): and not inlawb: rel_str = self.rel_class.get_sibling_relationship_string( self.rel_class.get_sibling_type( - self.database, pers1, pers2), + self.database, pers1, pers2), self.home_person.get_gender(), self.person.get_gender()) else: rel_str = self.rel_class.get_single_relationship_string( - distorig, distother, - self.home_person.get_gender(), + distorig, distother, + self.home_person.get_gender(), self.person.get_gender(), - relation[4], relation[2], + relation[4], relation[2], only_birth = birth, in_law_a = inlawa, in_law_b = inlawb) if not skip_list_text is None: @@ -244,8 +244,8 @@ class AllRelReport(): sdoc.paragraph(_FMT % (count, rel_str)) count += 1 return count - - def print_details_path(self, relations, pers1, pers2, + + def print_details_path(self, relations, pers1, pers2, inlawa=False, inlawb=False, count = 1, skip_list = [], first=True): if not relations or relations[0][0] == -1: @@ -260,7 +260,7 @@ class AllRelReport(): if first: pers = p1 inlaw = inlawb - + if count == 1: sdoc.paragraph("") sdoc.header1(_("Detailed path from %(person)s to common ancestor" @@ -273,7 +273,7 @@ class AllRelReport(): if count in skip_list: count += 1 continue - counter = str(count - len([x for x in range(count) if x+1 in skip_list])) + counter = str(count - len([x for x in range(count) if x+1 in skip_list])) name = _('Unknown') if relation[1]: name = self.sdb.name(self.database.get_person_from_handle( @@ -298,17 +298,17 @@ class AllRelReport(): if rel == rel_class.REL_FATHER \ or rel == rel_class.REL_FATHER_NOTBIRTH: par_str = _('Father') - if (rel == rel_class.REL_FAM_BIRTH - or rel == rel_class.REL_FAM_NONBIRTH + if (rel == rel_class.REL_FAM_BIRTH + or rel == rel_class.REL_FAM_NONBIRTH or rel == rel_class.REL_FAM_BIRTH_MOTH_ONLY or rel == rel_class.REL_FAM_BIRTH_FATH_ONLY): par_str = _('Parents') birth_str = _('Yes') - if (rel == rel_class.REL_MOTHER_NOTBIRTH - or rel == rel_class.REL_FATHER_NOTBIRTH + if (rel == rel_class.REL_MOTHER_NOTBIRTH + or rel == rel_class.REL_FATHER_NOTBIRTH or rel == rel_class.REL_FAM_NONBIRTH): birth_str = _('No') - elif (rel == rel_class.REL_FAM_BIRTH_FATH_ONLY + elif (rel == rel_class.REL_FAM_BIRTH_FATH_ONLY or rel == rel_class.REL_FAM_BIRTH_MOTH_ONLY): birth_str = _('Partial') famstr = '' @@ -323,7 +323,7 @@ class AllRelReport(): name = '' count += 1 return count - + def remarks(self, msg_list, inlaw=False): if msg_list : sdoc = self.sdoc @@ -334,7 +334,7 @@ class AllRelReport(): sdoc.header1(_("Remarks")) sdoc.paragraph("") sdoc.paragraph(_("The following problems were encountered:")) - + list(map(sdoc.paragraph, msg_list)) sdoc.paragraph("") sdoc.paragraph("") diff --git a/gramps/plugins/quickview/filterbyname.py b/gramps/plugins/quickview/filterbyname.py index 1fa4c4016..e0d15e883 100644 --- a/gramps/plugins/quickview/filterbyname.py +++ b/gramps/plugins/quickview/filterbyname.py @@ -55,21 +55,21 @@ fname_map = {'all': _('Filtering_on|all'), 'all repositories': _('Filtering_on|all repositories'), 'all media': _('Filtering_on|all media'), 'all notes': _('Filtering_on|all notes'), - 'males': _('Filtering_on|males'), + 'males': _('Filtering_on|males'), 'females': _('Filtering_on|females'), - 'people with unknown gender': - _('Filtering_on|people with unknown gender'), - 'incomplete names': + 'people with unknown gender': + _('Filtering_on|people with unknown gender'), + 'incomplete names': _('Filtering_on|incomplete names'), - 'people with missing birth dates': - _('Filtering_on|people with missing birth dates'), + 'people with missing birth dates': + _('Filtering_on|people with missing birth dates'), 'disconnected people': _('Filtering_on|disconnected people'), 'unique surnames': _('Filtering_on|unique surnames'), - 'people with media': _('Filtering_on|people with media'), + 'people with media': _('Filtering_on|people with media'), 'media references': _('Filtering_on|media references'), - 'unique media': _('Filtering_on|unique media'), + 'unique media': _('Filtering_on|unique media'), 'missing media': _('Filtering_on|missing media'), - 'media by size': _('Filtering_on|media by size'), + 'media by size': _('Filtering_on|media by size'), 'list of people': _('Filtering_on|list of people')} def run(database, document, filter_name, *args, **kwargs): @@ -88,53 +88,53 @@ def run(database, document, filter_name, *args, **kwargs): sdoc.paragraph("") stab.columns(_("Object"), _("Count/Total")) if hasattr(database, "db"): - stab.row([_("People"), "Filter", "Person"], + stab.row([_("People"), "Filter", "Person"], "%d/%d" % (len(database.get_person_handles()), len(database.db.get_person_handles()))) - stab.row([_("Families"), "Filter", "Family"], + stab.row([_("Families"), "Filter", "Family"], "%d/%d" % (len(database.get_family_handles()), len(database.db.get_family_handles()))) - stab.row([_("Events"), "Filter", "Event"], + stab.row([_("Events"), "Filter", "Event"], "%d/%d" % (len(database.get_event_handles()), len(database.db.get_event_handles()))) - stab.row([_("Places"), "Filter", "Place"], + stab.row([_("Places"), "Filter", "Place"], "%d/%d" % (len(database.get_place_handles()), len(database.db.get_place_handles()))) - stab.row([_("Sources"), "Filter", "Source"], + stab.row([_("Sources"), "Filter", "Source"], "%d/%d" % (len(database.get_source_handles()), len(database.db.get_source_handles()))) - stab.row([_("Repositories"), "Filter", "Repository"], + stab.row([_("Repositories"), "Filter", "Repository"], "%d/%d" % (len(database.get_repository_handles()), len(database.db.get_repository_handles()))) - stab.row([_("Media"), "Filter", "MediaObject"], + stab.row([_("Media"), "Filter", "MediaObject"], "%d/%d" % (len(database.get_media_object_handles()), len(database.db.get_media_object_handles()))) - stab.row([_("Notes"), "Filter", "Note"], + stab.row([_("Notes"), "Filter", "Note"], "%d/%d" % (len(database.get_note_handles()), len(database.db.get_note_handles()))) else: - stab.row([_("People"), "Filter", "Person"], + stab.row([_("People"), "Filter", "Person"], "%d/%d" % (len(database.get_person_handles()), len(database.basedb.get_person_handles()))) - stab.row([_("Families"), "Filter", "Family"], + stab.row([_("Families"), "Filter", "Family"], "%d/%d" % (len(database.get_family_handles()), len(database.basedb.get_family_handles()))) - stab.row([_("Events"), "Filter", "Event"], + stab.row([_("Events"), "Filter", "Event"], "%d/%d" % (len(database.get_event_handles()), len(database.basedb.get_event_handles()))) - stab.row([_("Places"), "Filter", "Place"], + stab.row([_("Places"), "Filter", "Place"], "%d/%d" % (len(database.get_place_handles()), len(database.basedb.get_place_handles()))) - stab.row([_("Sources"), "Filter", "Source"], + stab.row([_("Sources"), "Filter", "Source"], "%d/%d" % (len(database.get_source_handles()), len(database.basedb.get_source_handles()))) - stab.row([_("Repositories"), "Filter", "Repository"], + stab.row([_("Repositories"), "Filter", "Repository"], "%d/%d" % (len(database.get_repository_handles()), len(database.basedb.get_repository_handles()))) - stab.row([_("Media"), "Filter", "MediaObject"], + stab.row([_("Media"), "Filter", "MediaObject"], "%d/%d" % (len(database.get_media_object_handles()), len(database.basedb.get_media_object_handles()))) - stab.row([_("Notes"), "Filter", "Note"], + stab.row([_("Notes"), "Filter", "Note"], "%d/%d" % (len(database.get_note_handles()), len(database.basedb.get_note_handles()))) sdoc.paragraph("") @@ -156,7 +156,7 @@ def run(database, document, filter_name, *args, **kwargs): for person in database.db.iter_people(): if person.handle not in proxy_handles: - stab.row(person, person.gramps_id, + stab.row(person, person.gramps_id, sdb.birth_or_fallback(person)) matches += 1 @@ -183,7 +183,7 @@ def run(database, document, filter_name, *args, **kwargs): elif (filter_name == 'Inverse Place'): sdb.dbase = database.db stab.columns(_("Place"), _("Gramps ID")) - proxy_handles = set(database.iter_place_handles()) + proxy_handles = set(database.iter_place_handles()) for place in database.db.iter_places(): if place.handle not in proxy_handles: @@ -193,7 +193,7 @@ def run(database, document, filter_name, *args, **kwargs): elif (filter_name == 'Inverse Source'): sdb.dbase = database.db stab.columns(_("Source"), _("Gramps ID")) - proxy_handles = set(database.iter_source_handles()) + proxy_handles = set(database.iter_source_handles()) for source in database.db.iter_sources(): if source.handle not in proxy_handles: @@ -213,7 +213,7 @@ def run(database, document, filter_name, *args, **kwargs): elif (filter_name == 'Inverse MediaObject'): sdb.dbase = database.db stab.columns(_("Media"), _("Gramps ID")) - proxy_handles = set(database.iter_media_object_handles()) + proxy_handles = set(database.iter_media_object_handles()) for media in database.db.iter_media_objects(): if media.handle not in proxy_handles: @@ -223,7 +223,7 @@ def run(database, document, filter_name, *args, **kwargs): elif (filter_name == 'Inverse Note'): sdb.dbase = database.db stab.columns(_("Note"), _("Gramps ID")) - proxy_handles = set(database.iter_note_handles()) + proxy_handles = set(database.iter_note_handles()) for note in database.db.iter_notes(): if note.handle not in proxy_handles: @@ -338,7 +338,7 @@ def run(database, document, filter_name, *args, **kwargs): elif (filter_name == 'disconnected people'): stab.columns(_("Person"), _("Birth Date"), _("Name type")) for person in database.iter_people(): - if ((not person.get_main_parents_family_handle()) and + if ((not person.get_main_parents_family_handle()) and (not len(person.get_family_handle_list()))): stab.row(person, sdb.birth_or_fallback(person), str(person.get_primary_name().get_type())) @@ -355,7 +355,7 @@ def run(database, document, filter_name, *args, **kwargs): for name in sorted(namelist): stab.row(name, namelist[name]) matches += 1 - stab.set_callback("leftdouble", + stab.set_callback("leftdouble", lambda name: run_quick_report_by_name_direct("samesurnames", database, document, diff --git a/gramps/plugins/quickview/lineage.py b/gramps/plugins/quickview/lineage.py index e8aeba3a8..6d5e4b626 100644 --- a/gramps/plugins/quickview/lineage.py +++ b/gramps/plugins/quickview/lineage.py @@ -62,15 +62,15 @@ def run_father(database, document, person): make_details(Person.MALE, person, sa, sd, database, stab) stab.write(sd) sd.paragraph("") - + if person.gender == Person.FEMALE : return - + sd.header2((_("Direct line male descendants"))) sd.paragraph("") - + make_details_child(Person.MALE, person, sa, sd, database) - + def run_mother(database, document, person): """ Function writing the mother lineage quick report """ @@ -88,28 +88,28 @@ def run_mother(database, document, person): " People in this lineage all share the same Mitochondrial DNA (mtDNA)." )) sd.paragraph("") - + stab = QuickTable(sa) stab.columns(_("Name Mother"), _("Birth"), _("Death Date"), _("Remark")) make_details(Person.FEMALE, person, sa, sd, database, stab) stab.write(sd) sd.paragraph("") - + if person.gender == Person.MALE : return - + sd.header2((_("Direct line female descendants"))) sd.paragraph("") - + make_details_child(Person.FEMALE, person, sa, sd, database) - + def make_details(gender, person, sa, sd, database, stab) : - """ Function writing one line of ancestry on the document in + """ Function writing one line of ancestry on the document in direct lineage """ - # avoid infinite loop: + # avoid infinite loop: personsprinted = 0 - + # loop as long as there are fathers/mothers rem_str = "" while person: @@ -125,7 +125,7 @@ def make_details(gender, person, sa, sd, database, stab) : sd.paragraph(_("ERROR : Too many levels in the tree " "(perhaps a loop?).")) return - + # obtain the first father/mother we find in the list parent_handle_list = person.get_parent_family_handle_list() person = None @@ -133,9 +133,9 @@ def make_details(gender, person, sa, sd, database, stab) : rem_str = "" family_id = parent_handle_list[0] family = database.get_family_from_handle(family_id) - childrel = [(ref.get_mother_relation(), - ref.get_father_relation()) for ref in - family.get_child_ref_list() + childrel = [(ref.get_mother_relation(), + ref.get_father_relation()) for ref in + family.get_child_ref_list() if ref.ref == person_handle] if gender == Person.MALE : person = database.get_person_from_handle( @@ -145,7 +145,7 @@ def make_details(gender, person, sa, sd, database, stab) : person = database.get_person_from_handle( family.get_mother_handle()) refnr = 0 - + #We do not allow for same sex marriages when going up # that would complicate the code #Also, we assume the birth relation is in the FIRST @@ -161,7 +161,7 @@ def make_details(gender, person, sa, sd, database, stab) : person = None def make_details_child(gender, person, sa, sd, database) : - """ Function that prints the details of the children in the + """ Function that prints the details of the children in the male/female lineage """ def make_child_line(child, prepend, generation) : @@ -176,8 +176,8 @@ def make_details_child(gender, person, sa, sd, database) : rem_str = "" if child.gender == Person.UNKNOWN : rem_str = add_rem(rem_str, _("Unknown gender")) - - if rem_str : + + if rem_str : rem_str = _("Remark")+": "+rem_str front = "" if prepend : @@ -198,19 +198,19 @@ def make_details_child(gender, person, sa, sd, database) : else : #something wrong with this family, continue with next continue - childrel = [(ref.ref, ref.get_mother_relation(), - ref.get_father_relation()) for ref in + childrel = [(ref.ref, ref.get_mother_relation(), + ref.get_father_relation()) for ref in fam.get_child_ref_list()] - for childdet in childrel: + for childdet in childrel: #relation with parent must be by birth if not childdet[childrelnr] == ChildRefType.BIRTH : continue - + newchild = database.get_person_from_handle(childdet[0]) # person must have the required gender if newchild and newchild.gender == gender : make_child_line(newchild, prepend + ' |', generation+1) - + # loop over all children of gender and output, start with no prepend try : make_child_line(person, "", 0) diff --git a/gramps/plugins/quickview/linkreferences.py b/gramps/plugins/quickview/linkreferences.py index a0d5c6148..c3f8a732d 100644 --- a/gramps/plugins/quickview/linkreferences.py +++ b/gramps/plugins/quickview/linkreferences.py @@ -58,7 +58,7 @@ def run(database, document, obj): tagtype = _("Internet") tagvalue = lvalue tagcheck = "" - stab.row(tagtype, tagvalue, tagcheck) + stab.row(tagtype, tagvalue, tagcheck) if stab.get_row_count() > 0: stab.write(sdoc) diff --git a/gramps/plugins/quickview/onthisday.py b/gramps/plugins/quickview/onthisday.py index 8a27cb99c..590e4c231 100644 --- a/gramps/plugins/quickview/onthisday.py +++ b/gramps/plugins/quickview/onthisday.py @@ -53,7 +53,7 @@ def get_ref(db, objclass, handle): def run(database, document, main_event): """ Displays events on a specific date of an event (or date) - + Takes an Event or Date object """ if isinstance(main_event, Date): @@ -74,39 +74,39 @@ def run(database, document, main_event): histab.set_link_col(3) # display the title - sdoc.title(_("Events of %(date)s") % + sdoc.title(_("Events of %(date)s") % {"date": sdb.date_string(main_date)}) sdoc.paragraph("") stab.columns(_("Date"), _("Type"), _("Place"), _("Reference")) yeartab.columns(_("Date"), _("Type"), _("Place"), _("Reference")) histab.columns(_("Date"), _("Type"), _("Place"), _("Reference")) - + for event in database.iter_events(): date = event.get_date_object() date.convert_calendar(cal) if date.get_year() == 0: continue - if (date.get_year() == main_date.get_year() and + if (date.get_year() == main_date.get_year() and date.get_month() == main_date.get_month() and date.get_day() == main_date.get_day()): for (objclass, handle) in database.find_backlink_handles(event.handle): ref = get_ref(database, objclass, handle) - stab.row(date, - sdb.event_type(event), + stab.row(date, + sdb.event_type(event), sdb.event_place(event), ref) elif (date.get_month() == main_date.get_month() and date.get_day() == main_date.get_day() and date.get_month() != 0): for (objclass, handle) in database.find_backlink_handles(event.handle): ref = get_ref(database, objclass, handle) - histab.row(date, - sdb.event_type(event), + histab.row(date, + sdb.event_type(event), sdb.event_place(event), ref) elif (date.get_year() == main_date.get_year()): for (objclass, handle) in database.find_backlink_handles(event.handle): ref = get_ref(database, objclass, handle) - yeartab.row(date, - sdb.event_type(event), + yeartab.row(date, + sdb.event_type(event), sdb.event_place(event), ref) document.has_data = False @@ -130,11 +130,11 @@ def run(database, document, main_event): if yeartab.get_row_count() > 0: document.has_data = True - sdoc.paragraph(_("Other events in %(year)d") % + sdoc.paragraph(_("Other events in %(year)d") % {"year":main_date.get_year()}) yeartab.write(sdoc) else: - sdoc.paragraph(_("No other events in %(year)d") % + sdoc.paragraph(_("No other events in %(year)d") % {"year":main_date.get_year()}) sdoc.paragraph("") sdoc.paragraph("") diff --git a/gramps/plugins/quickview/quickview.gpr.py b/gramps/plugins/quickview/quickview.gpr.py index 38670654f..831205954 100644 --- a/gramps/plugins/quickview/quickview.gpr.py +++ b/gramps/plugins/quickview/quickview.gpr.py @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # @@ -27,7 +27,7 @@ MODULE_VERSION="5.0" # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'ageondate', name = _("Age on Date"), description = _("Display people and ages on a particular date"), @@ -47,7 +47,7 @@ runfunc = 'run' # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'attribute_match', name = _("Attribute Match"), description = _("Display people with same attribute."), @@ -67,7 +67,7 @@ runfunc = 'run' # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'all_events', name = _("All Events"), description = _("Display a person's events, both personal and family."), @@ -82,7 +82,7 @@ runfunc = 'run' ) -register(QUICKREPORT, +register(QUICKREPORT, id = 'all_events_fam', name = _("All Family Events"), description = _("Display the family and family members events."), @@ -102,7 +102,7 @@ runfunc = 'run_fam' # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'all_relations', name = _("Relation to Home Person"), description = _("Display all relationships between person and home person."), @@ -122,7 +122,7 @@ runfunc = 'run' # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'filterbyname', name = _("Filter"), description = _("Display filtered data"), @@ -142,7 +142,7 @@ runfunc = 'run' # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'father_lineage', name = _("Father lineage"), description = _("Display father lineage"), @@ -156,7 +156,7 @@ category = CATEGORY_QR_PERSON, runfunc = 'run_father' ) -register(QUICKREPORT, +register(QUICKREPORT, id = 'mother_lineage', name = _("Mother lineage"), description = _("Display mother lineage"), @@ -169,14 +169,14 @@ authors_email = ["benny.malengier@gramps-project.org"], category = CATEGORY_QR_PERSON, runfunc = 'run_mother' ) - + #------------------------------------------------------------------------ # # On This Day # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'onthisday', name = _("On This Day"), description = _("Display events on a particular day"), @@ -196,20 +196,20 @@ runfunc = 'run' # #------------------------------------------------------------------------ -refitems = [(CATEGORY_QR_PERSON, 'person', _("Person")), - (CATEGORY_QR_FAMILY,'family', _("Family")), - (CATEGORY_QR_EVENT, 'event', _("Event")), - (CATEGORY_QR_SOURCE, 'source', _("Source")), - (CATEGORY_QR_PLACE, 'place', _("Place")), - (CATEGORY_QR_MEDIA, 'media', _("Media")), - (CATEGORY_QR_NOTE, 'note', _("Note")), +refitems = [(CATEGORY_QR_PERSON, 'person', _("Person")), + (CATEGORY_QR_FAMILY,'family', _("Family")), + (CATEGORY_QR_EVENT, 'event', _("Event")), + (CATEGORY_QR_SOURCE, 'source', _("Source")), + (CATEGORY_QR_PLACE, 'place', _("Place")), + (CATEGORY_QR_MEDIA, 'media', _("Media")), + (CATEGORY_QR_NOTE, 'note', _("Note")), (CATEGORY_QR_CITATION, 'citation', _("Citation")), - (CATEGORY_QR_SOURCE_OR_CITATION, 'source or citation', + (CATEGORY_QR_SOURCE_OR_CITATION, 'source or citation', _("Source or Citation")) ] for (category, item, trans) in refitems: - register(QUICKREPORT, + register(QUICKREPORT, id = item + 'references', name = _("%s References") % trans, description = _("Display references for a %s") % trans, @@ -223,7 +223,7 @@ for (category, item, trans) in refitems: runfunc = 'run_%s' % item ) -register(QUICKREPORT, +register(QUICKREPORT, id = 'link_references', name = _("Link References"), description = _("Display link references for a note"), @@ -243,7 +243,7 @@ register(QUICKREPORT, # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'RepoRef', name = _("Repository References"), description = _("Display the repository reference for sources related to" @@ -264,7 +264,7 @@ runfunc = 'run' # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'samesurnames', name = _("Same Surnames"), description = _("Display people with the same surname as a person."), @@ -278,7 +278,7 @@ category = CATEGORY_QR_PERSON, runfunc = 'run' ) -register(QUICKREPORT, +register(QUICKREPORT, id = 'samegivens', name = _("Same Given Names"), description = _("Display people with the same given name as a person."), @@ -292,7 +292,7 @@ category = CATEGORY_QR_PERSON, runfunc = 'run_given' ) -register(QUICKREPORT, +register(QUICKREPORT, id = 'samegivens_misc', name = _("Same Given Names - stand-alone"), description = _("Display people with the same given name as a person."), @@ -311,7 +311,7 @@ runfunc = 'run_given' # siblings # #------------------------------------------------------------------------ -register(QUICKREPORT, +register(QUICKREPORT, id = 'siblings', name = _("Siblings"), description = _("Display a person's siblings."), diff --git a/gramps/plugins/quickview/references.py b/gramps/plugins/quickview/references.py index 751760944..eaf499d02 100644 --- a/gramps/plugins/quickview/references.py +++ b/gramps/plugins/quickview/references.py @@ -87,7 +87,7 @@ run_family = lambda db, doc, obj: run(db, doc, obj, 'family', _("Family")) run_event = lambda db, doc, obj: run(db, doc, obj, 'event', _("Event")) run_source = lambda db, doc, obj: run(db, doc, obj, 'source', _("Source")) run_citation = lambda db, doc, obj: run(db, doc, obj, 'citation', _("Citation")) -run_source_or_citation = lambda db, doc, obj: run(db, doc, obj, +run_source_or_citation = lambda db, doc, obj: run(db, doc, obj, 'source or citation', _("Source or Citation")) run_place = lambda db, doc, obj: run(db, doc, obj, 'place', _("Place")) run_media = lambda db, doc, obj: run(db, doc, obj, 'media', _("Media")) diff --git a/gramps/plugins/quickview/samesurnames.py b/gramps/plugins/quickview/samesurnames.py index 63e040076..d7263a047 100644 --- a/gramps/plugins/quickview/samesurnames.py +++ b/gramps/plugins/quickview/samesurnames.py @@ -119,7 +119,7 @@ def run(database, document, person): else: rule = IncompleteSurname([]) filter.add_rule(rule) - people = filter.apply(database, + people = filter.apply(database, database.iter_person_handles()) matches = 0 @@ -164,9 +164,9 @@ def run_given(database, document, person): else: rule = IncompleteGiven([]) filter.add_rule(rule) - people = filter.apply(database, + people = filter.apply(database, database.iter_person_handles()) - + matches = 0 for person_handle in people: person = database.get_person_from_handle(person_handle) diff --git a/gramps/plugins/quickview/siblings.py b/gramps/plugins/quickview/siblings.py index 4bbc03c1e..7f416b74f 100644 --- a/gramps/plugins/quickview/siblings.py +++ b/gramps/plugins/quickview/siblings.py @@ -56,14 +56,14 @@ def run(database, document, person): # only display if this child is not the active person if sdb.gid(child) != gid: rel_str = rel_class.get_sibling_relationship_string( - rel_class.get_sibling_type(database, person, child), + rel_class.get_sibling_type(database, person, child), person.get_gender(), child.get_gender()) else: rel_str = _('self') # pass row the child object to make link: - stab.row(child, - sdb.gender(child), - sdb.birth_or_fallback(child), + stab.row(child, + sdb.gender(child), + sdb.birth_or_fallback(child), rel_str) document.has_data = True stab.write(sdoc) diff --git a/gramps/plugins/rel/rel_ca.py b/gramps/plugins/rel/rel_ca.py index a973f16c0..e8f5896d4 100644 --- a/gramps/plugins/rel/rel_ca.py +++ b/gramps/plugins/rel/rel_ca.py @@ -884,7 +884,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): # than the first person. rel_str = _get_nebots_valencians(Ga, Gb, inlaw) - + else: rel_str = "Error in get_plural_relationship_string()" @@ -977,7 +977,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "la cunyada" else: # gender_b == Person.UNKNOWN: rel_str = "un cunyat" - + elif gender_b == Person.MALE : rel_str = _get_uncle(Ga, inlaw, step) elif gender_b == Person.FEMALE : @@ -1109,7 +1109,7 @@ if __name__ == "__main__": # (Above not needed here) #"" - # TRANSLATORS, copy this if statement at the bottom of your + # TRANSLATORS, copy this if statement at the bottom of your # rel_xx.py module, and test your work with: # python src/plugins/rel/rel_xx.py #"" diff --git a/gramps/plugins/rel/rel_cs.py b/gramps/plugins/rel/rel_cs.py index 90dc98359..f8fa57d1e 100644 --- a/gramps/plugins/rel/rel_cs.py +++ b/gramps/plugins/rel/rel_cs.py @@ -37,7 +37,7 @@ import gramps.gen.relationship #------------------------------------------------------------------------- # -# Czech-specific definitions of relationships +# Czech-specific definitions of relationships # #------------------------------------------------------------------------- @@ -149,8 +149,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_relationship(self, secondRel, firstRel, orig_person_gender, other_person_gender): """ Return a string representing the relationshp between the two people, - along with a list of common ancestors (typically father,mother) - + along with a list of common ancestors (typically father,mother) + Special cases: relation strings "", "undefined" and "spouse". """ @@ -206,11 +206,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): return self.get_relationship(Ga, Gb, gender_a, gender_b)[0]; - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): return self.get_relationship(1, 1, gender_a, gender_b)[0]; @@ -222,7 +222,7 @@ if __name__ == "__main__": # python src/plugins/rel/rel_cs.py # (Above not needed here) - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_da.py b/gramps/plugins/rel/rel_da.py index 53865455d..eeac9f6b2 100644 --- a/gramps/plugins/rel/rel_da.py +++ b/gramps/plugins/rel/rel_da.py @@ -178,11 +178,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): return self.get_relationship(reltocommon_a, reltocommon_b, gender_a, gender_b)[0] - - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): return self.get_two_way_rel(gender_b, "", "") @@ -194,7 +194,7 @@ if __name__ == "__main__": # python src/plugins/rel/rel_da.py # (Above not needed here) - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_de.py b/gramps/plugins/rel/rel_de.py index 830cd7f76..9ad5de03a 100644 --- a/gramps/plugins/rel/rel_de.py +++ b/gramps/plugins/rel/rel_de.py @@ -201,7 +201,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if degree == 0 and removed < 0: # for descendants the "in-law" logic is reversed - (in_law_a, in_law_b) = (in_law_b, in_law_a) + (in_law_a, in_law_b) = (in_law_b, in_law_a) rel_str = '' pre = '' @@ -267,7 +267,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): reltocommon_a, reltocommon_b, only_birth, in_law_a, in_law_b) - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): if sib_type in [self.NORM_SIB, self.UNKNOWN_SIB]: # the NORM_SIB translation is generic and suitable for UNKNOWN_SIB @@ -291,11 +291,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if __name__ == "__main__": # Test function. Call it as follows from the command line (so as to find # imported modules): - # export PYTHONPATH=/path/to/gramps/src - # python src/plugins/rel/rel_de.py + # export PYTHONPATH=/path/to/gramps/src + # python src/plugins/rel/rel_de.py # (Above not needed here) - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_es.py b/gramps/plugins/rel/rel_es.py index 115ac02bc..d2aa02b3c 100644 --- a/gramps/plugins/rel/rel_es.py +++ b/gramps/plugins/rel/rel_es.py @@ -100,7 +100,7 @@ _mother_level = [ "", "madre%(inlaw)s", # other marry again. Divorce is common now, so these relationships abound, but history has left us # without support in the language. So, in this case, we will be more liberal than in other cases and # or coin a few new words or accept others that seem to have some use, but always patterned -# after the style of the well-documented cases, so that users can intuitively guess their meaning. +# after the style of the well-documented cases, so that users can intuitively guess their meaning. # Notice that "that relationship does not exist in Spanish" is not a valid objection. Once the Gramps # core has computed a relationship, it *has* to be named *somehow*. The only alternative is to change # the Gramps core so that it does not find relationships that cannot be named in Spanish. @@ -140,7 +140,7 @@ _son_level = [ "", "hijo%(inlaw)s", _step_son_level = [ "", "hijastro%(inlaw)s", "nietastro%(inlaw)s" ] -_daughter_level = [ "", "hija%(inlaw)s", +_daughter_level = [ "", "hija%(inlaw)s", "nieta%(inlaw)s", "bisnieta%(inlaw)s", "tataranieta%(inlaw)s", @@ -480,7 +480,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return "%s %s%s" % (prim,_level_name_male[level], inlaw) else: return "%s %d-ésimo%s" % (prim, level, inlaw) - elif removed > 0 and lower: + elif removed > 0 and lower: if gender_c == MALE: return "%s de un %s" % (self._get_son(removed,step,inlaw), self._get_male_cousin(level, 0, lower, step, inlaw, gender_c)) @@ -500,7 +500,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: return "%s de un %s" % (self._get_male_cousin(level, 0, lower, step, inlaw, gender_c), self._get_father(removed,step,inlaw)) - + else: return "%s %scousin%s (%d-%d)" % (_level_name[level], step, inlaw, @@ -521,7 +521,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return "%s %s%s" % (prim,_level_name_female[level], inlaw) else: return "%s %d-ésima%s" % (prim, level, inlaw) - elif removed > 0 and lower: + elif removed > 0 and lower: if gender_c == MALE: return "%s de un %s" % (self._get_daughter(removed,step,inlaw), self._get_male_cousin(level, 0, lower, step, inlaw, gender_c)) @@ -541,7 +541,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: return "%s de un %s" % (self._get_female_cousin(level, 0, lower, step, inlaw, gender_c), self._get_father(removed,step,inlaw)) - + else: return "%s %sprima%s (%d-%d)" % (_level_name[level], step, inlaw, @@ -616,28 +616,28 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: rel_str = "sobrinos %d-ésimos" % (Gb-1) elif Ga > 1 and Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. rel_str = "%s de los %s" % ( self.get_plural_relationship_string(0, Gb), self.get_plural_relationship_string(Ga, 0) ) elif Gb > 1 and Gb > Ga: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. rel_str = "%s de los %s" % ( self.get_plural_relationship_string(0, Gb), self.get_plural_relationship_string(Ga, 0) ) - + if in_law_b == True: rel_str = "cónyuges de los %s" % rel_str - + return rel_str - + def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): """Spanish version of method to create relation string - check relationship.py """ @@ -695,10 +695,10 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): elif Ga == Gb: # a and b cousins in the same generation if gender_b == MALE: - rel_str = self._get_male_cousin(Ga-1, 0, lower=False, step=step, + rel_str = self._get_male_cousin(Ga-1, 0, lower=False, step=step, inlaw=inlaw) elif gender_b == FEMALE: - rel_str = self._get_female_cousin(Ga-1, 0, lower=False, step=step, + rel_str = self._get_female_cousin(Ga-1, 0, lower=False, step=step, inlaw=inlaw) else: rel_str = "%s o %s" % (self._get_male_cousin(Ga-1, 0, step=step, inlaw=inlaw), @@ -720,8 +720,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "%s o %s" % (self._get_distant_nephew(Gb-1, 0, step=step, inlaw=inlaw), self._get_distant_niece(Gb-1, 0, step=step, inlaw=inlaw)) elif Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. # We need to know the gender of the ancestor of the first person who is on # the same generation as the other person @@ -732,10 +732,10 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: gender_c = UNKNOWN if gender_b == MALE: - rel_str = self._get_male_cousin(Gb-1, Ga-Gb, lower=False, + rel_str = self._get_male_cousin(Gb-1, Ga-Gb, lower=False, step=step, inlaw=inlaw, gender_c=gender_c) elif gender_b == FEMALE: - rel_str = self._get_female_cousin(Gb-1, Ga-Gb, lower=False, + rel_str = self._get_female_cousin(Gb-1, Ga-Gb, lower=False, step=step, inlaw=inlaw, gender_c=gender_c) else: rel_str = "%s o %s" % (self._get_male_cousin(Gb-1, Ga-Gb, lower=False, @@ -744,8 +744,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): step=step, inlaw=inlaw)) elif Gb > Ga: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. # We need to know the gender of the person who is an ancestor of the second person and # is on the same generation that the first person @@ -756,10 +756,10 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: gender_c = UNKNOWN if gender_b == MALE: - rel_str = self._get_male_cousin(Ga-1, Gb-Ga, lower=True, + rel_str = self._get_male_cousin(Ga-1, Gb-Ga, lower=True, step=step, inlaw=inlaw, gender_c=gender_c) elif gender_b == FEMALE: - rel_str = self._get_female_cousin(Ga-1, Gb-Ga, lower=True, + rel_str = self._get_female_cousin(Ga-1, Gb-Ga, lower=True, step=step, inlaw=inlaw, gender_c=gender_c) else: rel_str = "%s o %s" % (self._get_male_cousin(Ga-1, Gb-Ga, lower=True, @@ -769,7 +769,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return rel_str - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): """ """ @@ -810,7 +810,7 @@ if __name__ == "__main__": # python src/plugins/rel/rel_es.py # (Above not needed here) - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_fi.py b/gramps/plugins/rel/rel_fi.py index 280975f75..0fb6329a1 100644 --- a/gramps/plugins/rel/rel_fi.py +++ b/gramps/plugins/rel/rel_fi.py @@ -195,11 +195,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): return self.get_relationship(reltocommon_a, reltocommon_b, gender_a, gender_b)[0] - - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): if gender_b == Person.MALE: return self.get_ancestors_brother("") @@ -214,7 +214,7 @@ if __name__ == "__main__": # python src/plugins/rel/rel_fi.py # (Above not needed here) - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_fr.py b/gramps/plugins/rel/rel_fr.py index 3a574b6c3..e69cfce31 100644 --- a/gramps/plugins/rel/rel_fr.py +++ b/gramps/plugins/rel/rel_fr.py @@ -529,10 +529,10 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "les neveux et nièces" + can + civ elif Ga < len(_LEVEL_NAME): rel_str = "les neveux et nièces" + bygen % Gb - + if in_law_b == True: rel_str = "les conjoints pour %s" % rel_str - + return rel_str # quick report (missing on RelCalc tool - Status Bar) @@ -850,7 +850,7 @@ if __name__ == "__main__": # python src/plugins/rel/rel_fr.py # (Above not needed here) - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_hr.py b/gramps/plugins/rel/rel_hr.py index 80348a28a..d56e15fa6 100644 --- a/gramps/plugins/rel/rel_hr.py +++ b/gramps/plugins/rel/rel_hr.py @@ -37,7 +37,7 @@ _PARENTS = ['', 'otac i majka', 'djedovi i bake', 'pradjedovi i prabake', _CHILDS = ['', 'djeca', 'unučad', 'praunučad', '%s praunučad'] _CHILDS_SP = ['', 'snahe i zetovi', 'prasnahe i prazetovi', 'supružnici praunučadi', 'supružnici %s praunučadi'] - + #------------------------------------------------------------------------- # # Class HrDeclination @@ -61,7 +61,7 @@ class HrDeclination(object): (1, 1, 7): 'im', (2, 1, 7): 'im', (1, 2, 3): 'im', (1, 2, 6): 'im', (1, 2, 7): 'im', (0, 2, 3): 'im', (0, 2,6): 'im', (0, 2, 7): 'im', (0, 1, 1): 'a', (0, 1, 5): 'a', (2, 2, 1): 'a', (2, 2, 5): 'a', - (0, 1, 2): 'e', (0, 1, 4): 'e', (1, 2, 4): 'e', + (0, 1, 2): 'e', (0, 1, 4): 'e', (1, 2, 4): 'e', (0, 2, 1): 'e', (0, 2, 4): 'e', (0, 2, 5): 'e', (2 , 1, 1): 'o', (2, 1, 4): 'o', (2, 1, 5): 'o', (0, 1, 3): 'oj', (0, 1, 6): 'oj', (2, 2, 3): 'oj', (2, 2, 6): 'oj', @@ -69,7 +69,7 @@ class HrDeclination(object): (2, 2, 4): 'u' } def get_ordnum(self, num, gender, number, case): - """ + """ Declination of ordinal numbers gender: 0 = feminine, 1 = masculine, 2 = neuter case: 1 = nominative, 2 = genitive, 3 = dative, 4 = accusative @@ -89,7 +89,7 @@ class HrDeclination(object): if num % 10 == 3: if gender != 0 and sufix != 'oj': sufix = sufix.replace('o','e') - lres[-1] += sufix + lres[-1] += sufix res = ' '.join(lres) else: res = str(num) + '. ' @@ -117,27 +117,27 @@ def _get_parents(level): if level < 4: return _PARENTS[level] else: - return '%s' % _PARENTS[4] % (HRDN(level-2, 1, 1, 1), + return '%s' % _PARENTS[4] % (HRDN(level-2, 1, 1, 1), HRDN(level-2, 0, 2, 1)) - + def _get_uncles(gen, inlaw): """ in general: uncles, ants--- """ if gen == 2: if not inlaw: return 'stričevi, ujaci i tetke' - else: - return 'strine, ujne i tetci' + else: + return 'strine, ujne i tetci' elif gen == 3: if not inlaw: return 'prastričevi, praujaci i pratetke' - else: + else: return 'prastrine, praujne i pratetci' else: if not inlaw: return '%s prastričevi, %s praujaci i %s pratetke' % (HRDN(gen-2, 1, 2, 1), HRDN(gen-2, 1, 2, 1), HRDN(gen-2, 0, 2, 1)) - else: + else: return 'prastrine, praujne i pratetci' #------------------------------------------------------------------------- @@ -183,7 +183,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): # These are aunts/uncles rel_str += _get_uncles(gena, in_law_b) return rel_str - + if __name__ == "__main__": # Test function. Call it as follows from the command line (so as to find diff --git a/gramps/plugins/rel/rel_hu.py b/gramps/plugins/rel/rel_hu.py index 7abe8cfab..666dc4d5a 100644 --- a/gramps/plugins/rel/rel_hu.py +++ b/gramps/plugins/rel/rel_hu.py @@ -137,7 +137,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_age_comp(self, orig_person, other_person): # in 3.X api we can't know persons age return 0 - + def get_age_brother (self, level): if level == 0 : return "testvére" @@ -151,7 +151,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): #--------------------------------------------- # - # en: father-in-law, mother-in-law, son-in-law, daughter-in-law + # en: father-in-law, mother-in-law, son-in-law, daughter-in-law # hu: após, anyós, vő, meny # #--------------------------------------------- @@ -161,14 +161,14 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): family = self.db.get_family_from_handle(f) sp_id = None if family: - if other == family.get_father_handle(): + if other == family.get_father_handle(): sp_id = family.get_mother_handle() - elif other == family.get_mother_handle(): + elif other == family.get_mother_handle(): sp_id = family.get_father_handle() for g in orig.get_family_handle_list(): family = self.db.get_family_from_handle(g) if family: - if sp_id in family.get_child_handle_list(): + if sp_id in family.get_child_handle_list(): return 1 return 0 @@ -184,16 +184,16 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): family = self.db.get_family_from_handle(f) sp_id = None if family: - if orig == family.get_father_handle(): + if orig == family.get_father_handle(): sp_id = family.get_mother_handle() - elif other == family.get_mother_handle(): + elif other == family.get_mother_handle(): sp_id = family.get_father_handler() p = other.get_main_parents_family_handle() family = self.db.get_family_from_handle(p) if family: c = family.get_child_handle_list() - if (other.get_handle() in c) and (sp_id in c): + if (other.get_handle() in c) and (sp_id in c): return 1 return 0 @@ -274,11 +274,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): return self.get_relationship(Ga, Gb, gender_a, gender_b, in_law_a, in_law_b)[0] - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): return self.get_relationship(1, 1, gender_a, gender_b, in_law_a, in_law_b)[0] @@ -290,7 +290,7 @@ if __name__ == "__main__": # python src/plugins/rel/rel_hu.py # (Above not needed here) - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_it.py b/gramps/plugins/rel/rel_it.py index 3a10242b5..bc6b48b68 100644 --- a/gramps/plugins/rel/rel_it.py +++ b/gramps/plugins/rel/rel_it.py @@ -46,56 +46,56 @@ import gramps.gen.relationship #------------------------------------------------------------------------- _level = [ - "", "prim%(gen)s", "second%(gen)s", "terz%(gen)s", "quart%(gen)s", + "", "prim%(gen)s", "second%(gen)s", "terz%(gen)s", "quart%(gen)s", "quint%(gen)s", "sest%(gen)s", - "settim%(gen)s", "ottav%(gen)s", "non%(gen)s", "decim%(gen)s", + "settim%(gen)s", "ottav%(gen)s", "non%(gen)s", "decim%(gen)s", "undicesim%(gen)s", "dodicesim%(gen)s", "tredicesim%(gen)s", "quattordicesim%(gen)s", "quindicesim%(gen)s", - "sedicesim%(gen)s", "diciasettesim%(gen)s", "diciottesim%(gen)s", + "sedicesim%(gen)s", "diciasettesim%(gen)s", "diciottesim%(gen)s", "diciannovesim%(gen)s", "ventesim%(gen)s" ] _level_m = [ - "", "primo", "secondo", "terzo", "quarto", + "", "primo", "secondo", "terzo", "quarto", "quinto", "sesto", - "settimo", "ottavo", "nono", "decimo", + "settimo", "ottavo", "nono", "decimo", "undicesimo", "dodicesimo", "tredicesimo", "quattordicesimo", "quindicesimo", - "sedicesimo", "diciasettesimo", "diciottesimo", + "sedicesimo", "diciasettesimo", "diciottesimo", "diciannovesimo", "ventesimo" ] _level_f = [ - "", "prima", "seconda", "terza", "quarta", + "", "prima", "seconda", "terza", "quarta", "quinta", "sesta", - "settima", "ottava", "nona", "decima", + "settima", "ottava", "nona", "decima", "undicesima", "dodicesima", "tredicesima", "quattordicesima", "quindicesima", - "sedicesima", "diciasettesima", "diciottesima", + "sedicesima", "diciasettesima", "diciottesima", "diciannovesima", "ventesima" ] -_father_level = [ "", - "il padre%(step)s%(inlaw)s", - "il nonno%(step)s%(inlaw)s", - "il bisnonno%(step)s%(inlaw)s", +_father_level = [ "", + "il padre%(step)s%(inlaw)s", + "il nonno%(step)s%(inlaw)s", + "il bisnonno%(step)s%(inlaw)s", "il trisnonno%(step)s%(inlaw)s", ] -_mother_level = [ "", - "la madre%(step)s%(inlaw)s", - "la nonna%(step)s%(inlaw)s", - "la bisnonna%(step)s%(inlaw)s", +_mother_level = [ "", + "la madre%(step)s%(inlaw)s", + "la nonna%(step)s%(inlaw)s", + "la bisnonna%(step)s%(inlaw)s", "la trisnonna%(step)s%(inlaw)s", ] _son_level = [ "", "il figlio%(step)s%(inlaw)s", - "il nipote%(step)s%(inlaw)s diretto", + "il nipote%(step)s%(inlaw)s diretto", "il pronipote%(step)s%(inlaw)s diretto" ] _daughter_level = [ "", "la figlia%(step)s%(inlaw)s", - "la nipote%(step)s%(inlaw)s diretta", + "la nipote%(step)s%(inlaw)s diretta", "la pronipote%(step)s%(inlaw)s diretta" ] @@ -126,9 +126,9 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): """ RelationshipCalculator Class """ - + INLAW = ' acquisit%(gen)s' - + STEP = ' adottiv%(gen)s' def __init__(self): @@ -143,12 +143,12 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): # please, drop me an email. # #------------------------------------------------------------------------- - + def __gen_suffix(self, gender): if gender == Person.MALE: return 'o' return 'a' - + def get_parents (self, level): if level > len(_level)-1: return "remote ancestors" @@ -157,7 +157,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_father (self, level, step='', inlaw=''): gen = "o" - + if level < len(_father_level): return _father_level[level] % {'step': step, 'inlaw': inlaw} \ % {'gen': gen} @@ -172,7 +172,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_mother (self, level, step='', inlaw=''): gen = "a" - + if level < len(_father_level): return _mother_level[level] % {'step': step, 'inlaw': inlaw} \ % {'gen': gen} @@ -187,7 +187,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_parent_unknown(self, level, step='', inlaw=''): gen = "o/a" - + if level == 1: return "uno dei genitori%(step)s%(inlaw)s" % {'step': step, 'inlaw': inlaw} \ % {'gen': gen} @@ -297,7 +297,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): "(%(levA)d-%(levB)d)" \ % {'level': levelA+levelB-1, 'step': step, 'inlaw': inlaw, - 'levA': levelA, + 'levA': levelA, 'levB': levelB} % {'gen': gen} def get_female_cousin (self, levelA, levelB, step="", inlaw=""): @@ -306,7 +306,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): "(%(levA)d-%(levB)d)" \ % {'level': levelA+levelB-1, 'step': step, 'inlaw': inlaw, - 'levA': levelA, + 'levA': levelA, 'levB': levelB} % {'gen': gen} #------------------------------------------------------------------------- @@ -331,7 +331,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if is_spouse: return (is_spouse, []) - #get_relationship_distance changed, first data is relation to + #get_relationship_distance changed, first data is relation to #orig person, apperently secondRel in this function (secondRel, firstRel, common) = \ self.get_relationship_distance(db, orig_person, other_person) @@ -376,7 +376,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): """ See Comment in Relationship Class (relationship.py) @@ -458,16 +458,16 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = self.get_female_cousin(Gb-1, Ga-1, step, inlaw) return rel_str - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): """ Determine the string giving the relation between two siblings of type sib_type. Eg: b is the brother of a Here 'brother' is the string we need to determine - This method gives more details about siblings than + This method gives more details about siblings than get_single_relationship_string can do. - + .. warning:: DON'T TRANSLATE THIS PROCEDURE IF LOGIC IS EQUAL IN YOUR LANGUAGE, AND SAME METHODS EXIST (get_uncle, get_aunt, get_sibling) @@ -476,7 +476,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): inlaw = self.INLAW else: inlaw = '' - + if sib_type == self.NORM_SIB or sib_type == self.UNKNOWN_SIB: if not inlaw: if gender_b == Person.MALE: @@ -514,10 +514,10 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if __name__ == "__main__": # Test function. Call it as follows from the command line (so as to find # imported modules): - # export PYTHONPATH=/path/to/gramps/src - # python src/plugins/rel/rel_it.py - - """TRANSLATORS, copy this if statement at the bottom of your + # export PYTHONPATH=/path/to/gramps/src + # python src/plugins/rel/rel_it.py + + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_nl.py b/gramps/plugins/rel/rel_nl.py index 67909d73c..ef48e35ee 100644 --- a/gramps/plugins/rel/rel_nl.py +++ b/gramps/plugins/rel/rel_nl.py @@ -52,7 +52,7 @@ _removed_level = [ " ", " elfde", " twaalfde", " dertiende", - " veertiende", + " veertiende", " vijftiende", " zestiende", " zeventiende", @@ -60,7 +60,7 @@ _removed_level = [ " ", " negentiende", " twintigste", " eenentwintigste", - " tweeëntwintigste", + " tweeëntwintigste", " drieëntwingste", " vierentwingste", " vijfentwintigste", @@ -197,7 +197,7 @@ _ouder_level = [ "", _son_level = [ "", "%s%szoon", "%s%skleinzoon", - "%s%sachterkleinzoon", + "%s%sachterkleinzoon", "%s%sachterachterkleinzoon", "%s%sachterachterachterkleinzoon"] @@ -222,16 +222,16 @@ _nephew_level = [ "", _niece_level = [ "", "%s%snicht", - "%s%sachternicht", + "%s%sachternicht", "%s%sachterachternicht"] -_aunt_level = [ "", - "%s%stante", +_aunt_level = [ "", + "%s%stante", "%s%sgroottante", "%s%sovergroottante", "%s%sbetovergroottante", "%s%soudtante"] -_uncle_level = [ "", +_uncle_level = [ "", "%s%soom", "%s%sgrootoom", "%s%sovergrootoom", @@ -246,11 +246,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): """ RelationshipCalculator Class """ - + #sibling strings STEP = 'stief' HALF = 'half' - + INLAW = 'aangetrouwde ' def __init__(self): @@ -291,7 +291,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): """Internal Dutch method to create relation string """ if level > len(_daughter_level)-1: - return "verre %s%sachterkleindochter (%d generaties)" % (inlaw, + return "verre %s%sachterkleindochter (%d generaties)" % (inlaw, step, level) else: return _daughter_level[level] % (inlaw, step) @@ -311,7 +311,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): """Internal Dutch method to create relation string """ if level > len(_kind_level)-1: - return "ver %s%sachterkleinkind (%d generaties)" % (inlaw, step, + return "ver %s%sachterkleinkind (%d generaties)" % (inlaw, step, level) else: return _kind_level[level] % (inlaw, step) @@ -331,8 +331,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): step, _removed_level[removed], level) else: return _aunt_level[level] % (inlaw, step) \ - + _removed_level[removed] + " graad" - + + _removed_level[removed] + " graad" + def _get_uncle(self, level, removed, step='', inlaw=''): """Internal Dutch method to create relation string """ @@ -341,7 +341,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): elif removed == 1: return "verre %s%soom (%d generaties)" % (inlaw, step, level) elif level > len(_uncle_level)-1 and removed > len(_removed_level) -1: - return "verre %s%soom (%d generaties, %d graden)" % (inlaw, step, + return "verre %s%soom (%d generaties, %d graden)" % (inlaw, step, level, removed) elif level > len(_uncle_level)-1: return "verre %s%soom van de%s graad (%d generaties)" % (inlaw, @@ -368,7 +368,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return "verre %s%sneef (%d generaties, %d graden)" % (inlaw, step, level, removed) elif level > len(_nephew_level)-1: - return "verre %s%sneef van de%s graad (%d generaties)" % (inlaw, step, + return "verre %s%sneef van de%s graad (%d generaties)" % (inlaw, step, _removed_level[removed], level) else: return _nephew_level[level] % (inlaw, step) \ @@ -385,7 +385,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return "verre %s%snicht (%d generaties, %d graden)" % (inlaw, step, level, removed) elif level > len(_niece_level)-1: - return "verre %s%snicht van de%s graad (%d generaties)"% (inlaw, + return "verre %s%snicht van de%s graad (%d generaties)"% (inlaw, step, _removed_level[removed], level) else: return _niece_level[level] % (inlaw, step) \ @@ -398,7 +398,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): """ removed -= 1 if removed > len(_removed_level)-1: - return "verre %s%sneef (kozijn, %d graden)" % (inlaw, step, + return "verre %s%sneef (kozijn, %d graden)" % (inlaw, step, removed) elif removed == 0: return "%s%sbroer" % (inlaw, step) @@ -413,7 +413,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): """ removed -= 1 if removed > len(_removed_level)-1: - return "verre %s%snicht (kozijn, %d graden)" % (inlaw, step, + return "verre %s%snicht (kozijn, %d graden)" % (inlaw, step, removed) elif removed == 0: return "%s%szus" % (inlaw, step) @@ -423,7 +423,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): """ Return a string representing the relationship between the two people, @@ -482,14 +482,14 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: rel_str = self._get_child_unknown(Gb, step, inlaw) elif Ga > Gb: - #b is higher in the branch, in english uncle/aunt or + #b is higher in the branch, in english uncle/aunt or #cousin up, in dutch always 'oom/tante' if gender_b == Person.MALE: rel_str = self._get_uncle(Ga - Gb, Gb, step, inlaw) else: rel_str = self._get_aunt(Ga - Gb, Gb, step, inlaw) elif Ga < Gb: - #b is lower in the branch, in english niece/nephew or + #b is lower in the branch, in english niece/nephew or #cousin down, in dutch always 'neef/nicht' if gender_b == Person.MALE: rel_str = self._get_nephew(Gb - Ga, Ga, step, inlaw) @@ -501,19 +501,19 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = self._get_male_cousin(Ga, step, inlaw) else: rel_str = self._get_female_cousin(Ga, step, inlaw) - + return rel_str - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): """ Determine the string giving the relation between two siblings of type sib_type. Eg: b is the brother of a Here 'brother' is the string we need to determine - This method gives more details about siblings than + This method gives more details about siblings than get_single_relationship_string can do. - + .. warning:: DON'T TRANSLATE THIS PROCEDURE IF LOGIC IS EQUAL IN YOUR LANGUAGE, AND SAME METHODS EXIST (get_uncle, get_aunt, get_sibling) @@ -551,8 +551,8 @@ if __name__ == "__main__": # imported modules): # export PYTHONPATH=/path/to/gramps/src # python src/plugins/rel/rel_nl.py - - """TRANSLATORS, copy this if statement at the bottom of your + + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_no.py b/gramps/plugins/rel/rel_no.py index 3edb2d12d..e6b6afa9a 100644 --- a/gramps/plugins/rel/rel_no.py +++ b/gramps/plugins/rel/rel_no.py @@ -39,12 +39,12 @@ import gramps.gen.relationship #------------------------------------------------------------------------- _cousin_level = [ "", "", #brother/sister, fetter/kusine -- these are taken care of separately -"tremenning", "firemenning", "femmenning", +"tremenning", "firemenning", "femmenning", "seksmenning", "sjumenning", "åttemenning", -"nimenning", "timenning", "elvemenning", +"nimenning", "timenning", "elvemenning", "tolvmenning", "tretenmenning", "fjortenmenning", "femtenmenning", "sekstenmenning", "syttenmenning", -"attenmenning", "nittenmenning", "tyvemenning" ] +"attenmenning", "nittenmenning", "tyvemenning" ] _cousin_terms = _cousin_level + ["fetter", "kusine"] #------------------------------------------------------------------------- @@ -68,7 +68,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_cousin(self, level): if level > len(_cousin_level)-1: - # FIXME: use Norwegian term term here, + # FIXME: use Norwegian term term here, # UPDATED by Frode: unsure about the expretion "en fjern slektning", should it be just "fjern slektning". # Need to see it used in the program to get the understanding. return "en fjern slektning" @@ -238,14 +238,14 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return (self.get_ancestors_cousin(other_person, secondRel, firstRel), common) else: return (self.get_cousins_descendant(other_person, firstRel, secondRel), common) - + def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): return self.get_relationship(reltocommon_a, reltocommon_b, gender_a, gender_b)[0]; - - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): return self.get_two_way_rel(gender_b, "", "") @@ -257,7 +257,7 @@ if __name__ == "__main__": # python src/plugins/rel/rel_no.py # (Above not needed here) - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_pl.py b/gramps/plugins/rel/rel_pl.py index 97a35a32f..7fa610a83 100644 --- a/gramps/plugins/rel/rel_pl.py +++ b/gramps/plugins/rel/rel_pl.py @@ -42,20 +42,20 @@ import gramps.gen.relationship #------------------------------------------------------------------------- -# określa liczebnik porządkowy +# określa liczebnik porządkowy -_level_name = [ "pierwszego", "drugiego", "trzeciego", "czwartego", "piątego", - "szóstego", "siódmego", "ósmego", "dziewiątego", "dziesiątego", - "jedenastego", "dwunastego","trzynastego", "czternastego", "piętnastego", +_level_name = [ "pierwszego", "drugiego", "trzeciego", "czwartego", "piątego", + "szóstego", "siódmego", "ósmego", "dziewiątego", "dziesiątego", + "jedenastego", "dwunastego","trzynastego", "czternastego", "piętnastego", "szesnastego", "siedemnastego", "osiemnastego","dziewiętnastego", "dwudziestego", ] - -_father_level = [ "", - "ojciec", - "dziadek", - "pradziadek", - "prapradziadek", - "praprapradziadek", + +_father_level = [ "", + "ojciec", + "dziadek", + "pradziadek", + "prapradziadek", + "praprapradziadek", "prapraprapradziadek", "praprapraprapradziadek", "prapraprapraprapradziadek", @@ -64,11 +64,11 @@ _father_level = [ "", ] -_mother_level = [ "", - "matka", - "babcia", - "prababcia", - "praprababcia", +_mother_level = [ "", + "matka", + "babcia", + "prababcia", + "praprababcia", "prapraprababcia", "praprapraprababcia", "prapraprapraprababcia", @@ -77,8 +77,8 @@ _mother_level = [ "", "praprapraprapraprapraprababcia", ] -_son_level = [ "", - "syn", +_son_level = [ "", + "syn", "wnuk", "prawnuk", "praprawnuk", @@ -90,158 +90,158 @@ _son_level = [ "", "praprapraprapraprapraprawnuk", ] -_daughter_level = [ "", - "córka", - "wnuczka", - "prawnuczka", - "praprawnuczka", - "prapraprauwnuczka", - "praprapraprauwnuczka", - "prapraprapraprawnuczka", - "praprapraprapraprawnuczka", - "prapraprapraprapraprawnuczka", - "praprapraprapraprapraprawnuczka", +_daughter_level = [ "", + "córka", + "wnuczka", + "prawnuczka", + "praprawnuczka", + "prapraprauwnuczka", + "praprapraprauwnuczka", + "prapraprapraprawnuczka", + "praprapraprapraprawnuczka", + "prapraprapraprapraprawnuczka", + "praprapraprapraprapraprawnuczka", ] -_sister_level_of_male = [ "", "siostra", "ciotka stryjeczna", - "babcia stryjeczna", - "prababcia stryjeczna", - "praprababcia stryjeczna", - "prapraprababcia stryjeczna", - "praprapraprababcia stryjeczna", - "prapraprapraprababcia stryjeczna", - "praprapraprapraprababcia stryjeczna", - "prapraprapraprapraprababcia stryjeczna", - "praprapraprapraprapraprababcia stryjeczna", +_sister_level_of_male = [ "", "siostra", "ciotka stryjeczna", + "babcia stryjeczna", + "prababcia stryjeczna", + "praprababcia stryjeczna", + "prapraprababcia stryjeczna", + "praprapraprababcia stryjeczna", + "prapraprapraprababcia stryjeczna", + "praprapraprapraprababcia stryjeczna", + "prapraprapraprapraprababcia stryjeczna", + "praprapraprapraprapraprababcia stryjeczna", ] -_sister_level_of_female = [ "", "siostra", "ciotka", - "babcia cioteczna", - "prababcia cioteczna", - "praprababcia cioteczna", - "prapraprababcia cioteczna", - "praprapraprababcia cioteczna", - "prapraprapraprababcia cioteczna", - "praprapraprapraprababcia cioteczna", - "prapraprapraprapraprababcia cioteczna", - "praprapraprapraprapraprababcia cioteczna", +_sister_level_of_female = [ "", "siostra", "ciotka", + "babcia cioteczna", + "prababcia cioteczna", + "praprababcia cioteczna", + "prapraprababcia cioteczna", + "praprapraprababcia cioteczna", + "prapraprapraprababcia cioteczna", + "praprapraprapraprababcia cioteczna", + "prapraprapraprapraprababcia cioteczna", + "praprapraprapraprapraprababcia cioteczna", ] -_brother_level_of_male = [ "", "brat", "stryj", - "dziadek stryjeczny", - "pradziadek stryjeczny", +_brother_level_of_male = [ "", "brat", "stryj", + "dziadek stryjeczny", + "pradziadek stryjeczny", "prapradziadek stryjeczny", - "praprapradziadek stryjeczny", - "prapraprapradziadek stryjeczny", - "praprapraprapradziadek stryjeczny", - "prapraprapraprapradziadek stryjeczny", - "praprapraprapraprapradziadek stryjeczny", - "prapraprapraprapraprapradziadek stryjeczny", + "praprapradziadek stryjeczny", + "prapraprapradziadek stryjeczny", + "praprapraprapradziadek stryjeczny", + "prapraprapraprapradziadek stryjeczny", + "praprapraprapraprapradziadek stryjeczny", + "prapraprapraprapraprapradziadek stryjeczny", ] -_brother_level_of_female = [ "", "brat", "wuj", - "dziadek cioteczny", - "pradziadek cioteczny", +_brother_level_of_female = [ "", "brat", "wuj", + "dziadek cioteczny", + "pradziadek cioteczny", "prapradziadek cioteczny", - "praprapradziadek cioteczny", - "prapraprapradziadek cioteczny", - "praprapraprapradziadek cioteczny", - "prapraprapraprapradziadek cioteczny", - "praprapraprapraprapradziadek cioteczny", - "prapraprapraprapraprapradziadek cioteczny", + "praprapradziadek cioteczny", + "prapraprapradziadek cioteczny", + "praprapraprapradziadek cioteczny", + "prapraprapraprapradziadek cioteczny", + "praprapraprapraprapradziadek cioteczny", + "prapraprapraprapraprapradziadek cioteczny", ] -_nephew_level_of_brothers_son = [ "", "bratanek", - "syn bratanka", - "wnuk bratanka", - "prawnuk bratanka", - "praprawnuk bratanka", - "prapraprawnuk bratanka", - "praprapraprawnuk bratanka", - "prapraprapraprawnuk bratanka", - "praprapraprapraprawnuk bratanka", - "prapraprapraprapraprawnuk bratanka", +_nephew_level_of_brothers_son = [ "", "bratanek", + "syn bratanka", + "wnuk bratanka", + "prawnuk bratanka", + "praprawnuk bratanka", + "prapraprawnuk bratanka", + "praprapraprawnuk bratanka", + "prapraprapraprawnuk bratanka", + "praprapraprapraprawnuk bratanka", + "prapraprapraprapraprawnuk bratanka", ] -_nephew_level_of_brothers_daughter = [ "", "bratanica", - "syn bratanicy", - "wnuk bratanicy", - "prawnuk bratanicy", - "praprawnuk bratanicy", - "prapraprawnuk bratanicy", - "praprapraprawnuk bratanicy", - "prapraprapraprawnuk bratanicy", - "praprapraprapraprawnuk bratanicy", - "prapraprapraprapraprawnuk bratanicy", - "praprapraprapraprapraprawnuk bratanicy", +_nephew_level_of_brothers_daughter = [ "", "bratanica", + "syn bratanicy", + "wnuk bratanicy", + "prawnuk bratanicy", + "praprawnuk bratanicy", + "prapraprawnuk bratanicy", + "praprapraprawnuk bratanicy", + "prapraprapraprawnuk bratanicy", + "praprapraprapraprawnuk bratanicy", + "prapraprapraprapraprawnuk bratanicy", + "praprapraprapraprapraprawnuk bratanicy", ] -_nephew_level_of_sisters_son = [ "", "siostrzeniec", - "syn siostrzeńca", - "wnuk siostrzeńca", - "prawnuk siostrzeńca", - "praprawnuk siostrzeńca", - "prapraprawnuk siostrzeńca", - "praprapraprawnuk siostrzeńca", - "prapraprapraprawnuk siostrzeńca", - "praprapraprapraprawnuk siostrzeńca", - "prapraprapraprapraprawnuk siostrzeńca", +_nephew_level_of_sisters_son = [ "", "siostrzeniec", + "syn siostrzeńca", + "wnuk siostrzeńca", + "prawnuk siostrzeńca", + "praprawnuk siostrzeńca", + "prapraprawnuk siostrzeńca", + "praprapraprawnuk siostrzeńca", + "prapraprapraprawnuk siostrzeńca", + "praprapraprapraprawnuk siostrzeńca", + "prapraprapraprapraprawnuk siostrzeńca", ] -_nephew_level_of_sisters_daughter = [ "", "siostrzenica", - "syn siostrzenicy", - "wnuk siostrzenicy", - "prawnuk siostrzenicy", - "praprawnuk siostrzenicy", - "prapraprawnuk siostrzenicy", - "praprapraprawnuk siostrzenicy", - "prapraprapraprawnuk siostrzenicy", - "praprapraprapraprawnuk siostrzenicy", - "prapraprapraprapraprawnuk siostrzenicy", +_nephew_level_of_sisters_daughter = [ "", "siostrzenica", + "syn siostrzenicy", + "wnuk siostrzenicy", + "prawnuk siostrzenicy", + "praprawnuk siostrzenicy", + "prapraprawnuk siostrzenicy", + "praprapraprawnuk siostrzenicy", + "prapraprapraprawnuk siostrzenicy", + "praprapraprapraprawnuk siostrzenicy", + "prapraprapraprapraprawnuk siostrzenicy", ] -_niece_level_of_brothers_son = [ "", "bratanica", - "córka bratanka", - "wnuczka bratanka", - "prawnuczka bratanka", - "praprawnuczka bratanka", - "prapraprawnuczka bratanka", - "praprapraprawnuczka bratanka", - "prapraprapraprawnuczka bratanka", - "praprapraprapraprawnuczka bratanka", +_niece_level_of_brothers_son = [ "", "bratanica", + "córka bratanka", + "wnuczka bratanka", + "prawnuczka bratanka", + "praprawnuczka bratanka", + "prapraprawnuczka bratanka", + "praprapraprawnuczka bratanka", + "prapraprapraprawnuczka bratanka", + "praprapraprapraprawnuczka bratanka", ] -_niece_level_of_brothers_daughter = [ "", "bratanica", - "córka bratanicy", - "wnuczka bratanicy", - "prawnuczka bratanicy", - "praprawnuczka bratanicy", - "prapraprawnuczka bratanicy", - "praprapraprawnuczka bratanicy", - "prapraprapraprawnuczka bratanicy", - "praprapraprapraprawnuczka bratanicy", +_niece_level_of_brothers_daughter = [ "", "bratanica", + "córka bratanicy", + "wnuczka bratanicy", + "prawnuczka bratanicy", + "praprawnuczka bratanicy", + "prapraprawnuczka bratanicy", + "praprapraprawnuczka bratanicy", + "prapraprapraprawnuczka bratanicy", + "praprapraprapraprawnuczka bratanicy", ] -_niece_level_of_sisters_son = [ "", "siostrzenica", - "córka siostrzeńca", - "wnuczka siostrzeńca", - "prawnuczka siostrzeńca", - "praprawnuczka siostrzeńca", - "prapraprawnuczka siostrzeńca", - "praprapraprawnuczka siostrzeńca", - "prapraprapraprawnuczka siostrzeńca", - "praprapraprapraprawnuczka siostrzeńca", +_niece_level_of_sisters_son = [ "", "siostrzenica", + "córka siostrzeńca", + "wnuczka siostrzeńca", + "prawnuczka siostrzeńca", + "praprawnuczka siostrzeńca", + "prapraprawnuczka siostrzeńca", + "praprapraprawnuczka siostrzeńca", + "prapraprapraprawnuczka siostrzeńca", + "praprapraprapraprawnuczka siostrzeńca", ] -_niece_level_of_sisters_daughter = [ "", "siostrzenica", - "córka siostrzenicy", - "wnuczka siostrzenicy", - "prawnuczka siostrzenicy", - "praprawnuczka siostrzenicy", - "prapraprawnuczka siostrzenicy", - "praprapraprawnuczka siostrzenicy", - "prapraprapraprawnuczka siostrzenicy", - "praprapraprapraprawnuczka siostrzenicy", +_niece_level_of_sisters_daughter = [ "", "siostrzenica", + "córka siostrzenicy", + "wnuczka siostrzenicy", + "prawnuczka siostrzenicy", + "praprawnuczka siostrzenicy", + "prapraprawnuczka siostrzenicy", + "praprapraprawnuczka siostrzenicy", + "prapraprapraprawnuczka siostrzenicy", + "praprapraprapraprawnuczka siostrzenicy", ] #------------------------------------------------------------------------- @@ -254,31 +254,31 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): """ RelationshipCalculator Class """ - + def __init__(self): - gramps.gen.relationship.RelationshipCalculator.__init__(self) - + gramps.gen.relationship.RelationshipCalculator.__init__(self) + def get_son(self, level, inlaw=''): """ - Podaje tekst zawierający informację, jak bardzo potomek męski + Podaje tekst zawierający informację, jak bardzo potomek męski (np. syn) jest spokrewniony do danej osoby """ - + # Określ, czy osoba jest przybraną, czy rodzoną if inlaw == '': t_inlaw = "" else: t_inlaw = "przybrany " - + # TODO: dodać rozpoznawanie pasierb/pasierbica if level >= 0 and level < len(_son_level): return t_inlaw +_son_level[level] - + elif level >= len(_son_level) \ - and (level - 1) < len(_level_name): + and (level - 1) < len(_level_name): return t_inlaw + \ "potomek męski %s pokolenia" % _level_name[level - 1] - + else: return t_inlaw + \ "potomek męski w %d pokoleniu" % level @@ -287,11 +287,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_daughter(self, level, inlaw=''): """ - Podaje tekst zawierający informację, jak bardzo potomek żeński + Podaje tekst zawierający informację, jak bardzo potomek żeński (np. córka) jest spokrewniony do danej osoby """ - - # Określ, czy osoba jest przybraną, czy rodzoną + + # Określ, czy osoba jest przybraną, czy rodzoną # + stwórz obie formy (męską i żeńską) if inlaw == '': t_inlaw = "" @@ -299,13 +299,13 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: t_inlaw = "przybrana " t_inlawM = "przybrany " - + # TODO: dodać rozpoznawanie pasierb/pasierbica if level >= 0 and level < len(_daughter_level): return t_inlaw + _daughter_level[level] - + elif level >= len(_daughter_level) \ - and (level - 1) < len(_level_name): + and (level - 1) < len(_level_name): return t_inlawM + \ "potomek żeński %s pokolenia" % _level_name[level - 1] else: @@ -315,29 +315,29 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_child_unknown(self, level, inlaw=''): """ - Podaje tekst zawierający informację, jak bardzo potomek + Podaje tekst zawierający informację, jak bardzo potomek o nieokreślonej płci jest spokrewniony dodanej osoby """ - + # Określ, czy osoba jest przybraną, czy rodzoną if inlaw == '': t_inlaw = "" else: t_inlaw = "przybrany " - + if level == 1: if inlaw == '' : return "dziecko" else: return "przybrane dziecko" - - elif level >= 1 and (level - 1) < len(_level_name): + + elif level >= 1 and (level - 1) < len(_level_name): return t_inlaw + "potomek %s pokolenia" % _level_name[level - 1] - + else: return t_inlaw + "potomek w %d pokoleniu" % level - - + + def get_sword_distaff(self, level, reltocommon, spacebefore = ""): """ PL: Generuje relację po mieczu/po kądzieli @@ -345,28 +345,28 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): """ if level <= 1: return "" - + elif level == 2: # dziadek/babcia - - if reltocommon[0] == self.REL_FATHER: + + if reltocommon[0] == self.REL_FATHER: # ze strony rodzonego ojca return spacebefore + "po mieczu" - elif reltocommon[0] == self.REL_MOTHER: + elif reltocommon[0] == self.REL_MOTHER: # ze strony rodzonej matki return spacebefore + "po kądzieli" else: # relacja inna niż rodzona return "" - + elif level == 3: # pradziadek/prababcia - + if (reltocommon[0] == self.REL_FATHER) \ & (reltocommon[1] == self.REL_FATHER): # pradziadek od dziadka ze strony ojca return spacebefore + "podwójnego miecza" - + elif (reltocommon[0] == self.REL_FATHER) \ & (reltocommon[1] == self.REL_MOTHER): # pradziadek od babci ze strony ojca @@ -381,212 +381,212 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): & (reltocommon[1] == self.REL_MOTHER): # pradziadek od babci ze strony matki return spacebefore + "podwójnej kądzieli" - + else: # relacja inna niż rodzona return "" - + elif level == 4: # prapradziadek/praprababcia - + if (reltocommon[0] == self.REL_FATHER) \ & (reltocommon[1] == self.REL_FATHER) \ & (reltocommon[2] == self.REL_FATHER): # tzw. linia męska return spacebefore + "potrójnego miecza" - + if (reltocommon[0] == self.REL_FATHER) \ & (reltocommon[1] == self.REL_FATHER) \ & (reltocommon[2] == self.REL_FATHER): # tzw. linia żeńska return spacebefore + "potrójnego miecza" - + else: return "" - + else: return "" - - - + + + def get_father(self, level, reltocommon, inlaw=''): """ - Podaje tekst zawierający informację, jak bardzo przodek męski + Podaje tekst zawierający informację, jak bardzo przodek męski (np. ojciec) jest spokrewniony do danej osoby """ if inlaw == '': t_inlaw = "" else: t_inlaw = "przybrany " - + if level >= 0 and level < len(_father_level): # Jeśli znasz bezpośrednią nazwę relacji, to ją zastosuj - + if level == 1: # ojciec return t_inlaw + _father_level[level] - + elif (level >= 2) & (level <= 4): # dziadek, pradziadek, prapradziadek return t_inlaw + _father_level[level] \ + self.get_sword_distaff(level, reltocommon, ' ') - + else: return t_inlaw + _father_level[level] - + elif level >= len(_father_level) \ - and (level - 1) < len(_level_name): + and (level - 1) < len(_level_name): # jeśli istnieje liczebnik dla danej liczby return t_inlaw + \ "przodek męski %s pokolenia" % (_level_name[level - 1]) - + else: # dla pozostałych przypadków wypisz relację liczbowo return t_inlaw + \ - "przodek męski w %d pokoleniu" % level - + "przodek męski w %d pokoleniu" % level + def get_mother(self, level, reltocommon, inlaw=''): """ Podaje tekst zawierający informację, jak bardzo przodek żeński - (np. matka) jest spokrewniony do danej osoby + (np. matka) jest spokrewniony do danej osoby """ - + if inlaw == '': t_inlaw = "" else: t_inlaw = "przybrana " - + if level >= 0 and level < len(_mother_level): # Jeśli znasz bezpośrednią nazwę relacji, to ją zastosuj - + if level == 1: # matka return t_inlaw + _mother_level[level] - + elif (level >= 2) & (level <= 4): # babcia, prababcia, praprababcia return t_inlaw + _mother_level[level] \ + self.get_sword_distaff(level, reltocommon, ' ') - + else: return t_inlaw + _mother_level[level] - + elif level >= len(_mother_level) \ - and (level - 1) < len(_level_name): + and (level - 1) < len(_level_name): # jeśli istnieje liczebnik dla danej liczby return t_inlaw + \ "przodek żeński %s pokolenia" % (_level_name[level - 1]) - + else: # dla pozostałych przypadków wypisz relację liczbowo return t_inlaw +"przodek żeński w %d pokoleniu" % level - + def get_parent_unknown(self, level, inlaw=''): """ - Podaje tekst zawierający informację, jak bardzo przodek - o nieokreślonej płci jest spokrewniony dodanej osoby + Podaje tekst zawierający informację, jak bardzo przodek + o nieokreślonej płci jest spokrewniony dodanej osoby """ - + if inlaw == '': t_inlaw = "" else: t_inlaw = "przybrany " - + if level == 1: return t_inlaw + "rodzic" - + elif level > 1 and (level - 1) < len(_level_name): if (level >= 2) & (level <= 4): - # babcia, prababcia, praprababcia + # babcia, prababcia, praprababcia # (albo dziadek, pradziadek, prapradziadek) tmp = t_inlaw +\ "przodek %s pokolenia" % (_level_name[level - 1]) # TODO: try to recognize a gender... - return tmp - # + self.get_sword_distaff(level, reltocommon, ' ') + return tmp + # + self.get_sword_distaff(level, reltocommon, ' ') else: return t_inlaw + \ "przodek %s pokolenia" % (_level_name[level - 1]) else: return t_inlaw +"przodek w %d pokoleniu" % level - + def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): """ Provide a string that describes the relationsip between a person, and another person. E.g. "grandparent" or "child". - """ - + """ + if only_birth: step = '' else: step = self.STEP - + if in_law_a or in_law_b : inlaw = self.INLAW else: inlaw = '' - - + + # b is the same person as a if Ga == Gb == 0: rel_str = 'ta sama osoba' elif Ga == 0: # b is son/descendant of a - + if gender_b == Person.MALE: if inlaw and Gb == 1 and not step: rel_str = "zięć" else: rel_str = self.get_son(Gb, inlaw) - + elif gender_b == Person.FEMALE: if inlaw and Gb == 1 and not step: rel_str = "synowa" else: rel_str = self.get_daughter(Gb, inlaw) - + else: rel_str = self.get_child_unknown(Gb, inlaw) - - + + elif Gb == 0: # b is parent/grand parent of a - + if gender_b == Person.MALE: if inlaw and Gb == 1 and not step: # TODO: znaleźć odpowiedniki w zależności czy to syn/córka rel_str = "teść" else: rel_str = self.get_father(Ga, reltocommon_a, inlaw) - + elif gender_b == Person.FEMALE: if inlaw and Gb == 1 and not step: # TODO: znaleźć odpowiedniki w zależności czy to syn/córka rel_str = "teściowa" else: rel_str = self.get_mother(Ga, reltocommon_a, inlaw) - + else: rel_str = self.get_parent_unknown(Ga, inlaw) elif Ga == Gb == 1: # rodzeństwo - if gender_b == Person.MALE: + if gender_b == Person.MALE: if inlaw and not step: rel_str = "brat przyrodni" else: rel_str = "brat rodzony" - elif gender_b == Person.FEMALE: + elif gender_b == Person.FEMALE: if inlaw and not step: rel_str = "siostra przyrodnia" else: @@ -594,24 +594,24 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: rel_str = "brat/siostra" - elif Gb == 1 and Ga > 1: - + elif Gb == 1 and Ga > 1: + # Przyjmij, że nie rozróżniamy osób prawnie i nieprawnie przybranych... - + if Ga == 2: # rodzeństwo rodziców - + # brat ojca, czyli stryj if (gender_b == Person.MALE) \ & (reltocommon_a[0] == self.REL_FATHER): rel_str = "stryj" - # siostra ojca, czyli ciotka ??? + # siostra ojca, czyli ciotka ??? elif (gender_b == Person.FEMALE) \ & (reltocommon_a[0] == self.REL_FATHER): rel_str = "ciotka (tzw. stryjna)" - - # brat matki, czyli wuj/wujek + + # brat matki, czyli wuj/wujek elif (gender_b == Person.MALE) \ & (reltocommon_a[0] == self.REL_MOTHER): rel_str = "wuj (wujek)" @@ -620,13 +620,13 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): elif (gender_b == Person.FEMALE) \ & (reltocommon_a[0] == self.REL_MOTHER): rel_str = "ciotka" - + else: rel_str = "brat lub siostra rodzica" - + elif Ga == 3: # rodzeństwo dziadków rodziców osoby sprawdzanej - + # rodzeństwo dziadka po mieczu (ojca ojca) if (reltocommon_a[0] == self.REL_FATHER) \ & (reltocommon_a[1] == self.REL_FATHER): @@ -637,14 +637,14 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "babcia stryjeczna" else: rel_str = "rodzeństwo przodka w 2 pokoleniu" - + # rodzeństwo babki po mieczu (matki ojca) elif (reltocommon_a[0] == self.REL_FATHER) \ & (reltocommon_a[1] == self.REL_MOTHER): - # TODO: Należy sprawdzić, czy w staropolszczyźnie nie ma + # TODO: Należy sprawdzić, czy w staropolszczyźnie nie ma # dokładniejszych określeń dla tego typu relacji - # TODO: EN: Try to check, whether in old polish language + # TODO: EN: Try to check, whether in old polish language # are more specific word for this kind of relation if (gender_b == Person.MALE): rel_str = "dziadek stryjeczny (tzw przestryj, stary stryj)" @@ -657,9 +657,9 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): elif (reltocommon_a[0] == self.REL_MOTHER) \ & (reltocommon_a[1] == self.REL_FATHER): - # TODO: Należy sprawdzić, czy w staropolszczyźnie nie ma + # TODO: Należy sprawdzić, czy w staropolszczyźnie nie ma # dokładniejszych określeń dla tego typu relacji - # TODO: EN: Try to check, whether in old polish language + # TODO: EN: Try to check, whether in old polish language # are more specific word for this kind of relation if (gender_b == Person.MALE): rel_str = "dziadek cioteczny (starop. prapociot)" @@ -667,15 +667,15 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "babcia cioteczna (starop. praciota)" else: rel_str = "rodzeństwo przodka w 2 pokoleniu" - - + + # rodzeństwo babki po kądzieli (matki matki) elif (reltocommon_a[0] == self.REL_MOTHER) \ & (reltocommon_a[1] == self.REL_MOTHER): - # TODO: Należy sprawdzić, czy w staropolszczyźnie nie ma + # TODO: Należy sprawdzić, czy w staropolszczyźnie nie ma # dokładniejszych określeń dla tego typu relacji - # TODO: EN: Try to check, whether in old polish language + # TODO: EN: Try to check, whether in old polish language # are more specific word for this kind of relation if (gender_b == Person.MALE): rel_str = "dziadek cioteczny (starop. prapociot)" @@ -683,7 +683,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "babcia cioteczna (starop. praciota)" else: rel_str = "rodzeństwo przodka w 2 pokoleniu" - + else: if (gender_b == Person.MALE): rel_str = "rodzeństwo dziadka" @@ -691,13 +691,13 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "rodzeństwo babci" else: rel_str = "rodzeństwo przodka w 2 pokoleniu" - + elif Ga > 3: # pradziadkowie... (grandparents) - + if (gender_b == Person.MALE) \ & (reltocommon_a[0] == self.REL_FATHER): - + if Ga >= 0 and Ga < len(_brother_level_of_male): rel_str = _brother_level_of_male[Ga] else: @@ -709,10 +709,10 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = _sister_level_of_male[Ga] else: rel_str = "rodzeństwo przodka żeńskiego %d pokolenia" % Ga - + elif (gender_b == Person.MALE) \ & (reltocommon_a[0] == self.REL_MOTHER): - + if Ga >= 0 and Ga < len(_brother_level_of_female): rel_str = _brother_level_of_male[Ga] else: @@ -724,15 +724,15 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = _sister_level_of_male[Ga] else: rel_str = "rodzeństwo przodka żeńskiego %d pokolenia" % Ga - + else: rel_str = "rodzeństwo przodka %d pokolenia" % Ga else: # A program should never goes there, but... - rel_str = "Relacja nie określona" + rel_str = "Relacja nie określona" elif Ga ==1 and Gb > 1: - + # syn brata if (gender_b == Person.MALE) \ & (reltocommon_b[0] == self.REL_FATHER): @@ -740,7 +740,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = _nephew_level_of_brothers_son[Gb] else: rel_str = "męski potomek w %d pokoleniu brata" % Gb - + # córka brata elif (gender_b == Person.FEMALE) \ & (reltocommon_b[0] == self.REL_FATHER): @@ -748,7 +748,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = _nephew_level_of_brothers_daughter[Gb] else: rel_str = "żeński potomek w %d pokoleniu brata" % Gb - + # syn siostry if (gender_b == Person.MALE) \ & (reltocommon_b[0] == self.REL_MOTHER): @@ -756,7 +756,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = _nephew_level_of_sisters_son[Gb] else: rel_str = "męski potomek w %d pokoleniu brata" % Gb - + # córka siostry elif (gender_b == Person.FEMALE) \ & (reltocommon_b[0] == self.REL_MOTHER): @@ -768,37 +768,37 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): # potomek brata elif (reltocommon_b[0] == self.REL_FATHER): rel_str = "potomek w %d pokoleniu brata" % Gb - + # potomek brata elif (reltocommon_b[0] == self.REL_MOTHER): rel_str = "potomek w %d pokoleniu brata" % Gb - + else : rel_str = "potomek w %d pokoleniu rodzeństwa" % Gb - + elif Ga > 1 and Gb > 1: if (gender_b == Person.MALE): if Ga == 2 and Gb == 2: rel_str = "kuzyn" else: - rel_str = "daleki kuzyn (%d. stopień pokrewieństwa)" % (Ga+Gb) - + rel_str = "daleki kuzyn (%d. stopień pokrewieństwa)" % (Ga+Gb) + elif (gender_b == Person.FEMALE): if Ga == 2 and Gb == 2: rel_str = "kuzynka" - else: - rel_str = "daleka kuzynka (%d. stopień pokrewieństwa)" % (Ga+Gb) - + else: + rel_str = "daleka kuzynka (%d. stopień pokrewieństwa)" % (Ga+Gb) + else: if Ga == 2 and Gb == 2: rel_str = "kuzyn(ka)" - else: - rel_str = "daleki członek rodziny (%d. stopień pokrewieństwa)" % (Ga+Gb) + else: + rel_str = "daleki członek rodziny (%d. stopień pokrewieństwa)" % (Ga+Gb) - else: + else: # A program should never goes there, but... rel_str = "nieokreślony stopień pokrewieństwa" - + return rel_str def get_plural_relationship_string(self, Ga, Gb, @@ -841,15 +841,15 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if 1 < Ga and 1 < Gb: return 'dalsza rodzina' return 'relacja nieznana' - - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): - + if in_law_a or in_law_b : inlaw = self.INLAW else: inlaw = '' - + if sib_type == self.NORM_SIB: if not inlaw: if gender_b == Person.MALE: @@ -909,16 +909,16 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "brat lub siostra przyrodnia" else: rel_str = "nieokreślona relacja rodzeństwa" - return rel_str + return rel_str if __name__ == "__main__": # Test function. Call it as follows from the command line (so as to find # imported modules): - # export PYTHONPATH=/path/to/gramps/src - # python src/plugins/rel/rel_pl.py - - """TRANSLATORS, copy this if statement at the bottom of your + # export PYTHONPATH=/path/to/gramps/src + # python src/plugins/rel/rel_pl.py + + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_ru.py b/gramps/plugins/rel/rel_ru.py index 0f01ba80a..c6ca8c582 100644 --- a/gramps/plugins/rel/rel_ru.py +++ b/gramps/plugins/rel/rel_ru.py @@ -48,249 +48,249 @@ _parents_level = [ "прапрапрапрапрадедушки/прапрапрапрапрабабушки (8 поколение)", ] -_male_cousin_level = [ - "", - "двоюродный", - "троюродный", - "четвероюродный", - "пятиюродный", - "шестиюродный", - "семиюродный", - "восьмиюродный", - "девятиюродный", - "десятиюродный", - "одиннацатиюродный", - "двенадцатиюродный", - "тринадцатиюродный", - "четырнадцатиюродный", - "пятнадцатиюродный", - "шестнадцатиюродный", - "семнадцатиюродный", - "восемнадцатиюродный", - "девятнадцатиюродный", - "двадцатиюродный", - ] - -_female_cousin_level = [ - "", - "двоюродная", - "троюродная", - "четвероюродная", - "пятиюродная", - "шестиюродная", - "семиюродная", - "восьмиюродная", - "девятиюродная", - "десятиюродная", - "одиннацатиюродная", - "двенадцатиюродная", - "тринадцатиюродная", - "четырнадцатиюродная", - "пятнадцатиюродная", - "шестнадцатиюродная", - "семнадцатиюродная", - "восемнадцатиюродная", - "девятнадцатиюродная", - "двадцатиюродная", - ] - -_cousin_level = [ +_male_cousin_level = [ "", - "двоюродные", - "троюродные", + "двоюродный", + "троюродный", + "четвероюродный", + "пятиюродный", + "шестиюродный", + "семиюродный", + "восьмиюродный", + "девятиюродный", + "десятиюродный", + "одиннацатиюродный", + "двенадцатиюродный", + "тринадцатиюродный", + "четырнадцатиюродный", + "пятнадцатиюродный", + "шестнадцатиюродный", + "семнадцатиюродный", + "восемнадцатиюродный", + "девятнадцатиюродный", + "двадцатиюродный", + ] + +_female_cousin_level = [ + "", + "двоюродная", + "троюродная", + "четвероюродная", + "пятиюродная", + "шестиюродная", + "семиюродная", + "восьмиюродная", + "девятиюродная", + "десятиюродная", + "одиннацатиюродная", + "двенадцатиюродная", + "тринадцатиюродная", + "четырнадцатиюродная", + "пятнадцатиюродная", + "шестнадцатиюродная", + "семнадцатиюродная", + "восемнадцатиюродная", + "девятнадцатиюродная", + "двадцатиюродная", + ] + +_cousin_level = [ + "", + "двоюродные", + "троюродные", "четвероюродные", - "пятиюродные", - "шестиюродные", - "семиюродные", + "пятиюродные", + "шестиюродные", + "семиюродные", "восьмиюродные", - "девятиюродные", + "девятиюродные", "десятиюродные", - "одиннацатиюродные", + "одиннацатиюродные", "двенадцатиюродные", - "тринадцатиюродные", - "четырнадцатиюродные", - "пятнадцатиюродные", - "шестнадцатиюродные", - "семнадцатиюродные", - "восемнадцатиюродные", - "девятнадцатиюродные", - "двадцатиюродные", + "тринадцатиюродные", + "четырнадцатиюродные", + "пятнадцатиюродные", + "шестнадцатиюродные", + "семнадцатиюродные", + "восемнадцатиюродные", + "девятнадцатиюродные", + "двадцатиюродные", ] -_junior_male_removed_level = [ - "брат", - "племянник", - "внучатый племянник", - "правнучатый племянник", - "праправнучатый племянник", - "прапраправнучатый племянник", - "прапрапраправнучатый племянник", +_junior_male_removed_level = [ + "брат", + "племянник", + "внучатый племянник", + "правнучатый племянник", + "праправнучатый племянник", + "прапраправнучатый племянник", + "прапрапраправнучатый племянник", ] -_junior_female_removed_level = [ - "сестра", - "племянница", - "внучатая племянница", - "правнучатая племянница", - "праправнучатая племянница", - "прапраправнучатая племянница", - "прапрапраправнучатая племянница", +_junior_female_removed_level = [ + "сестра", + "племянница", + "внучатая племянница", + "правнучатая племянница", + "праправнучатая племянница", + "прапраправнучатая племянница", + "прапрапраправнучатая племянница", ] -_juniors_removed_level = [ - "братья/сестры", - "племянники", - "внучатые племянники", - "правнучатые племянники", - "праправнучатые племянники", - "прапраправнучатые племянники", - "прапрапраправнучатые племянники", +_juniors_removed_level = [ + "братья/сестры", + "племянники", + "внучатые племянники", + "правнучатые племянники", + "праправнучатые племянники", + "прапраправнучатые племянники", + "прапрапраправнучатые племянники", ] -_senior_male_removed_level = [ - "", - "дядя", - "дед", - "прадед", - "прапрадед", - "прапрапрадед", - "прапрапрапрадед", +_senior_male_removed_level = [ + "", + "дядя", + "дед", + "прадед", + "прапрадед", + "прапрапрадед", + "прапрапрапрадед", ] -_senior_female_removed_level = [ - "", - "тётя", - "бабушка", - "прабабушка", - "прапрабабушка", - "прапрапрабабушка", - "прапрапрапрабабушка", +_senior_female_removed_level = [ + "", + "тётя", + "бабушка", + "прабабушка", + "прапрабабушка", + "прапрапрабабушка", + "прапрапрапрабабушка", ] -_seniors_removed_level = [ - "", - "дяди/тёти", - "дедушки/бабушки", - "прадеды/прабабушки", - "прапрадеды/прапрабабушки", - "прапрапрадеды/прапрапрабабушки", - "прапрапрапрадеды/прапрапрапрабабушки", +_seniors_removed_level = [ + "", + "дяди/тёти", + "дедушки/бабушки", + "прадеды/прабабушки", + "прапрадеды/прапрабабушки", + "прапрапрадеды/прапрапрабабушки", + "прапрапрапрадеды/прапрапрапрабабушки", ] -_father_level = [ - "", - "отец", - "дед", - "прадед", - "прапрадед", - "прапрапрадед", - "прапрапрапрадед", +_father_level = [ + "", + "отец", + "дед", + "прадед", + "прапрадед", + "прапрапрадед", + "прапрапрапрадед", ] -_mother_level = [ - "", - "мать", - "бабушка", - "прабабушка", - "прапрабабушка", - "прапрапрабабушка", - "прапрапрапрабабушка", +_mother_level = [ + "", + "мать", + "бабушка", + "прабабушка", + "прапрабабушка", + "прапрапрабабушка", + "прапрапрапрабабушка", ] -_son_level = [ - "", - "сын", - "внук", - "правнук", - "праправнук", - "прапраправнук", - "прапрапраправнук", +_son_level = [ + "", + "сын", + "внук", + "правнук", + "праправнук", + "прапраправнук", + "прапрапраправнук", ] -_daughter_level = [ - "", - "дочь", - "внучка", - "правнучка", - "праправнучка", - "прапраправнучка", - "прапрапраправнучка", +_daughter_level = [ + "", + "дочь", + "внучка", + "правнучка", + "праправнучка", + "прапраправнучка", + "прапрапраправнучка", ] -_children_level = [ - "", - "дети", - "внуки", - "правнуки", - "праправнуки", - "прапраправнуки", - "прапрапраправнуки", +_children_level = [ + "", + "дети", + "внуки", + "правнуки", + "праправнуки", + "прапраправнуки", + "прапрапраправнуки", "прапрапрапраправнуки", ] -_sister_level = [ - "", - "сестра", - "тётя", - "двоюродная бабушка", - "двоюродная прабабушка", - "двоюродная прапрабабушка", - "двоюродная прапрапрабабушка", - "двоюродная прапрапрапрабабушка", +_sister_level = [ + "", + "сестра", + "тётя", + "двоюродная бабушка", + "двоюродная прабабушка", + "двоюродная прапрабабушка", + "двоюродная прапрапрабабушка", + "двоюродная прапрапрапрабабушка", ] -_brother_level = [ - "", - "брат", - "дядя", - "двоюродный дед", - "двоюродный прадед", - "двоюродный прапрадед", - "двоюродный прапрапрадед", - "двоюродный прапрапрапрадед", +_brother_level = [ + "", + "брат", + "дядя", + "двоюродный дед", + "двоюродный прадед", + "двоюродный прапрадед", + "двоюродный прапрапрадед", + "двоюродный прапрапрапрадед", ] -_siblings_level = [ - "", - "братья/сестры", - "дядьки/тётки", - "двоюродные дедушки/бабушки", - "двоюродные прадедушки/прабабушки", - "двоюродные прапрадедушки/прапрабабушки (5 поколение)", +_siblings_level = [ + "", + "братья/сестры", + "дядьки/тётки", + "двоюродные дедушки/бабушки", + "двоюродные прадедушки/прабабушки", + "двоюродные прапрадедушки/прапрабабушки (5 поколение)", "двоюродные прапрапрадедушки/прапрапрабабушки (6 поколение)", "двоюродные прапрапрапрадедушки/прапрапрапрабабушки (7 поколение)", "двоюродные прапрапрапрапрадедушки/прапрапрапрапрабабушки (8 поколение)", ] -_nephew_level = [ - "", - "племянник", - "внучатый племянник", - "правнучатый племянник", - "праправнучатый племянник", - "прапраправнучатый племянник", - "прапрапраправнучатый племянник", +_nephew_level = [ + "", + "племянник", + "внучатый племянник", + "правнучатый племянник", + "праправнучатый племянник", + "прапраправнучатый племянник", + "прапрапраправнучатый племянник", ] -_niece_level = [ - "", - "племянница", - "внучатая племянница", - "правнучатая племянница", - "праправнучатая племянница", - "прапраправнучатая племянница", - "прапрапраправнучатая племянница", +_niece_level = [ + "", + "племянница", + "внучатая племянница", + "правнучатая племянница", + "праправнучатая племянница", + "прапраправнучатая племянница", + "прапрапраправнучатая племянница", ] _nephews_nieces_level = [ - "", - "братья/сестры", - "племянники", - "внучатые племянники", - "правнучатые племянники", - "праправнучатые племянники", - "прапраправнучатые племянники", - "прапрапраправнучатые племянники", + "", + "братья/сестры", + "племянники", + "внучатые племянники", + "правнучатые племянники", + "праправнучатые племянники", + "прапраправнучатые племянники", + "прапрапраправнучатые племянники", ] #------------------------------------------------------------------------- @@ -396,7 +396,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): if Gb == 0: @@ -463,28 +463,28 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: rel_str = "дальние племянники/племянницы" elif Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. if Gb <= len(_seniors_removed_level) and (Ga-Gb) < len(_cousin_level): - rel_str = "%s %s" % ( _cousin_level[Gb-1], + rel_str = "%s %s" % ( _cousin_level[Gb-1], _seniors_removed_level[Ga-Gb] ) else: rel_str = "(старшие) дальние родственники" else: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. if Ga <= len(_juniors_removed_level) and (Gb-Ga) < len(_cousin_level): - rel_str = "%s %s" % ( _cousin_level[Ga-1], + rel_str = "%s %s" % ( _cousin_level[Ga-1], _juniors_removed_level[Gb-Ga] ) else: rel_str = "(младшие) дальние родственники" - + if in_law_b == True: # TODO: Translate this! rel_str = "spouses of %s" % rel_str - + return rel_str # TODO: def get_sibling_relationship_string for Russian step and inlaw relations @@ -497,7 +497,7 @@ if __name__ == "__main__": # python src/plugins/rel/rel_ru.py # (Above not needed here) - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_sk.py b/gramps/plugins/rel/rel_sk.py index ca96b98ab..0ef7387f1 100644 --- a/gramps/plugins/rel/rel_sk.py +++ b/gramps/plugins/rel/rel_sk.py @@ -34,12 +34,12 @@ import gramps.gen.relationship #------------------------------------------------------------------------- # -#GRAMPS 3.x - Slovak-specific terms by Lubo Vasko +#GRAMPS 3.x - Slovak-specific terms by Lubo Vasko # #------------------------------------------------------------------------- -# hĺbka použitá pre označenie / zistenie vzťahov od genenácie : -# ku generácii, +# hĺbka použitá pre označenie / zistenie vzťahov od genenácie : +# ku generácii, _level_name = [ "prvého", "druhého", "tretieho", "štvrtého", "piateho", "šiesteho", @@ -50,7 +50,7 @@ _level_name = [ "prvého", "druhého", "tretieho", "štvrtého", "piateho", "ši "dvadsiatehoôsmeho","dvadsiatehodeviateho","tridsiateho" ] -# vzdialení príbuzní +# vzdialení príbuzní _removed_level = [ "prvého", "druhého", "tretieho", "štvrtého", "piateho", "šiesteho", "siedmeho", "ôsmeho", "deviateho", "desiateho", "jedenásteho", "dvanásteho", @@ -58,18 +58,18 @@ _removed_level = [ "prvého", "druhého", "tretieho", "štvrtého", "piateho", " "sedemnásteho", "osemnásteho", "devätnásteho", "dvadsiateho", "dvadsiatehoprvého", "dvadsiatehodruhého", "dvadsiatehotretieho", "dvadsiatehoštvrtého","dvadsiatehopiateho","dvadsiatehošiesteho","dvadsiatehosiedmeho", "dvadsiatehoôsmeho","dvadsiatehodeviateho","tridsiateho" ] - + # small lists, use generation level if > [5] _father_level = [ "", "otec%s", "starý otec%s", "prastarý otec%s", "prapredok%s", ] -_mother_level = [ "", "matka%s", "stará matka%s", +_mother_level = [ "", "matka%s", "stará matka%s", "prastará matka%s", "prapredok%s", ] _son_level = [ "", "syn%s", "vnuk%s", "pravnuk%s", ] -_daughter_level = [ "", "dcéra%s", "vnučka%s", +_daughter_level = [ "", "dcéra%s", "vnučka%s", "pravnučka%s", ] _sister_level = [ "", "sestra%s", "teta%s", "prateta%s", "praprateta%s", ] @@ -82,21 +82,21 @@ _niece_level = [ "", "neter%s", "praneter%s", "prapraneter%s", ] # kinship report -_parents_level = [ "", "rodičia", "starí rodičia", +_parents_level = [ "", "rodičia", "starí rodičia", "prastarí rodičia", "predkovia", ] -_children_level = [ "", "deti", "vnúčatá", - "pravnúčatá", +_children_level = [ "", "deti", "vnúčatá", + "pravnúčatá", "pra-pravnúčatá", ] -_siblings_level = [ "", "bratia a sestry", - "strýkovia a tety", - "prastrýkovia a pratety", - "pra-prastrýkovia a pra-pratety", +_siblings_level = [ "", "bratia a sestry", + "strýkovia a tety", + "prastrýkovia a pratety", + "pra-prastrýkovia a pra-pratety", ] -_nephews_nieces_level = [ "", "synovci a netere", - "prasynovci a pranetere", +_nephews_nieces_level = [ "", "synovci a netere", + "prasynovci a pranetere", "pra-prasynovci a pra-pranetere", ] @@ -110,7 +110,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): """ RelationshipCalculator Class """ - + INLAW = ' (m. zväzok)' @@ -118,7 +118,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): gramps.gen.relationship.RelationshipCalculator.__init__(self) -# od aktívnej osoby vzhľadom k spoločnému predkovi Ga=[level] +# od aktívnej osoby vzhľadom k spoločnému predkovi Ga=[level] # pre vyhodnotenie vzťahov def get_cousin(self, level, removed, dir = '', inlaw=''): @@ -251,14 +251,14 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = _parents_level[Ga] else: rel_str = "predkovia" + gen % ( - Ga+1) + Ga+1) elif Gb == 1: # These are siblings/aunts/uncles if Ga < len(_siblings_level): rel_str = _siblings_level[Ga] else: rel_str = "deti predka" + gen % ( - Ga+1) + cmt + Ga+1) + cmt elif Ga == 1: # These are nieces/nephews if Gb < len(_nephews_nieces_level): @@ -270,16 +270,16 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): # These are cousins in the same generation # use custom level for latin words if Ga == 2: - rel_str = "vlastní bratranci a sesternice" + rel_str = "vlastní bratranci a sesternice" elif Ga <= len(_level_name): # %ss for plural rel_str = " %ss bratranci a sesternice" % _level_name[Ga-2] - # security + # security else: rel_str = "bratranci a sesternice" elif Ga > 1 and Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. # use custom level for latin words and specific relation if Ga == 3 and Gb == 2: @@ -294,8 +294,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "prastrýkovia a pratety" + bygen % ( Ga+1) elif Gb > 1 and Gb > Ga: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. # use custom level for latin words and specific relation if Ga == 2 and Gb == 3: @@ -312,7 +312,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if in_law_b == True: # TODO: Translate this! rel_str = "spouses of %s" % rel_str - + return rel_str @@ -320,7 +320,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): """ see relationship.py @@ -333,9 +333,9 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if in_law_a or in_law_b : inlaw = self.INLAW else: - inlaw = '' - - + inlaw = '' + + rel_str = "vzdialený príbuznýs%s" % (inlaw) bygen = " z %s generácie" if Ga == 0: @@ -416,7 +416,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): elif gender_b == Person.FEMALE and Gb < len(_niece_level): rel_str = self.get_niece(Gb-1, inlaw) else: - if gender_b == Person.MALE: + if gender_b == Person.MALE: rel_str = "vzdialený synovec%s (%d generácia)" % ( inlaw, Gb) elif gender_b == Person.FEMALE: @@ -429,27 +429,27 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): elif Ga == Gb: # a and b cousins in the same generation if gender_b == Person.MALE: - rel_str = self.get_cousin(Ga-1, 0, dir = '', + rel_str = self.get_cousin(Ga-1, 0, dir = '', inlaw=inlaw) elif gender_b == Person.FEMALE: - rel_str = self.get_cousine(Ga-1, 0, dir = '', + rel_str = self.get_cousine(Ga-1, 0, dir = '', inlaw=inlaw) elif gender_b == Person.UNKNOWN: rel_str = self.get_sibling_unknown(Ga-1, inlaw) else: return rel_str elif Ga > 1 and Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. if Ga == 3 and Gb == 2: if gender_b == Person.MALE: desc = " (bratranec niektorého z rodičov)" rel_str = "strýko z druhého kolena" + desc - elif gender_b == Person.FEMALE: + elif gender_b == Person.FEMALE: desc = " (sesternica niektorého z rodičov)" rel_str = "teta z druhého kolena" + desc - elif gender_b == Person.UNKNOWN: + elif gender_b == Person.UNKNOWN: return self.get_sibling_unknown(Ga, inlaw) else: return rel_str @@ -466,28 +466,28 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: return rel_str else: - if gender_b == Person.MALE: + if gender_b == Person.MALE: rel_str = self.get_uncle(Ga, inlaw) elif gender_b == Person.FEMALE: rel_str = self.get_aunt(Ga, inlaw) elif gender_b == Person.UNKNOWN: rel_str = self.get_sibling_unknown(Ga, inlaw) else: - return rel_str + return rel_str elif Gb > 1 and Gb > Ga: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. if Ga == 2 and Gb == 3: info = " (potomok bratranca/sesternice)" - if gender_b == Person.MALE: + if gender_b == Person.MALE: rel_str = "synovec z druhého kolena" + info elif gender_b == Person.FEMALE: rel_str = "neter z druhého kolena" + info elif gender_b == Person.UNKNOWN: rel_str = self.get_sibling_unknown(Ga, inlaw) else: - return rel_str + return rel_str elif Ga <= len(_level_name) and (Gb-Ga) < len(_removed_level) and (Ga+Gb+1) < len(_removed_level): can = " z %s do %s stupňa (kan.)" % ( _removed_level[Gb], _removed_level[Ga] ) @@ -515,14 +515,14 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): # RelCalc tool - Status Bar - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): if in_law_a or in_law_b : inlaw = self.INLAW else: inlaw = '' - + if sib_type == self.NORM_SIB: if not inlaw: if gender_b == Person.MALE: @@ -582,11 +582,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if __name__ == "__main__": # Test function. Call it as follows from the command line (so as to find # imported modules): - # export PYTHONPATH=/path/to/gramps/src - # python src/plugins/rel/rel_sk.py + # export PYTHONPATH=/path/to/gramps/src + # python src/plugins/rel/rel_sk.py # (Above not needed here) - - """TRANSLATORS, copy this if statement at the bottom of your + + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/rel_sl.py b/gramps/plugins/rel/rel_sl.py index 90f11817e..52981f0b2 100644 --- a/gramps/plugins/rel/rel_sl.py +++ b/gramps/plugins/rel/rel_sl.py @@ -49,7 +49,7 @@ _femaleCousins = [ "", "sestra", "sestrična", "mala sestrična" ] _someCousins = [ "", "brat ali sestra", "bratranec ali sestrična", "mali bratranec ali mala sestrična" ] _aunts = [ "", "teta", "stara teta", "prateta", "praprateta" ] -_uncles = [ "", "stric", "stari stric", "prastric", "praprastric" ] +_uncles = [ "", "stric", "stari stric", "prastric", "praprastric" ] _nieces = [ "", "nečakinja", "pranečakinja", "prapranečakinja" ] _nephews = [ "", "nečak", "pranečak", "prapranečak" ] @@ -78,37 +78,37 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return "%s-krat-pra-prednik" % (level-2) else: return _ancestors[level] - + def getFather(self, level): if level > len(_fathers)-1: return "%s-krat-pra-ded" % (level-2) else: return _fathers[level] - + def getMother(self, level): if level > len(_mothers)-1: return "%s-krat-pra-babica" % (level-2) else: return _mothers[level] - + def getSon(self, level): if level > len(_sons)-1: return "%s-krat-pra-vnuk" % (level-2) else: return _sons[level] - + def getDaughter(self, level): if level > len(_daughters)-1: return "%s-krat-pra-vnukinja" % (level-2) else: return _daughters[level] - + def getDescendant(self, level): if level > len(_descendants)-1: return "%s-krat-pra-vnuk(inja)" % (level-2) else: return _descendants[level] - + def getMaleCousin(self, level): if level > len(_maleCousins)-1: return "bratranec v %s. kolenu" % (level*2) @@ -126,14 +126,14 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return "bratranec ali sestrična v %s. kolenu" % (level*2) else: return _someCousins[level] - + def getSuffix(self, distance, level): # distance-level = 2Gb <=> Gb=1 if distance-level == 2 or distance < 6: return "" else: return " v %s. kolenu" % (distance) - + def getAunt(self, distance, level): if distance == 5 and level == 1: return "mala teta" @@ -141,7 +141,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return "%s-krat-pra-teta%s" % (level-2, self.getSuffix(distance, level)) else: return "%s%s" % (_aunts[level], self.getSuffix(distance, level)) - + def getUncle(self, distance, level): if distance == 5 and level == 1: return "mali stric" @@ -157,7 +157,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return "%s-krat-pra-nečakinja%s" % (level-1, self.getSuffix(distance, level)) else: return "%s%s" % (_nieces[level], self.getSuffix(distance, level)) - + def getNephew(self, distance, level): if distance == 5 and level == 1: return "mali nečak" @@ -165,30 +165,30 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): return "%s-krat-pra-nečak%s" % (level-1, self.getSuffix(distance, level)) else: return "%s%s" % (_nephews[level], self.getSuffix(distance, level)) - + def get_single_relationship_string( self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, only_birth=True, in_law_a=False, in_law_b=False): """ Provide a string that describes the relationsip between a person, and another person. E.g. "grandparent" or "child". - + To be used as: 'person b is the grandparent of a', this will be in translation string: 'person b is the %(relation)s of a' - Note that languages with gender should add 'the' inside the + Note that languages with gender should add 'the' inside the translation, so eg in french: 'person b est %(relation)s de a' where relation will be here: le grandparent - + Ga and Gb can be used to mathematically calculate the relationship. - + .. seealso:: http://en.wikipedia.org/wiki/Cousin#Mathematical_definitions - + Some languages need to know the specific path to the common ancestor. - Those languages should use reltocommon_a and reltocommon_b which is + Those languages should use reltocommon_a and reltocommon_b which is a string like 'mfmf'. - + The possible string codes are: ======================= =========================================== @@ -204,27 +204,27 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): REL_FAM_BIRTH_FATH_ONLY # going up to fam, only birth rel to father ======================= =========================================== - Prefix codes are stripped, so REL_FAM_INLAW_PREFIX is not present. + Prefix codes are stripped, so REL_FAM_INLAW_PREFIX is not present. If the relation starts with the inlaw of the person a, then 'in_law_a' is True, if it starts with the inlaw of person b, then 'in_law_b' is True. - Also REL_SIBLING (# going sideways to sibling (no parents)) is not - passed to this routine. The collapse_relations changes this to a - family relation. + Also REL_SIBLING (# going sideways to sibling (no parents)) is not + passed to this routine. The collapse_relations changes this to a + family relation. - Hence, calling routines should always strip REL_SIBLING and + Hence, calling routines should always strip REL_SIBLING and REL_FAM_INLAW_PREFIX before calling get_single_relationship_string() Note that only_birth=False, means that in the reltocommon one of the NOTBIRTH specifiers is present. - The REL_FAM identifiers mean that the relation is not via a common - ancestor, but via a common family (note that that is not possible for + The REL_FAM identifiers mean that the relation is not via a common + ancestor, but via a common family (note that that is not possible for direct descendants or direct ancestors!). If the relation to one of the parents in that common family is by birth, then 'only_birth' is not set to False. The only_birth() method is normally used for this. - - :param Ga: The number of generations between the main person and the + + :param Ga: The number of generations between the main person and the common ancestor. :type Ga: int :param Gb: The number of generations between the other person and the @@ -235,13 +235,13 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): :param gender_b: gender of person b :type gender_b: int gender :param reltocommon_a: relation path to common ancestor or common - Family for person a. + Family for person a. Note that length = Ga - :type reltocommon_a: str + :type reltocommon_a: str :param reltocommon_b: relation path to common ancestor or common - Family for person b. + Family for person b. Note that length = Gb - :type reltocommon_b: str + :type reltocommon_b: str :param in_law_a: True if path to common ancestors is via the partner of person a :type in_law_a: bool @@ -253,24 +253,24 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): :type only_birth: bool :returns: A string describing the relationship between the two people :rtype: str - - .. note:: 1. the self.REL_SIBLING should not be passed to this routine, + + .. note:: 1. the self.REL_SIBLING should not be passed to this routine, so we should not check on it. All other self. - 2. for better determination of siblings, use if Ga=1=Gb + 2. for better determination of siblings, use if Ga=1=Gb get_sibling_relationship_string """ if Gb == 0: if Ga == 0: rel_str = "ista oseba" elif gender_b == Person.MALE: rel_str = (self.getFather(Ga)) - elif gender_b == Person.FEMALE: + elif gender_b == Person.FEMALE: rel_str = (self.getMother(Ga)) else: rel_str = (self.getAncestor(Ga)) elif Ga == 0: if gender_b == Person.MALE: rel_str = (self.getSon(Gb)) - elif gender_b == Person.FEMALE: + elif gender_b == Person.FEMALE: rel_str = (self.getDaughter(Gb)) else: rel_str = (self.getDescendant(Gb)) @@ -292,18 +292,18 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: rel_str = (self.getNephew(Ga+Gb, Gb-Ga)) # we'll use male for unknown sex return rel_str - - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): """ Determine the string giving the relation between two siblings of type sib_type. Eg: b is the brother of a Here 'brother' is the string we need to determine - This method gives more details about siblings than + This method gives more details about siblings than get_single_relationship_string can do. - + .. warning:: DON'T TRANSLATE THIS PROCEDURE IF LOGIC IS EQUAL IN YOUR LANGUAGE, AND SAME METHODS EXIST (get_uncle, get_aunt, get_sibling) @@ -314,7 +314,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): prefix = "pol" else: prefix = "" - + if sib_type < self.STEP_SIB: # ie. NORM_SIB or one of HALF_SIBs if not inlaw: @@ -335,11 +335,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): rel_str = "" return rel_str - + def get_plural_relationship_string( self, Ga, Gb, reltocommon_a='', reltocommon_b='', only_birth=True, in_law_a=False, in_law_b=False): - + distance = Ga+Gb rel_str = "sorodniki v %s. kolenu" % (distance) if Ga == 0: @@ -375,8 +375,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: rel_str = "bratranci v %s. kolenu" % (distance) elif Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. level = Ga - Gb if distance == 5: @@ -387,8 +387,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): else: rel_str = "%s-krat-pra-strici v %s. kolenu" % (level-2, distance) else: #Gb > Ga: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. level = Gb - Ga if distance == 5: @@ -396,19 +396,19 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): elif level < len(_neph_niec): rel_str = "%s v %s. kolenu" % (_neph_niec[level], distance) else: - rel_str = "%s-krat-pra-nečaki v %s. kolenu" % (level-1, distance) + rel_str = "%s-krat-pra-nečaki v %s. kolenu" % (level-1, distance) if in_law_b == True: rel_str = "zakonci, ki jih imajo %s" % rel_str return rel_str if __name__ == "__main__": - """TRANSLATORS, copy this if statement at the bottom of your + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ from gramps.gen.relationship import test RC = RelationshipCalculator() test(RC, True) -# +# #from PluginMgr import register_relcalc # register_relcalc(RelationshipCalculatorClass,["sl","sl_SI","sl-SI","slovenian","Slovenian","slovenščina"]) diff --git a/gramps/plugins/rel/rel_sv.py b/gramps/plugins/rel/rel_sv.py index 913b66e3f..8ed2b9fee 100644 --- a/gramps/plugins/rel/rel_sv.py +++ b/gramps/plugins/rel/rel_sv.py @@ -40,25 +40,25 @@ import gramps.gen.relationship #------------------------------------------------------------------------- -_cousin_level = [ "", "kusin", -"tremänning", "fyrmänning", "femmänning", +_cousin_level = [ "", "kusin", +"tremänning", "fyrmänning", "femmänning", "sexmänning", "sjumänning", "åttamänning", -"niomänning", "tiomänning", "elvammänning", +"niomänning", "tiomänning", "elvammänning", "tolvmänning", "trettonmänning", "fjortonmänning", "femtonmänning", "sextonmänning", "sjuttonmänning", "artonmänning", "nittonmänning", "tjugomänning", "tjugoettmänning", "tjugotvåmänning", "tjugotremänning", "tjugofyramänning","tjugofemmänning","tjugoexmänning", "tjugosjumänning","tjugoåttamänning","tjugoniomänning", -"trettiomänning" ] +"trettiomänning" ] _children_level = 20 -_level_name = [ "", "första", +_level_name = [ "", "första", "andra", "tredje", "fjärde", "femte", -"sjätte", "sjunde", "åttonde", "nionde", -"tionde", "elfte", "tolfte", "trettonde", -"fjortonde", "femtonde", "sextonde", "sjuttonde", +"sjätte", "sjunde", "åttonde", "nionde", +"tionde", "elfte", "tolfte", "trettonde", +"fjortonde", "femtonde", "sextonde", "sjuttonde", "artonde", "nittonde", "tjugonde" ] #------------------------------------------------------------------------- @@ -76,7 +76,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): HALF = 'halv' #in-law string INLAW = 'ingift ' - + def __init__(self): gramps.gen.relationship.RelationshipCalculator.__init__(self) @@ -271,16 +271,16 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): result[-2] = result[-2] + 's ' return self.pair_up(result, step) - def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, + def get_sibling_relationship_string(self, sib_type, gender_a, gender_b, in_law_a=False, in_law_b=False): """ Determine the string giving the relation between two siblings of type sib_type. Eg: b is the brother of a Here 'brother' is the string we need to determine - This method gives more details about siblings than + This method gives more details about siblings than get_single_relationship_string can do. - + .. warning:: DON'T TRANSLATE THIS PROCEDURE IF LOGIC IS EQUAL IN YOUR LANGUAGE, AND SAME METHODS EXIST (get_uncle, get_aunt, get_sibling) @@ -320,26 +320,26 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): Provide a string that describes the relationsip between a person, and a group of people with the same relationship. E.g. "grandparents" or "children". - + Ga and Gb can be used to mathematically calculate the relationship. .. seealso:: http://en.wikipedia.org/wiki/Cousin#Mathematical_definitions - - :param Ga: The number of generations between the main person and the + + :param Ga: The number of generations between the main person and the common ancestor. :type Ga: int :param Gb: The number of generations between the group of people and the common ancestor :type Gb: int :param reltocommon_a: relation path to common ancestor or common - Family for person a. + Family for person a. Note that length = Ga - :type reltocommon_a: str + :type reltocommon_a: str :param reltocommon_b: relation path to common ancestor or common - Family for person b. + Family for person b. Note that length = Gb - :type reltocommon_b: str + :type reltocommon_b: str :param only_birth: True if relation between a and b is by birth only False otherwise :type only_birth: bool @@ -361,7 +361,7 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if Gb < _children_level: for AntBarn in range(Gb): result.append("barn") - rel_str = self.pair_up(result,'') + rel_str = self.pair_up(result,'') else: rel_str = "avlägsna ättlingar" elif Gb == 0: @@ -389,63 +389,63 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): result.append("syskonbarn") for AntBarn in range(Gb-2): result.append("barn") - rel_str = self.pair_up(result,'') + rel_str = self.pair_up(result,'') else: rel_str = "avlägsna brorsöner/systersöner/brorsdöttrar/systerdöttrar" elif Ga > 1 and Ga == Gb: # These are cousins in the same generation rel_str = self._get_cousin_kinship(Ga) elif Ga > 1 and Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. if Gb <= len(_level_name): rel_str = "förfäders " + self._get_cousin_kinship(Ga) + \ - " i "+ _level_name[Gb] + " generationen" + " i "+ _level_name[Gb] + " generationen" else: rel_str = "avlägsna kusiner" elif Gb > 1 and Gb > Ga: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. if Ga <= len(_level_name): result = [] result.append(self._get_cousin(Ga-1, False, '')) for AntBarn in range(Gb-Ga): result.append("barn") - rel_str = self.pair_up(result,'') + rel_str = self.pair_up(result,'') else: rel_str = "avlägsna kusiner" - + if in_law_b == True: rel_str = "makar till %s" % rel_str - + return rel_str def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b, reltocommon_a, reltocommon_b, - only_birth=True, + only_birth=True, in_law_a=False, in_law_b=False): """ Provide a string that describes the relationsip between a person, and another person. E.g. "grandparent" or "child". - + To be used as: 'person b is the grandparent of a', this will be in translation string: 'person b is the %(relation)s of a' - Note that languages with gender should add 'the' inside the + Note that languages with gender should add 'the' inside the translation, so eg in french: 'person b est %(relation)s de a' where relation will be here: le grandparent - + Ga and Gb can be used to mathematically calculate the relationship. - + .. seealso:: http://en.wikipedia.org/wiki/Cousin#Mathematical_definitions - + Some languages need to know the specific path to the common ancestor. - Those languages should use reltocommon_a and reltocommon_b which is + Those languages should use reltocommon_a and reltocommon_b which is a string like 'mfmf'. - + The possible string codes are: ======================= =========================================== @@ -461,27 +461,27 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): REL_FAM_BIRTH_FATH_ONLY # going up to fam, only birth rel to father ======================= =========================================== - Prefix codes are stripped, so REL_FAM_INLAW_PREFIX is not present. + Prefix codes are stripped, so REL_FAM_INLAW_PREFIX is not present. If the relation starts with the inlaw of the person a, then 'in_law_a' is True, if it starts with the inlaw of person b, then 'in_law_b' is True. - Also REL_SIBLING (# going sideways to sibling (no parents)) is not - passed to this routine. The collapse_relations changes this to a - family relation. + Also REL_SIBLING (# going sideways to sibling (no parents)) is not + passed to this routine. The collapse_relations changes this to a + family relation. - Hence, calling routines should always strip REL_SIBLING and + Hence, calling routines should always strip REL_SIBLING and REL_FAM_INLAW_PREFIX before calling get_single_relationship_string() Note that only_birth=False, means that in the reltocommon one of the NOTBIRTH specifiers is present. - The REL_FAM identifiers mean that the relation is not via a common - ancestor, but via a common family (note that that is not possible for + The REL_FAM identifiers mean that the relation is not via a common + ancestor, but via a common family (note that that is not possible for direct descendants or direct ancestors!). If the relation to one of the parents in that common family is by birth, then 'only_birth' is not set to False. The only_birth() method is normally used for this. - - :param Ga: The number of generations between the main person and the + + :param Ga: The number of generations between the main person and the common ancestor. :type Ga: int :param Gb: The number of generations between the other person and the @@ -492,13 +492,13 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): :param gender_b: gender of person b :type gender_b: int gender :param reltocommon_a: relation path to common ancestor or common - Family for person a. + Family for person a. Note that length = Ga - :type reltocommon_a: str + :type reltocommon_a: str :param reltocommon_b: relation path to common ancestor or common - Family for person b. + Family for person b. Note that length = Gb - :type reltocommon_b: str + :type reltocommon_b: str :param in_law_a: True if path to common ancestors is via the partner of person a :type in_law_a: bool @@ -510,10 +510,10 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): :type only_birth: bool :returns: A string describing the relationship between the two people :rtype: str - - .. note:: 1. the self.REL_SIBLING should not be passed to this routine, + + .. note:: 1. the self.REL_SIBLING should not be passed to this routine, so we should not check on it. All other self. - 2. for better determination of siblings, use if Ga=1=Gb + 2. for better determination of siblings, use if Ga=1=Gb get_sibling_relationship_string """ if only_birth: @@ -538,22 +538,22 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): elif Gb == 1: # b is sibling/aunt/uncle of a # handles brother and unknown gender as second person, - # shows up in "testing unknown cousins same generation" + # shows up in "testing unknown cousins same generation" if gender_b == Person.MALE or gender_b == Person.UNKNOWN: rel_str = self._get_ancestors_brother(reltocommon_a, gender_b, step, inlaw) elif gender_b == Person.FEMALE: rel_str = self._get_ancestors_sister(reltocommon_a, step, inlaw) elif Ga == Gb: # a and b cousins in the same generation - rel_str = self._get_cousin(Ga-1, step, inlaw) + rel_str = self._get_cousin(Ga-1, step, inlaw) elif Ga > Gb: - # These are cousins in different generations with the second person - # being in a higher generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a higher generation from the common ancestor than the # first person. rel_str = self._get_ancestors_cousin(reltocommon_a, reltocommon_b, step, inlaw) elif Gb > Ga: - # These are cousins in different generations with the second person - # being in a lower generation from the common ancestor than the + # These are cousins in different generations with the second person + # being in a lower generation from the common ancestor than the # first person. rel_str = self._get_cousins_descendant(gender_b, reltocommon_b, reltocommon_a, step, inlaw) return rel_str @@ -562,11 +562,11 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator): if __name__ == "__main__": # Test function. Call it as follows from the command line (so as to find # imported modules): - # export PYTHONPATH=/path/to/gramps/src - # python src/plugins/rel/rel_sv.py + # export PYTHONPATH=/path/to/gramps/src + # python src/plugins/rel/rel_sv.py # (Above not needed here) - - """TRANSLATORS, copy this if statement at the bottom of your + + """TRANSLATORS, copy this if statement at the bottom of your rel_xx.py module, and test your work with: python src/plugins/rel/rel_xx.py """ diff --git a/gramps/plugins/rel/relplugins.gpr.py b/gramps/plugins/rel/relplugins.gpr.py index cd2b8cc74..836963d1b 100644 --- a/gramps/plugins/rel/relplugins.gpr.py +++ b/gramps/plugins/rel/relplugins.gpr.py @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" # # Relationship calculators @@ -79,7 +79,7 @@ plg.status = STABLE plg.fname = 'rel_de.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' -plg.lang_list = ["de", "DE", "de_DE", "deutsch", "Deutsch", "de_DE.UTF8", +plg.lang_list = ["de", "DE", "de_DE", "deutsch", "Deutsch", "de_DE.UTF8", "de_DE@euro", "de_DE.UTF8@euro", "de_AT.UTF-8", "de_AT.utf-8", "de_AT.utf8", "german","German", "de_DE.UTF-8", "de_DE.utf-8", "de_DE.utf8", "de_CH.UTF-8", "de_CH.utf-8", "de_CH.utf8"] @@ -96,7 +96,7 @@ plg.fname = 'rel_es.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' plg.lang_list = ["es", "ES", "es_ES", "espanol", "Espanol", "es_ES.UTF8", - "es_ES@euro", "es_ES.UTF8@euro", "spanish", "Spanish", + "es_ES@euro", "es_ES.UTF8@euro", "spanish", "Spanish", "es_ES.UTF-8", "es_ES.utf-8", "es_ES.utf8"] # fi @@ -110,8 +110,8 @@ plg.status = STABLE plg.fname = 'rel_fi.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' -plg.lang_list = ["fi", "FI", "fi_FI", "finnish", "Finnish", "fi_FI.UTF8", - "fi_FI@euro", "fi_FI.UTF8@euro", "suomi", "Suomi", +plg.lang_list = ["fi", "FI", "fi_FI", "finnish", "Finnish", "fi_FI.UTF8", + "fi_FI@euro", "fi_FI.UTF8@euro", "suomi", "Suomi", "fi_FI.UTF-8", "fi_FI.utf-8", "fi_FI.utf8"] # fr @@ -126,7 +126,7 @@ plg.fname = 'rel_fr.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' plg.lang_list = ["fr", "FR", "fr_FR", "fr_CA", "français", - "Français", "fr_FR.UTF8", "fr_FR@euro", + "Français", "fr_FR.UTF8", "fr_FR@euro", "fr_FR.UTF8@euro", "french", "French", "fr_FR.UTF-8", "fr_FR.utf-8", "fr_FR.utf8", "fr_CA.UTF-8", "Français_France"] @@ -182,9 +182,9 @@ plg.status = STABLE plg.fname = 'rel_nl.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' -plg.lang_list = ["nl", "NL", "nl_NL", "nl_BE", "nederlands", "Nederlands", - "nl_NL.UTF8", "nl_BE.UTF8","nl_NL@euro", "nl_NL.UTF8@euro", - "nl_BE@euro", "dutch", "Dutch", "nl_NL.UTF-8", +plg.lang_list = ["nl", "NL", "nl_NL", "nl_BE", "nederlands", "Nederlands", + "nl_NL.UTF8", "nl_BE.UTF8","nl_NL@euro", "nl_NL.UTF8@euro", + "nl_BE@euro", "dutch", "Dutch", "nl_NL.UTF-8", "nl_BE.UTF-8", "nl_NL.utf-8", "nl_BE.utf-8","nl_NL.utf8", "nl_BE.UTF-8", "nl_BE.UTF8@euro"] @@ -199,10 +199,10 @@ plg.status = STABLE plg.fname = 'rel_no.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' -plg.lang_list = ["nb", "nn", "no", "nb_NO", "nn_NO", "no_NO", "nb_NO.UTF8", +plg.lang_list = ["nb", "nn", "no", "nb_NO", "nn_NO", "no_NO", "nb_NO.UTF8", "nn_NO.UTF8", "no_NO.UTF8", "nb_NO.UTF-8", "nn_NO.UTF-8", "no_NO.UTF-8", "nb_NO.utf-8", "nn_NO.utf-8", "no_NO.utf-8", - "nb_NO.iso88591", "nn_NO.iso88591", "no_NO.iso88591", + "nb_NO.iso88591", "nn_NO.iso88591", "no_NO.iso88591", "nynorsk", "Nynorsk"] # pl @@ -216,9 +216,9 @@ plg.status = STABLE plg.fname = 'rel_pl.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' -plg.lang_list = ["pl", "PL", "pl_PL", "polski", "Polski", - "pl_PL.UTF-8", "pl_PL.UTF8", "pl_PL.utf-8", "pl_PL.utf8", - "pl_PL.iso-8859-2", "pl_PL.iso8859-2", +plg.lang_list = ["pl", "PL", "pl_PL", "polski", "Polski", + "pl_PL.UTF-8", "pl_PL.UTF8", "pl_PL.utf-8", "pl_PL.utf8", + "pl_PL.iso-8859-2", "pl_PL.iso8859-2", "pl_PL.cp1250", "pl_PL.cp-1250"] # pt @@ -232,8 +232,8 @@ plg.status = STABLE plg.fname = 'rel_pt.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' -plg.lang_list = ["pt", "PT", "pt_PT", "pt_BR", "portugues", "Portugues", - "pt_PT.UTF8", "pt_BR.UTF8", "pt_PT@euro", "pt_PT.UTF8@euro", +plg.lang_list = ["pt", "PT", "pt_PT", "pt_BR", "portugues", "Portugues", + "pt_PT.UTF8", "pt_BR.UTF8", "pt_PT@euro", "pt_PT.UTF8@euro", "pt_PT.UTF-8", "pt_BR.UTF-8", "pt_PT.utf-8", "pt_BR.utf-8", "pt_PT.utf8","pt_BR.utf8"] @@ -248,7 +248,7 @@ plg.status = STABLE plg.fname = 'rel_ru.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' -plg.lang_list = ["ru", "RU", "ru_RU", "koi8r", "ru_koi8r", "russian", +plg.lang_list = ["ru", "RU", "ru_RU", "koi8r", "ru_koi8r", "russian", "Russian", "ru_RU.koi8r", "ru_RU.KOI8-R", "ru_RU.utf8", "ru_RU.UTF8", "ru_RU.utf-8", "ru_RU.UTF-8", "ru_RU.iso88595", "ru_RU.iso8859-5", "ru_RU.iso-8859-5"] @@ -264,7 +264,7 @@ plg.status = STABLE plg.fname = 'rel_sk.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' -plg.lang_list = ["sk", "SK", "sk_SK", "slovensky", "slovak", "Slovak", +plg.lang_list = ["sk", "SK", "sk_SK", "slovensky", "slovak", "Slovak", "sk_SK.UTF8", "sk_SK.UTF-8", "sk_SK.utf-8", "sk_SK.utf8"] # sl @@ -278,7 +278,7 @@ plg.status = STABLE plg.fname = 'rel_sl.py' plg.ptype = RELCALC plg.relcalcclass = 'RelationshipCalculator' -plg.lang_list = ["sl", "SL", "sl_SI", "slovenščina", "slovenian", "Slovenian", +plg.lang_list = ["sl", "SL", "sl_SI", "slovenščina", "slovenian", "Slovenian", "sl_SI.UTF8", "sl_SI.UTF-8", "sl_SI.utf-8", "sl_SI.utf8"] # sv plg = newplugin() @@ -309,4 +309,4 @@ plg.lang_list = ["uk", "UA", "uk_UA", "ukrainian", "Ukrainian", "uk_UA.utf8", "uk_UA.UTF8", "uk_UA.utf-8", "uk_UA.UTF-8", "uk_UA.iso88595", "uk_UA.iso8859-5", "uk_UA.iso-8859-5", "koi8u", "uk_koi8u", - "uk_UA.koi8u","uk_UA.KOI8-U",] + "uk_UA.koi8u","uk_UA.KOI8-U",] diff --git a/gramps/plugins/sidebar/categorysidebar.py b/gramps/plugins/sidebar/categorysidebar.py index 9841103c7..495a88809 100644 --- a/gramps/plugins/sidebar/categorysidebar.py +++ b/gramps/plugins/sidebar/categorysidebar.py @@ -76,7 +76,7 @@ class CategorySidebar(BaseSidebar): self.window.add(vbox) self.window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) self.window.show() - + use_text = config.get('interface.sidebar-text') for cat_num, cat_name, cat_icon in categories: @@ -84,7 +84,7 @@ class CategorySidebar(BaseSidebar): button = self.__make_sidebar_button(use_text, cat_num, cat_name, cat_icon) vbox.pack_start(button, False, True, 0) - + # Enable view switching during DnD button.drag_dest_set(0, [], 0) button.connect('drag_motion', self.cb_switch_page_on_dnd, cat_num) @@ -124,14 +124,14 @@ class CategorySidebar(BaseSidebar): else: button.set_active(False) self.__handlers_unblock() - + def __handlers_block(self): """ Block signals to the buttons to prevent spurious events. """ for idx in range(len(self.buttons)): self.buttons[idx].handler_block(self.button_handlers[idx]) - + def __handlers_unblock(self): """ Unblock signals to the buttons. @@ -173,7 +173,7 @@ class CategorySidebar(BaseSidebar): self.button_handlers.append(handler_id) button.show() - # add the image. If we are using text, use the BUTTON (larger) size. + # add the image. If we are using text, use the BUTTON (larger) size. # otherwise, use the smaller size hbox = Gtk.Box() hbox.show() @@ -191,7 +191,7 @@ class CategorySidebar(BaseSidebar): label = Gtk.Label(label=page_title) label.show() hbox.pack_start(label, False, True, 0) - + button.add(hbox) return button diff --git a/gramps/plugins/sidebar/dropdownsidebar.py b/gramps/plugins/sidebar/dropdownsidebar.py index fa0fb17a7..96bd7cd45 100644 --- a/gramps/plugins/sidebar/dropdownsidebar.py +++ b/gramps/plugins/sidebar/dropdownsidebar.py @@ -46,7 +46,7 @@ _ = glocale.translation.gettext #------------------------------------------------------------------------- class DropdownSidebar(BaseSidebar): """ - A sidebar displaying toggle buttons and buttons with drop-down menus that + A sidebar displaying toggle buttons and buttons with drop-down menus that allows the user to change the current view. """ def __init__(self, dbstate, uistate, categories, views): @@ -62,7 +62,7 @@ class DropdownSidebar(BaseSidebar): self.window.add(grid) self.window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) self.window.show() - + use_text = config.get('interface.sidebar-text') for cat_num, cat_name, cat_icon in categories: self.__make_category(grid, use_text, cat_num, cat_name, cat_icon) @@ -87,14 +87,14 @@ class DropdownSidebar(BaseSidebar): else: button.set_active(False) self.__handlers_unblock() - + def __handlers_block(self): """ Block signals to the buttons to prevent spurious events. """ for idx in range(len(self.buttons)): self.buttons[idx].handler_block(self.button_handlers[idx]) - + def __handlers_unblock(self): """ Unblock signals to the buttons. @@ -152,7 +152,7 @@ class DropdownSidebar(BaseSidebar): if len(self.views[cat_num]) > 1: dropdown = Gtk.Button() dropdown.set_relief(Gtk.ReliefStyle.NONE) - arrow = Gtk.Arrow(arrow_type=Gtk.ArrowType.DOWN, + arrow = Gtk.Arrow(arrow_type=Gtk.ArrowType.DOWN, shadow_type=Gtk.ShadowType.NONE) dropdown.add(arrow) dropdown.connect('clicked', self.__view_clicked, cat_num) @@ -167,7 +167,7 @@ class DropdownSidebar(BaseSidebar): self.button_handlers.append(handler_id) button.show() - # add the image. If we are using text, use the BUTTON (larger) size. + # add the image. If we are using text, use the BUTTON (larger) size. # otherwise, use the smaller size hbox = Gtk.Box() hbox.show() @@ -187,12 +187,12 @@ class DropdownSidebar(BaseSidebar): hbox.pack_start(label, False, True, 0) button.add(hbox) - + # Enable view switching during DnD button.drag_dest_set(0, [], 0) button.connect('drag_motion', self.cb_switch_page_on_dnd, cat_num) - grid.attach(button, 0, cat_num, 1, 1) + grid.attach(button, 0, cat_num, 1, 1) def cb_switch_page_on_dnd(self, widget, context, xpos, ypos, time, page_no): """ @@ -218,5 +218,5 @@ def cb_menu_position(*args): ret_val, x_pos, y_pos = button.get_window().get_origin() x_pos += button.get_allocation().x y_pos += button.get_allocation().y + button.get_allocation().height - + return (x_pos, y_pos, False) diff --git a/gramps/plugins/sidebar/expandersidebar.py b/gramps/plugins/sidebar/expandersidebar.py index effc8b07c..2bb892e7f 100644 --- a/gramps/plugins/sidebar/expandersidebar.py +++ b/gramps/plugins/sidebar/expandersidebar.py @@ -46,7 +46,7 @@ from gramps.gui.basesidebar import BaseSidebar #------------------------------------------------------------------------- class ExpanderSidebar(BaseSidebar): """ - A sidebar displaying toggle buttons and buttons with drop-down menus that + A sidebar displaying toggle buttons and buttons with drop-down menus that allows the user to change the current view. """ def __init__(self, dbstate, uistate, categories, views): @@ -64,7 +64,7 @@ class ExpanderSidebar(BaseSidebar): self.window.add(vbox) self.window.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC) self.window.show() - + use_text = config.get('interface.sidebar-text') for cat_num, cat_name, cat_icon in categories: @@ -90,7 +90,7 @@ class ExpanderSidebar(BaseSidebar): viewbox.pack_start(button, False, False, 0) expander.add(viewbox) vbox.pack_start(expander, False, True, 0) - + # Enable view switching during DnD #catbox.drag_dest_set(0, [], 0) #catbox.connect('drag_motion', self.cb_switch_page_on_dnd, cat_num) @@ -119,14 +119,14 @@ class ExpanderSidebar(BaseSidebar): else: button.set_active(False) self.__handlers_unblock() - + def __handlers_block(self): """ Block signals to the buttons to prevent spurious events. """ for idx in range(len(self.buttons)): self.buttons[idx].handler_block(self.button_handlers[idx]) - + def __handlers_unblock(self): """ Unblock signals to the buttons. @@ -168,7 +168,7 @@ class ExpanderSidebar(BaseSidebar): the button. """ top = Gtk.Box() - + # create the button button = Gtk.ToggleButton() button.set_relief(Gtk.ReliefStyle.NONE) @@ -183,7 +183,7 @@ class ExpanderSidebar(BaseSidebar): self.button_handlers.append(handler_id) button.show() - # add the image. If we are using text, use the BUTTON (larger) size. + # add the image. If we are using text, use the BUTTON (larger) size. # otherwise, use the smaller size hbox = Gtk.Box() hbox.show() @@ -201,11 +201,11 @@ class ExpanderSidebar(BaseSidebar): label = Gtk.Label(label=view_name) label.show() hbox.pack_start(label, False, True, 0) - + button.add(hbox) - + top.pack_start(button, False, True, 0) - + return top def cb_switch_page_on_dnd(self, widget, context, xpos, ypos, time, page_no): @@ -232,5 +232,5 @@ def cb_menu_position(*args): ret_val, x_pos, y_pos = button.get_window().get_origin() x_pos += button.get_allocation().x y_pos += button.get_allocation().y + button.get_allocation().height - + return (x_pos, y_pos, False) diff --git a/gramps/plugins/sidebar/sidebar.gpr.py b/gramps/plugins/sidebar/sidebar.gpr.py index e81c7cb84..ecbe9e6a7 100644 --- a/gramps/plugins/sidebar/sidebar.gpr.py +++ b/gramps/plugins/sidebar/sidebar.gpr.py @@ -19,7 +19,7 @@ # # $Id: sidebar.gpr.py 20634 2012-11-07 17:53:14Z bmcage $ -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # @@ -27,7 +27,7 @@ MODULE_VERSION="5.0" # #------------------------------------------------------------------------ -register(SIDEBAR, +register(SIDEBAR, id = 'categorysidebar', name = _("Category Sidebar"), description = _("A sidebar to allow the selection of view categories"), @@ -42,7 +42,7 @@ menu_label = _('Category'), order = START ) -register(SIDEBAR, +register(SIDEBAR, id = 'dropdownsidebar', name = _("Drop-down Sidebar"), description = _("Selection of categories and views from drop-down lists"), @@ -57,7 +57,7 @@ menu_label = _('Drop-Down'), order = END ) -register(SIDEBAR, +register(SIDEBAR, id = 'expandersidebar', name = _("Expander Sidebar"), description = _("Selection of views from lists with expanders"), diff --git a/gramps/plugins/textreport/alphabeticalindex.py b/gramps/plugins/textreport/alphabeticalindex.py index ae2c40aa0..eade10da5 100644 --- a/gramps/plugins/textreport/alphabeticalindex.py +++ b/gramps/plugins/textreport/alphabeticalindex.py @@ -34,7 +34,7 @@ _ = glocale.translation.sgettext from gramps.gen.plug.report import Report from gramps.gen.plug.report import MenuReportOptions from gramps.gen.plug.report import stdoptions -from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle, TableStyle, +from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle, TableStyle, TableCellStyle, FONT_SANS_SERIF, IndexMark, INDEX_TYPE_TOC) @@ -48,7 +48,7 @@ class AlphabeticalIndex(Report): def __init__(self, database, options, user): """ Create AlphabeticalIndex object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -78,11 +78,11 @@ class AlphabeticalIndexOptions(MenuReportOptions): """ Defines options and provides handling interface. """ - + def __init__(self, name, dbase): self.__db = dbase MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add the options for this report """ category_name = _("Report Options") @@ -97,17 +97,17 @@ class AlphabeticalIndexOptions(MenuReportOptions): para.set_bottom_margin(0.25) para.set_description(_('The style used for the title.')) default_style.add_paragraph_style("IDX-Title", para) - + table = TableStyle() table.set_width(100) table.set_columns(2) table.set_column_width(0, 80) table.set_column_width(1, 20) default_style.add_table_style("IDX-Table", table) - + cell = TableCellStyle() default_style.add_cell_style("IDX-Cell", cell) - + font = FontStyle() font.set(face=FONT_SANS_SERIF, size=10) para = ParagraphStyle() diff --git a/gramps/plugins/textreport/ancestorreport.py b/gramps/plugins/textreport/ancestorreport.py index d660131b8..a7eeeb6a3 100644 --- a/gramps/plugins/textreport/ancestorreport.py +++ b/gramps/plugins/textreport/ancestorreport.py @@ -41,7 +41,7 @@ from gramps.gen.errors import ReportError from gramps.gen.lib import ChildRefType from gramps.gen.plug.menu import (BooleanOption, NumberOption, PersonOption) from gramps.gen.plug.docgen import (IndexMark, FontStyle, ParagraphStyle, - FONT_SANS_SERIF, INDEX_TYPE_TOC, + FONT_SANS_SERIF, INDEX_TYPE_TOC, PARA_ALIGN_CENTER) from gramps.gen.plug.report import Report from gramps.gen.plug.report import utils as ReportUtils @@ -72,7 +72,7 @@ class AncestorReport(Report): def __init__(self, database, options, user): """ Create the AncestorReport object that produces the Ahnentafel report. - + The arguments are: database - the GRAMPS database instance @@ -81,7 +81,7 @@ class AncestorReport(Report): This report needs the following parameters (class variables) that come in the options class. - + gen - Maximum number of generations to include. pagebbg - Whether to include page breaks between generations. name_format - Preferred format to display names @@ -123,7 +123,7 @@ class AncestorReport(Report): if not person_handle or generation > self.max_generations: return - # store the person in the map based off their index number + # store the person in the map based off their index number # which is passed to the routine. self.map[index] = person_handle @@ -148,8 +148,8 @@ class AncestorReport(Report): if ref: # If the father_handle is not defined and the relationship is - # BIRTH, then we have found the birth father. Same applies to - # the birth mother. If for some reason, the we have multiple + # BIRTH, then we have found the birth father. Same applies to + # the birth mother. If for some reason, the we have multiple # people defined as the birth parents, we will select based on # priority in the list @@ -160,7 +160,7 @@ class AncestorReport(Report): ref[0].get_mother_relation() == ChildRefType.BIRTH: mother_handle = family.get_mother_handle() - # Recursively call the function. It is okay if the handle is None, + # Recursively call the function. It is okay if the handle is None, # since routine handles a handle of None self.apply_filter(father_handle, index*2, generation+1) @@ -172,7 +172,7 @@ class AncestorReport(Report): is opened and ready for writing. """ - # Call apply_filter to build the self.map array of people in the + # Call apply_filter to build the self.map array of people in the # database that match the ancestry. self.apply_filter(self.center_person.get_handle(), 1) @@ -183,11 +183,11 @@ class AncestorReport(Report): name = self._name_display.display_formal(self.center_person) # feature request 2356: avoid genitive form title = self._("Ahnentafel Report for %s") % name - mark = IndexMark(title, INDEX_TYPE_TOC, 1) + mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.start_paragraph("AHN-Title") self.doc.write_text(title, mark) self.doc.end_paragraph() - + # get the entries out of the map, and sort them. generation = 0 @@ -217,13 +217,13 @@ class AncestorReport(Report): person = self.database.get_person_from_handle(self.map[key]) name = self._name_display.display(person) mark = ReportUtils.get_person_mark(self.database, person) - + # write the name in bold self.doc.start_bold() self.doc.write_text(name.strip(), mark) self.doc.end_bold() - # terminate with a period if it is not already terminated. + # terminate with a period if it is not already terminated. # This can happen if the person's name ends with something 'Jr.' if name[-1:] == '.': self.doc.write_text(" ") @@ -240,7 +240,7 @@ class AncestorReport(Report): self.doc.write_text(self.__narrator.get_christened_string()) self.doc.write_text(self.__narrator.get_died_string()) self.doc.write_text(self.__narrator.get_buried_string()) - + self.doc.end_paragraph() #------------------------------------------------------------------------ @@ -256,30 +256,30 @@ class AncestorOptions(MenuReportOptions): def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the ancestor report. """ category_name = _("Report Options") - + pid = PersonOption(_("Center Person")) pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", pid) stdoptions.add_name_format_option(menu, category_name) - + stdoptions.add_private_data_option(menu, category_name) maxgen = NumberOption(_("Generations"), 10, 1, 100) maxgen.set_help(_("The number of generations to include in the report")) menu.add_option(category_name, "maxgen", maxgen) - + pagebbg = BooleanOption(_("Page break between generations"), False) pagebbg.set_help( _("Whether to start a new page after each generation.")) menu.add_option(category_name, "pagebbg", pagebbg) - + namebrk = BooleanOption(_("Add linebreak after each name"), False) namebrk.set_help(_("Indicates if a line break should follow the name.")) menu.add_option(category_name, "namebrk", namebrk) @@ -308,7 +308,7 @@ class AncestorOptions(MenuReportOptions): 14pt Paragraph : Second level header 0.125cm top and bottom margins - + AHN - Normal text display for each entry Font : default @@ -326,10 +326,10 @@ class AncestorOptions(MenuReportOptions): para.set_header_level(1) para.set_top_margin(0.25) para.set_bottom_margin(0.25) - para.set_alignment(PARA_ALIGN_CENTER) + para.set_alignment(PARA_ALIGN_CENTER) para.set_description(_('The style used for the title of the page.')) default_style.add_paragraph_style("AHN-Title", para) - + # # AHN-Generation # @@ -339,16 +339,16 @@ class AncestorOptions(MenuReportOptions): para.set_font(font) para.set_header_level(2) para.set_top_margin(0.125) - para.set_bottom_margin(0.125) + para.set_bottom_margin(0.125) para.set_description(_('The style used for the generation header.')) default_style.add_paragraph_style("AHN-Generation", para) - + # # AHN-Entry # para = ParagraphStyle() para.set(first_indent=-1.0, lmargin=1.0) para.set_top_margin(0.125) - para.set_bottom_margin(0.125) + para.set_bottom_margin(0.125) para.set_description(_('The basic style used for the text display.')) default_style.add_paragraph_style("AHN-Entry", para) diff --git a/gramps/plugins/textreport/birthdayreport.py b/gramps/plugins/textreport/birthdayreport.py index 3397ca98d..1101bd84d 100644 --- a/gramps/plugins/textreport/birthdayreport.py +++ b/gramps/plugins/textreport/birthdayreport.py @@ -44,7 +44,7 @@ from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle, GraphicsStyle, FONT_SERIF, PARA_ALIGN_RIGHT, PARA_ALIGN_LEFT, PARA_ALIGN_CENTER, IndexMark, INDEX_TYPE_TOC) -from gramps.gen.plug.menu import (BooleanOption, StringOption, NumberOption, +from gramps.gen.plug.menu import (BooleanOption, StringOption, NumberOption, EnumeratedListOption, FilterOption, PersonOption) from gramps.gen.plug.report import Report @@ -101,20 +101,20 @@ class BirthdayReport(Report): self.filter_option = menu.get_option_by_name('filter') self.filter = self.filter_option.get_filter() pid = mgobn('pid') - + lang = menu.get_option_by_name('trans').get_value() self._locale = self.set_locale(lang) stdoptions.run_name_format_option(self, menu) - + self.center_person = database.get_person_from_gramps_id(pid) if (self.center_person == None) : raise ReportError(_("Person %s is not in the Database") % pid ) def get_name(self, person, maiden_name = None): - """ - Return person's name, unless maiden_name given, unless married_name - listed. + """ + Return person's name, unless maiden_name given, unless married_name + listed. """ # Get all of a person's names: primary_name = person.get_primary_name() @@ -151,7 +151,7 @@ class BirthdayReport(Report): holiday_table.load_holidays(self.year, country) for month in range(1, 13): for day in range(1, 32): - holiday_names = holiday_table.get_holidays(month, day) + holiday_names = holiday_table.get_holidays(month, day) for holiday_name in holiday_names: self.add_day_item(self._(holiday_name), month, day) # FIXME translation only works for a limited set of things @@ -179,7 +179,7 @@ class BirthdayReport(Report): # get data from database: self.collect_data() # generate the report: - self.doc.start_paragraph('BIR-Title') + self.doc.start_paragraph('BIR-Title') if self.titletext == _(_TITLE0): title = self._(_TITLE0) + ": " + str(self.year) else: @@ -215,7 +215,7 @@ class BirthdayReport(Report): self.doc.write_text(self._("Relationships shown are to %s") % self._name_display.display_name(name), mark) self.doc.end_paragraph() - with self._user.progress(_('Birthday and Anniversary Report'), + with self._user.progress(_('Birthday and Anniversary Report'), _('Formatting months...'), 12) as step: for month in range(1, 13): step() @@ -254,17 +254,17 @@ class BirthdayReport(Report): and text. """ people = self.database.iter_person_handles() - with self._user.progress(_('Birthday and Anniversary Report'), - _('Applying Filter...'), + with self._user.progress(_('Birthday and Anniversary Report'), + _('Applying Filter...'), self.database.get_number_of_people()) as step: - people = self.filter.apply(self.database, people, + people = self.filter.apply(self.database, people, step) - + ngettext = self._locale.translation.ngettext # to see "nearby" comments rel_calc = get_relationship_calculator(reinit=True, clocale=self._locale) - with self._user.progress(_('Birthday and Anniversary Report'), + with self._user.progress(_('Birthday and Anniversary Report'), _('Reading database...'), len(people)) as step: for person_handle in people: step() @@ -314,8 +314,8 @@ class BirthdayReport(Report): comment = "" if self.relationships: relation = rel_calc.get_one_relationship( - self.database, - self.center_person, + self.database, + self.center_person, person, olocale=self._locale) if relation: @@ -327,7 +327,7 @@ class BirthdayReport(Report): 'relation' : comment} else: # translators: leave all/any {...} untranslated - text = ngettext('{person}, {age}{relation}', + text = ngettext('{person}, {age}{relation}', '{person}, {age}{relation}', nyears).format(person=short_name, age=nyears, @@ -336,7 +336,7 @@ class BirthdayReport(Report): self.add_day_item(text, month, day, person) if self.anniversaries: family_list = person.get_family_handle_list() - for fhandle in family_list: + for fhandle in family_list: fam = self.database.get_family_from_handle(fhandle) father_handle = fam.get_father_handle() mother_handle = fam.get_mother_handle() @@ -355,11 +355,11 @@ class BirthdayReport(Report): are_married = None for event_ref in fam.get_event_ref_list(): event = self.database.get_event_from_handle(event_ref.ref) - if event.type in [EventType.MARRIAGE, + if event.type in [EventType.MARRIAGE, EventType.MARR_ALT]: are_married = event - elif event.type in [EventType.DIVORCE, - EventType.ANNULMENT, + elif event.type in [EventType.DIVORCE, + EventType.ANNULMENT, EventType.DIV_FILING]: are_married = None if are_married is not None: @@ -376,14 +376,14 @@ class BirthdayReport(Report): if event_obj.is_valid(): if nyears == 0: text = self._("%(spouse)s and\n %(person)s, wedding") % { - 'spouse' : spouse_name, + 'spouse' : spouse_name, 'person' : short_name} else: # translators: leave all/any {...} untranslated text = ngettext("{spouse} and\n {person}, {nyears}", "{spouse} and\n {person}, {nyears}", nyears).format(spouse=spouse_name, person=short_name, nyears=nyears) - + prob_alive_date = Date(self.year, month, day) alive1 = probably_alive(person, self.database, prob_alive_date) @@ -404,12 +404,12 @@ class BirthdayOptions(MenuReportOptions): self.__pid = None self.__filter = None MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add the options for the text birthday report """ category_name = _("Report Options") - year = NumberOption(_("Year of report"), time.localtime()[0], + year = NumberOption(_("Year of report"), time.localtime()[0], 1000, 3000) year.set_help(_("Year of report")) menu.add_option(category_name, "year", year) @@ -418,7 +418,7 @@ class BirthdayOptions(MenuReportOptions): self.__filter.set_help( _("Select filter to restrict people that appear on report")) menu.add_option(category_name, "filter", self.__filter) - + self.__pid = PersonOption(_("Center Person")) self.__pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", self.__pid) @@ -439,7 +439,7 @@ class BirthdayOptions(MenuReportOptions): holiday_table = libholiday.HolidayTable() countries = holiday_table.get_countries() countries.sort() - if (len(countries) == 0 or + if (len(countries) == 0 or (len(countries) > 0 and countries[0] != '')): countries.insert(0, '') count = 0 @@ -453,9 +453,9 @@ class BirthdayOptions(MenuReportOptions): long_days = date_displayer.long_days for count in range(1, 8): # conversion between gramps numbering (sun=1) and iso numbering (mon=1) of weekdays below - start_dow.add_item((count+5) % 7 + 1, long_days[count].capitalize()) + start_dow.add_item((count+5) % 7 + 1, long_days[count].capitalize()) start_dow.set_help(_("Select the first day of the week for the report")) - menu.add_option(category_name, "start_dow", start_dow) + menu.add_option(category_name, "start_dow", start_dow) maiden_name = EnumeratedListOption(_("Birthday surname"), "own") maiden_name.add_item("spouse_first", _("Wives use husband's surname (from first family listed)")) @@ -471,8 +471,8 @@ class BirthdayOptions(MenuReportOptions): anniversaries = BooleanOption(_("Include anniversaries"), True) anniversaries.set_help(_("Include anniversaries in the report")) menu.add_option(category_name, "anniversaries", anniversaries) - - option = BooleanOption(_("Include relationships to center person"), + + option = BooleanOption(_("Include relationships to center person"), False) option.set_help(_("Include relationships to center person (slower)")) menu.add_option(category_name, "relationships", option) @@ -480,12 +480,12 @@ class BirthdayOptions(MenuReportOptions): stdoptions.add_localization_option(menu, category_name) category_name = _("Text Options") - + titletext = StringOption(_("Title text"), _(_TITLE0)) titletext.set_help(_("Title of report")) menu.add_option(category_name, "titletext", titletext) - text1 = StringOption(_("Text Area 1"), _(_TITLE1)) + text1 = StringOption(_("Text Area 1"), _(_TITLE1)) text1.set_help(_("First line of text at bottom of report")) menu.add_option(category_name, "text1", text1) @@ -496,7 +496,7 @@ class BirthdayOptions(MenuReportOptions): text3 = StringOption(_("Text Area 3"), URL_HOMEPAGE,) text3.set_help(_("Third line of text at bottom of report")) menu.add_option(category_name, "text3", text3) - + def __update_filters(self): """ Update the filter list based on the selected person @@ -509,9 +509,9 @@ class BirthdayOptions(MenuReportOptions): name_format=nfv) self.__filter.set_filters(filter_list) - def make_my_style(self, default_style, name, description, - size=9, font=FONT_SERIF, justified ="left", - color=None, align=PARA_ALIGN_CENTER, + def make_my_style(self, default_style, name, description, + size=9, font=FONT_SERIF, justified ="left", + color=None, align=PARA_ALIGN_CENTER, shadow = None, italic=0, bold=0, borders=0, indent=None): """ Create paragraph and graphic styles of the same name """ # Paragraph: @@ -531,11 +531,11 @@ class BirthdayOptions(MenuReportOptions): if indent: p.set(first_indent=indent) if justified == "left": - p.set_alignment(PARA_ALIGN_LEFT) + p.set_alignment(PARA_ALIGN_LEFT) elif justified == "right": - p.set_alignment(PARA_ALIGN_RIGHT) + p.set_alignment(PARA_ALIGN_RIGHT) elif justified == "center": - p.set_alignment(PARA_ALIGN_CENTER) + p.set_alignment(PARA_ALIGN_CENTER) default_style.add_paragraph_style(name, p) # Graphics: g = GraphicsStyle() @@ -547,22 +547,22 @@ class BirthdayOptions(MenuReportOptions): if not borders: g.set_line_width(0) default_style.add_draw_style(name, g) - + def make_default_style(self, default_style): """ Add the styles used in this report """ - self.make_my_style(default_style, "BIR-Title", - _('Title text style'), 14, + self.make_my_style(default_style, "BIR-Title", + _('Title text style'), 14, bold=1, justified="center") - self.make_my_style(default_style, "BIR-Datastyle", + self.make_my_style(default_style, "BIR-Datastyle", _('Data text display'), 12, indent=1.0) - self.make_my_style(default_style, "BIR-Daystyle", - _('Day text style'), 12, indent=.5, + self.make_my_style(default_style, "BIR-Daystyle", + _('Day text style'), 12, indent=.5, italic=1, bold=1) - self.make_my_style(default_style, "BIR-Monthstyle", + self.make_my_style(default_style, "BIR-Monthstyle", _('Month text style'), 14, bold=1) - self.make_my_style(default_style, "BIR-Text1style", + self.make_my_style(default_style, "BIR-Text1style", _('Text at bottom, line 1'), 12, justified="center") - self.make_my_style(default_style, "BIR-Text2style", + self.make_my_style(default_style, "BIR-Text2style", _('Text at bottom, line 2'), 12, justified="center") - self.make_my_style(default_style, "BIR-Text3style", + self.make_my_style(default_style, "BIR-Text3style", _('Text at bottom, line 3'), 12, justified="center") diff --git a/gramps/plugins/textreport/custombooktext.py b/gramps/plugins/textreport/custombooktext.py index f204f641a..7f337c6a0 100644 --- a/gramps/plugins/textreport/custombooktext.py +++ b/gramps/plugins/textreport/custombooktext.py @@ -20,7 +20,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -# Written by Alex Roitman, +# Written by Alex Roitman, # largely based on the SimpleBookTitle.py by Don Allingham #------------------------------------------------------------------------ @@ -59,7 +59,7 @@ class CustomText(Report): def __init__(self, database, options, user): """ Create CustomText object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -68,7 +68,7 @@ class CustomText(Report): This report needs the following parameters (class variables) that come in the options class. - + top - Text on the top. mid - Text in the middle. bot - Text on the bottom. @@ -79,7 +79,7 @@ class CustomText(Report): self.top_text = menu.get_option_by_name('top').get_value() self.middle_text = menu.get_option_by_name('mid').get_value() self.bottom_text = menu.get_option_by_name('bot').get_value() - + def write_report(self): mark_text = _("Custom Text") if self.top_text[0]: @@ -117,22 +117,22 @@ class CustomTextOptions(MenuReportOptions): """ Defines options and provides handling interface. """ - + def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): - + category_name = _("Text") - + top = TextOption(_("Initial Text"), [""] ) top.set_help(_("Text to display at the top.")) menu.add_option(category_name, "top", top) - + mid = TextOption(_("Middle Text"), [""] ) mid.set_help(_("Text to display in the middle")) menu.add_option(category_name, "mid", mid) - + bot = TextOption(_("Final Text"), [""] ) bot.set_help(_("Text to display last.")) menu.add_option(category_name, "bot", bot) diff --git a/gramps/plugins/textreport/descendreport.py b/gramps/plugins/textreport/descendreport.py index 26a41398e..ecc85e82d 100644 --- a/gramps/plugins/textreport/descendreport.py +++ b/gramps/plugins/textreport/descendreport.py @@ -81,8 +81,8 @@ class PrintSimple(): self.num[level-1] = self.num[level-1] + 1 return to_return - - + + #------------------------------------------------------------------------ # # PrintVlliers @@ -93,18 +93,18 @@ class PrintVilliers(): def __init__(self): self.pama = 'abcdefghijklmnopqrstuvwxyz' self.num = {0:1} - + def number(self, level): to_return = self.pama[level-1] if level > 1: to_return += str(self.num[level-1]) to_return += "." - + self.num[level] = 1 self.num[level-1] = self.num[level-1] + 1 return to_return - + #------------------------------------------------------------------------ # @@ -115,7 +115,7 @@ class PrintVilliers(): class PrintMeurgey(): def __init__(self): self.childnum = [""] - + def number(self, level): if level == 1: dash = "" @@ -123,15 +123,15 @@ class PrintMeurgey(): dash = "-" if len(self.childnum) < level: self.childnum.append(1) - + to_return = (ReportUtils.roman(level) + dash + str(self.childnum[level-1]) + ".") if level > 1: self.childnum[level-1] += 1 - + return to_return - + #------------------------------------------------------------------------ # @@ -184,7 +184,7 @@ class Printinfo(): if string and tmp: string += ", " string += tmp - + if string: string = " (" + string + ")" @@ -210,7 +210,7 @@ class Printinfo(): self.dump_string(person) self.doc.end_paragraph() return display_num - + def print_spouse(self, level, spouse_handle, family_handle): #Currently print_spouses is the same for all numbering systems. if spouse_handle: @@ -249,9 +249,9 @@ class Printinfo(): class RecurseDown(): """ A simple object to recurse from a person down through their descendants - + The arguments are: - + max_generations: The max number of generations database: The database object objPrint: A Printinfo derived class that prints person @@ -314,7 +314,7 @@ class DescendantReport(Report): def __init__(self, database, options, user): """ Create the DescendantReport object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -323,7 +323,7 @@ class DescendantReport(Report): This report needs the following parameters (class variables) that come in the options class. - + gen - Maximum number of generations to include. name_format - Preferred format to display names dups - Whether to include duplicate descendant trees @@ -341,13 +341,13 @@ class DescendantReport(Report): self.center_person = self.database.get_person_from_gramps_id(pid) if (self.center_person == None) : raise ReportError(_("Person %s is not in the Database") % pid ) - + sort = Sort(self.database) - + lang = menu.get_option_by_name('trans').get_value() self._locale = self.set_locale(lang) - #Initialize the Printinfo class + #Initialize the Printinfo class self._showdups = menu.get_option_by_name('dups').get_value() numbering = menu.get_option_by_name('numbering').get_value() if numbering == "Simple": @@ -366,7 +366,7 @@ class DescendantReport(Report): self.objPrint = Printinfo(self.doc, self.database, obj, marrs, divs, self._name_display, self._locale) - + def write_report(self): self.doc.start_paragraph("DR-Title") name = self._name_display.display(self.center_person) @@ -375,7 +375,7 @@ class DescendantReport(Report): mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.write_text(title, mark) self.doc.end_paragraph() - + recurse = RecurseDown(self.max_generations, self.database, self.objPrint, self._showdups, self._locale) recurse.recurse(1, self.center_person, None) @@ -393,26 +393,26 @@ class DescendantOptions(MenuReportOptions): def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): category_name = _("Report Options") - + pid = PersonOption(_("Center Person")) pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", pid) - + stdoptions.add_name_format_option(menu, category_name) stdoptions.add_private_data_option(menu, category_name) numbering = EnumeratedListOption(_("Numbering system"), "Simple") numbering.set_items([ - ("Simple", _("Simple numbering")), - ("de Villiers/Pama", _("de Villiers/Pama numbering")), + ("Simple", _("Simple numbering")), + ("de Villiers/Pama", _("de Villiers/Pama numbering")), ("Meurgey de Tupigny", _("Meurgey de Tupigny numbering"))]) numbering.set_help(_("The numbering system to be used")) menu.add_option(category_name, "numbering", numbering) - + gen = NumberOption(_("Generations"), 10, 1, 15) gen.set_help(_("The number of generations to include in the report")) menu.add_option(category_name, "gen", gen) diff --git a/gramps/plugins/textreport/detancestralreport.py b/gramps/plugins/textreport/detancestralreport.py index eccc45c88..7dfd1c04b 100644 --- a/gramps/plugins/textreport/detancestralreport.py +++ b/gramps/plugins/textreport/detancestralreport.py @@ -47,7 +47,7 @@ _ = glocale.translation.gettext from gramps.gen.errors import ReportError from gramps.gen.lib import EventType, FamilyRelType, Person, NoteType from gramps.gen.plug.docgen import (IndexMark, FontStyle, ParagraphStyle, - FONT_SANS_SERIF, FONT_SERIF, + FONT_SANS_SERIF, FONT_SERIF, INDEX_TYPE_TOC, PARA_ALIGN_CENTER) from gramps.gen.plug.menu import BooleanOption, NumberOption, PersonOption from gramps.gen.plug.report import Report, Bibliography @@ -75,7 +75,7 @@ class DetAncestorReport(Report): def __init__(self, database, options, user): """ Create the DetAncestorReport object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -84,7 +84,7 @@ class DetAncestorReport(Report): 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. @@ -151,7 +151,7 @@ class DetAncestorReport(Report): self.gen_handles = {} self.prev_gen_handles = {} - + if blankdate: empty_date = EMPTY_ENTRY else: @@ -253,7 +253,7 @@ class DetAncestorReport(Report): person = self.db.get_person_from_handle(person_handle) plist = person.get_media_list() self.__narrator.set_subject(person) - + if self.addimages and len(plist) > 0: photo = plist[0] ReportUtils.insert_image(self.db, self.doc, photo, self._user) @@ -276,7 +276,7 @@ class DetAncestorReport(Report): if self.dupperson: # Check for duplicate record (result of distant cousins marrying) for dkey in sorted(self.map): - if dkey >= key: + if dkey >= key: break if self.map[key] == self.map[dkey]: self.doc.write_text( @@ -284,7 +284,7 @@ class DetAncestorReport(Report): % { 'name' : '', 'id_str' : str(dkey) }) self.doc.end_paragraph() return 1 # Duplicate person - + if not self.verbose: self.write_parents(person) @@ -295,7 +295,7 @@ class DetAncestorReport(Report): text = self.__narrator.get_baptised_string() if text: self.doc.write_text_citation(text) - + text = self.__narrator.get_christened_string() if text: self.doc.write_text_citation(text) @@ -326,7 +326,7 @@ class DetAncestorReport(Report): self.doc.end_paragraph() for notehandle in notelist: note = self.db.get_note_from_handle(notehandle) - self.doc.write_styled_note(note.get_styledtext(), + self.doc.write_styled_note(note.get_styledtext(), note.get_format(), "DAR-Entry", contains_html = note.get_type() == NoteType.HTML_CODE @@ -358,7 +358,7 @@ class DetAncestorReport(Report): for event_ref in person.get_primary_event_ref_list(): if event_ref == birth_ref or event_ref == death_ref: continue - + if first: self.doc.start_paragraph('DAR-MoreHeader') self.doc.write_text( @@ -366,9 +366,9 @@ class DetAncestorReport(Report): % {'person_name' : name}) self.doc.end_paragraph() first = 0 - + self.write_event(event_ref) - + if self.inc_addr: for addr in person.get_address_list(): if first: @@ -379,7 +379,7 @@ class DetAncestorReport(Report): self.doc.end_paragraph() first = False self.doc.start_paragraph('DAR-MoreDetails') - + text = ReportUtils.get_address_str(addr) self.doc.write_text(self._('Address: ')) @@ -394,7 +394,7 @@ class DetAncestorReport(Report): self.doc.write_text( text ) self.doc.write_text_citation( self.endnotes(addr) ) self.doc.end_paragraph() - + if self.inc_attrs: attrs = person.get_attribute_list() if first and attrs: @@ -416,7 +416,7 @@ class DetAncestorReport(Report): self.doc.end_paragraph() return 0 # Not duplicate person - + def write_event(self, event_ref): text = "" event = self.db.get_event_from_handle(event_ref.ref) @@ -431,7 +431,7 @@ class DetAncestorReport(Report): self.doc.start_paragraph('DAR-MoreDetails') evtName = self._get_type(event.get_type()) if date and place: - text += self._('%(date)s, %(place)s') % { + text += self._('%(date)s, %(place)s') % { 'date' : date, 'place' : place } elif date: text += self._('%(date)s') % {'date' : date} @@ -442,18 +442,18 @@ class DetAncestorReport(Report): if text: text += ". " text += event.get_description() - + text += self.endnotes(event) - + if text: text += ". " - + text = self._('%(event_name)s: %(event_text)s') % { 'event_name' : self._(evtName), 'event_text' : text } - + self.doc.write_text_citation(text) - + if self.inc_attrs: text = "" attr_list = event.get_attribute_list() @@ -469,7 +469,7 @@ class DetAncestorReport(Report): 'endnotes' : self.endnotes(attr) } text = " " + text self.doc.write_text_citation(text) - + self.doc.end_paragraph() if self.includenotes: @@ -479,13 +479,13 @@ class DetAncestorReport(Report): notelist.extend(event_ref.get_note_list()) for notehandle in notelist: note = self.db.get_note_from_handle(notehandle) - self.doc.write_styled_note(note.get_styledtext(), + self.doc.write_styled_note(note.get_styledtext(), note.get_format(), "DAR-MoreDetails", contains_html = (note.get_type() == NoteType.HTML_CODE) ) - + def write_parents(self, person): family_handle = person.get_main_parents_family_handle() if family_handle: @@ -518,7 +518,7 @@ class DetAncestorReport(Report): self.doc.write_text("", mother_mark) def write_marriage(self, person): - """ + """ Output marriage sentence. """ is_first = True @@ -562,7 +562,7 @@ class DetAncestorReport(Report): self.doc.start_paragraph("DAR-ChildTitle") self.doc.write_text( - self._("Children of %(mother_name)s and %(father_name)s") % + self._("Children of %(mother_name)s and %(father_name)s") % {'father_name': father_name, 'mother_name': mother_name} ) self.doc.end_paragraph() @@ -597,7 +597,7 @@ class DetAncestorReport(Report): self.doc.end_paragraph() def write_family_events(self, family): - + if not family.get_event_ref_list(): return @@ -635,7 +635,7 @@ class DetAncestorReport(Report): """Output birth, death, parentage, marriage and notes information """ ind = None has_info = False - + for family_handle in person.get_family_handle_list(): family = self.db.get_family_from_handle(family_handle) ind_handle = None @@ -654,7 +654,7 @@ class DetAncestorReport(Report): etype == EventType.BIRTH or etype == EventType.DEATH): has_info = True - break + break if not has_info: family_handle = ind.get_main_parents_family_handle() if family_handle: @@ -667,17 +667,17 @@ class DetAncestorReport(Report): self.doc.start_paragraph("DAR-MoreHeader") plist = ind.get_media_list() - + if self.addimages and len(plist) > 0: photo = plist[0] - ReportUtils.insert_image(self.db, self.doc, + ReportUtils.insert_image(self.db, self.doc, photo, self._user) - + name = self._name_display.display(ind) if not name: name = self._("Unknown") mark = ReportUtils.get_person_mark(self.db, ind) - + if family.get_relationship() == FamilyRelType.MARRIED: self.doc.write_text(self._("Spouse: %s") % name, mark) else: @@ -707,7 +707,7 @@ class DetAncestorReport(Report): text = self.__narrator.get_died_string(self.calcageflag) if text: self.doc.write_text_citation(text) - + text = self.__narrator.get_buried_string() if text: self.doc.write_text_citation(text) @@ -719,7 +719,7 @@ class DetAncestorReport(Report): def endnotes(self, obj): if not obj or not self.inc_sources: return "" - + txt = endnotes.cite_source(self.bibli, self.db, obj, self._locale) if txt: txt = '' + txt + '' @@ -738,14 +738,14 @@ class DetAncestorOptions(MenuReportOptions): def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): from functools import partial # Report Options category = _("Report Options") addopt = partial(menu.add_option, category) - + pid = PersonOption(_("Center Person")) pid.set_help(_("The center person for the report")) addopt("pid", pid) @@ -756,13 +756,13 @@ class DetAncestorOptions(MenuReportOptions): addopt("initial_sosa", start_number) stdoptions.add_name_format_option(menu, category) - + stdoptions.add_private_data_option(menu, category) gen = NumberOption(_("Generations"),10,1,100) gen.set_help(_("The number of generations to include in the report")) addopt("gen", gen) - + pagebbg = BooleanOption(_("Page break between generations"),False) pagebbg.set_help( _("Whether to start a new page after each generation.")) @@ -782,24 +782,24 @@ class DetAncestorOptions(MenuReportOptions): usecall = BooleanOption(_("Use callname for common name"),False) usecall.set_help(_("Whether to use the call name as the first name.")) addopt("usecall", usecall) - + fulldates = BooleanOption( _("Use full dates instead of only the year"),True) fulldates.set_help(_("Whether to use full dates instead of just year.")) addopt("fulldates", fulldates) - + listc = BooleanOption(_("List children"),True) listc.set_help(_("Whether to list children.")) addopt("listc", listc) - + computeage = BooleanOption(_("Compute death age"),True) computeage.set_help(_("Whether to compute a person's age at death.")) addopt("computeage", computeage) - + omitda = BooleanOption(_("Omit duplicate ancestors"),True) omitda.set_help(_("Whether to omit duplicate ancestors.")) addopt("omitda", omitda) - + verbose = BooleanOption(_("Use Complete Sentences"),True) verbose.set_help( _("Whether to use complete sentences or succinct language.")) @@ -813,7 +813,7 @@ class DetAncestorOptions(MenuReportOptions): # What to include addopt = partial(menu.add_option, _("Include")) - + incnotes = BooleanOption(_("Include notes"),True) incnotes.set_help(_("Whether to include notes.")) addopt("incnotes", incnotes) @@ -821,7 +821,7 @@ class DetAncestorOptions(MenuReportOptions): incattrs = BooleanOption(_("Include attributes"),False) incattrs.set_help(_("Whether to include attributes.")) addopt("incattrs", incattrs) - + incphotos = BooleanOption(_("Include Photo/Images from Gallery"),False) incphotos.set_help(_("Whether to include images.")) addopt("incphotos", incphotos) diff --git a/gramps/plugins/textreport/detdescendantreport.py b/gramps/plugins/textreport/detdescendantreport.py index 6ffd3fa87..a33f97254 100644 --- a/gramps/plugins/textreport/detdescendantreport.py +++ b/gramps/plugins/textreport/detdescendantreport.py @@ -47,10 +47,10 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gen.errors import ReportError from gramps.gen.lib import FamilyRelType, Person, NoteType -from gramps.gen.plug.menu import (BooleanOption, NumberOption, PersonOption, +from gramps.gen.plug.menu import (BooleanOption, NumberOption, PersonOption, EnumeratedListOption) -from gramps.gen.plug.docgen import (IndexMark, FontStyle, ParagraphStyle, - FONT_SANS_SERIF, FONT_SERIF, +from gramps.gen.plug.docgen import (IndexMark, FontStyle, ParagraphStyle, + FONT_SANS_SERIF, FONT_SERIF, INDEX_TYPE_TOC, PARA_ALIGN_CENTER) from gramps.gen.plug.report import Report, Bibliography from gramps.gen.plug.report import endnotes @@ -78,7 +78,7 @@ class DetDescendantReport(Report): def __init__(self, database, options, user): """ Create the DetDescendantReport object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -87,7 +87,7 @@ class DetDescendantReport(Report): 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. @@ -111,7 +111,7 @@ class DetDescendantReport(Report): 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 + 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 @@ -185,7 +185,7 @@ class DetDescendantReport(Report): stdoptions.run_name_format_option(self, menu) self.__narrator = Narrator(self.db, self.verbose, - use_call, use_fulldate, + use_call, use_fulldate, empty_date, empty_place, nlocale=self._locale, get_endnote_numbers=self.endnotes) @@ -200,7 +200,7 @@ class DetDescendantReport(Report): if len(self.gen_keys) < cur_gen: self.gen_keys.append([index]) - else: + else: self.gen_keys[cur_gen-1].append(index) person = self.db.get_person_from_handle(person_handle) @@ -222,7 +222,7 @@ class DetDescendantReport(Report): if len(self.gen_keys) < cur_gen: self.gen_keys.append([index]) - else: + else: self.gen_keys[cur_gen-1].append(index) person = self.db.get_person_from_handle(person_handle) @@ -240,10 +240,10 @@ class DetDescendantReport(Report): if (not person_handle) or (cur_gen > self.max_generations): return self.map[index] = person_handle - + if len(self.gen_keys) < cur_gen: self.gen_keys.append([index]) - else: + else: self.gen_keys[cur_gen-1].append(index) person = self.db.get_person_from_handle(person_handle) @@ -386,11 +386,11 @@ class DetDescendantReport(Report): if self.inc_paths: self.write_path(person) - + if self.dubperson: # Check for duplicate record (result of distant cousins marrying) for dkey in sorted(self.map): - if dkey >= key: + if dkey >= key: break if self.map[key] == self.map[dkey]: self.doc.write_text(self._( @@ -403,7 +403,7 @@ class DetDescendantReport(Report): return self.doc.end_paragraph() - + self.write_person_info(person) if (self.inc_mates or self.listchildren or self.inc_notes or @@ -436,7 +436,7 @@ class DetDescendantReport(Report): self.doc.start_paragraph('DDR-MoreDetails') event_name = self._get_type(event.get_type()) if date and place: - text += self._('%(date)s, %(place)s') % { + text += self._('%(date)s, %(place)s') % { 'date' : date, 'place' : place } elif date: text += self._('%(date)s') % {'date' : date} @@ -447,18 +447,18 @@ class DetDescendantReport(Report): if text: text += ". " text += event.get_description() - + text += self.endnotes(event) - + if text: text += ". " - + text = self._('%(event_name)s: %(event_text)s') % { 'event_name' : self._(event_name), 'event_text' : text } - + self.doc.write_text_citation(text) - + if self.inc_attrs: text = "" attr_list = event.get_attribute_list() @@ -484,7 +484,7 @@ class DetDescendantReport(Report): notelist.extend(event_ref.get_note_list()) for notehandle in notelist: note = self.db.get_note_from_handle(notehandle) - self.doc.write_styled_note(note.get_styledtext(), + self.doc.write_styled_note(note.get_styledtext(), note.get_format(),"DDR-MoreDetails", contains_html= note.get_type() == NoteType.HTML_CODE) @@ -519,7 +519,7 @@ class DetDescendantReport(Report): self.doc.write_text("", mother_mark) def write_marriage(self, person): - """ + """ Output marriage sentence. """ is_first = True @@ -527,18 +527,18 @@ class DetDescendantReport(Report): family = self.db.get_family_from_handle(family_handle) spouse_handle = ReportUtils.find_spouse(person, family) spouse = self.db.get_person_from_handle(spouse_handle) - + text = "" spouse_mark = ReportUtils.get_person_mark(self.db, spouse) - + text = self.__narrator.get_married_string(family, is_first, self._name_display) - + if text: self.doc.write_text_citation(text, spouse_mark) is_first = False - + def __write_mate(self, person, family): """ Write information about the person's spouse/mate. @@ -547,7 +547,7 @@ class DetDescendantReport(Report): mate_handle = family.get_mother_handle() else: mate_handle = family.get_father_handle() - + if mate_handle: mate = self.db.get_person_from_handle(mate_handle) @@ -604,7 +604,7 @@ class DetDescendantReport(Report): return mother_name, father_name def __write_children(self, family): - """ + """ List the children for the given family. """ if not family.get_child_ref_list(): @@ -614,7 +614,7 @@ class DetDescendantReport(Report): self.doc.start_paragraph("DDR-ChildTitle") self.doc.write_text( - self._("Children of %(mother_name)s and %(father_name)s") % + self._("Children of %(mother_name)s and %(father_name)s") % {'father_name': father_name, 'mother_name': mother_name } ) self.doc.end_paragraph() @@ -666,7 +666,7 @@ class DetDescendantReport(Report): self.doc.end_paragraph() def __write_family_notes(self, family): - """ + """ Write the notes for the given family. """ notelist = family.get_note_list() @@ -675,17 +675,17 @@ class DetDescendantReport(Report): self.doc.start_paragraph("DDR-NoteHeader") self.doc.write_text( - self._('Notes for %(mother_name)s and %(father_name)s:') % { + self._('Notes for %(mother_name)s and %(father_name)s:') % { 'mother_name' : mother_name, 'father_name' : father_name }) self.doc.end_paragraph() for notehandle in notelist: note = self.db.get_note_from_handle(notehandle) - self.doc.write_styled_note(note.get_styledtext(), + self.doc.write_styled_note(note.get_styledtext(), note.get_format(),"DDR-Entry") def __write_family_events(self, family): - """ + """ List the events for the given family. """ if not family.get_event_ref_list(): @@ -707,7 +707,7 @@ class DetDescendantReport(Report): return first def __write_family_attrs(self, family, first): - """ + """ List the attributes for the given family. """ attrs = family.get_attribute_list() @@ -738,7 +738,7 @@ class DetDescendantReport(Report): notelist = attr.get_note_list() for notehandle in notelist: note = self.db.get_note_from_handle(notehandle) - self.doc.write_styled_note(note.get_styledtext(), + self.doc.write_styled_note(note.get_styledtext(), note.get_format(), "DDR-MoreDetails") @@ -748,14 +748,14 @@ class DetDescendantReport(Report): if not name: name = self._("Unknown") self.__narrator.set_subject(person) - + plist = person.get_media_list() if self.addimages and len(plist) > 0: photo = plist[0] ReportUtils.insert_image(self.db, self.doc, photo, self._user) - + self.doc.start_paragraph("DDR-Entry") - + if not self.verbose: self.__write_parents(person) @@ -766,11 +766,11 @@ class DetDescendantReport(Report): text = self.__narrator.get_baptised_string() if text: self.doc.write_text_citation(text) - + text = self.__narrator.get_christened_string() if text: self.doc.write_text_citation(text) - + text = self.__narrator.get_died_string(self.calcageflag) if text: self.doc.write_text_citation(text) @@ -792,7 +792,7 @@ class DetDescendantReport(Report): self.doc.end_paragraph() for notehandle in notelist: note = self.db.get_note_from_handle(notehandle) - self.doc.write_styled_note(note.get_styledtext(), + self.doc.write_styled_note(note.get_styledtext(), note.get_format(),"DDR-Entry", contains_html= note.get_type() == NoteType.HTML_CODE) @@ -826,7 +826,7 @@ class DetDescendantReport(Report): first = 0 self.write_event(event_ref) - + if self.inc_addr: for addr in person.get_address_list(): if first: @@ -836,7 +836,7 @@ class DetDescendantReport(Report): self.doc.end_paragraph() first = False self.doc.start_paragraph('DDR-MoreDetails') - + text = ReportUtils.get_address_str(addr) if self.fulldate: @@ -851,12 +851,12 @@ class DetDescendantReport(Report): self.doc.write_text( text ) self.doc.write_text_citation( self.endnotes(addr) ) self.doc.end_paragraph() - + if self.inc_attrs: attrs = person.get_attribute_list() if first and attrs: self.doc.start_paragraph('DDR-MoreHeader') - self.doc.write_text(self._('More about %(person_name)s:') % { + self.doc.write_text(self._('More about %(person_name)s:') % { 'person_name' : name }) self.doc.end_paragraph() first = False @@ -874,7 +874,7 @@ class DetDescendantReport(Report): def endnotes(self, obj): if not obj or not self.inc_sources: return "" - + txt = endnotes.cite_source(self.bibli, self.db, obj, self._locale) if txt: txt = '' + txt + '' @@ -893,7 +893,7 @@ class DetDescendantOptions(MenuReportOptions): def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the detailed descendant report. @@ -902,30 +902,30 @@ class DetDescendantOptions(MenuReportOptions): # Report Options category = _("Report Options") add_option = partial(menu.add_option, category) - + pid = PersonOption(_("Center Person")) pid.set_help(_("The center person for the report")) add_option("pid", pid) - + stdoptions.add_name_format_option(menu, category) stdoptions.add_private_data_option(menu, category) numbering = EnumeratedListOption(_("Numbering system"), "Henry") numbering.set_items([ - ("Henry", _("Henry numbering")), - ("d'Aboville", _("d'Aboville numbering")), - ("Record (Modified Register)", + ("Henry", _("Henry numbering")), + ("d'Aboville", _("d'Aboville numbering")), + ("Record (Modified Register)", _("Record (Modified Register) numbering"))]) numbering.set_help(_("The numbering system to be used")) add_option("numbering", numbering) - + generations = NumberOption(_("Generations"), 10, 1, 100) generations.set_help( _("The number of generations to include in the report") ) add_option("gen", generations) - + pagebbg = BooleanOption(_("Page break between generations"), False) pagebbg.set_help( _("Whether to start a new page after each generation.")) @@ -939,30 +939,30 @@ class DetDescendantOptions(MenuReportOptions): stdoptions.add_localization_option(menu, category) # Content - + add_option = partial(menu.add_option, _("Content")) usecall = BooleanOption(_("Use callname for common name"), False) usecall.set_help(_("Whether to use the call name as the first name.")) add_option("usecall", usecall) - + fulldates = BooleanOption(_("Use full dates instead of only the year"), True) fulldates.set_help(_("Whether to use full dates instead of just year.")) add_option("fulldates", fulldates) - + listc = BooleanOption(_("List children"), True) listc.set_help(_("Whether to list children.")) add_option("listc", listc) - + computeage = BooleanOption(_("Compute death age"),True) computeage.set_help(_("Whether to compute a person's age at death.")) add_option("computeage", computeage) - + omitda = BooleanOption(_("Omit duplicate ancestors"), True) omitda.set_help(_("Whether to omit duplicate ancestors.")) add_option("omitda", omitda) - + verbose = BooleanOption(_("Use complete sentences"), True) verbose.set_help( _("Whether to use complete sentences or succinct language.")) @@ -976,7 +976,7 @@ class DetDescendantOptions(MenuReportOptions): category_name = _("Include") add_option = partial(menu.add_option, _("Include")) - + incnotes = BooleanOption(_("Include notes"), True) incnotes.set_help(_("Whether to include notes.")) add_option("incnotes", incnotes) @@ -984,7 +984,7 @@ class DetDescendantOptions(MenuReportOptions): incattrs = BooleanOption(_("Include attributes"), False) incattrs.set_help(_("Whether to include attributes.")) add_option("incattrs", incattrs) - + incphotos = BooleanOption(_("Include Photo/Images from Gallery"), False) incphotos.set_help(_("Whether to include images.")) add_option("incphotos", incphotos) @@ -1004,7 +1004,7 @@ class DetDescendantOptions(MenuReportOptions): incsources = BooleanOption(_("Include sources"), False) incsources.set_help(_("Whether to include source references.")) add_option("incsources", incsources) - + incsrcnotes = BooleanOption(_("Include sources notes"), False) incsrcnotes.set_help(_("Whether to include source notes in the " "Endnotes section. Only works if Include sources is selected.")) @@ -1031,8 +1031,8 @@ class DetDescendantOptions(MenuReportOptions): add_option("incpaths", incpaths) # Missing information - - add_option = partial(menu.add_option, _("Missing information")) + + add_option = partial(menu.add_option, _("Missing information")) repplace = BooleanOption(_("Replace missing places with ______"), False) repplace.set_help(_("Whether to replace missing Places with blanks.")) @@ -1104,7 +1104,7 @@ class DetDescendantOptions(MenuReportOptions): para = ParagraphStyle() para.set(first_indent=-1.5, lmargin=1.5) para.set_top_margin(0.25) - para.set_bottom_margin(0.25) + para.set_bottom_margin(0.25) para.set_description(_('The style used for the first personal entry.')) default_style.add_paragraph_style("DDR-First-Entry", para) diff --git a/gramps/plugins/textreport/endoflinereport.py b/gramps/plugins/textreport/endoflinereport.py index 1e601a145..c9f36a6ac 100644 --- a/gramps/plugins/textreport/endoflinereport.py +++ b/gramps/plugins/textreport/endoflinereport.py @@ -57,7 +57,7 @@ class EndOfLineReport(Report): def __init__(self, database, options, user): """ Create the EndOfLineReport object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -90,18 +90,18 @@ class EndOfLineReport(Report): # values are a map whose: # keys are person handles # values are an array whose: - # elements are an array of ancestor person handles that link + # elements are an array of ancestor person handles that link # the eol person handle to the person or interest # eol_map[generation][person_handle][pedigree_idx][ancestor_handle_idx] # - # There is an array of pedigrees because one person could show up twice + # There is an array of pedigrees because one person could show up twice # in one generation (descendants marrying). Most people only have one # pedigree. # # eol_map is populated by get_eol() which calls itself recursively. self.eol_map = {} self.get_eol(self.center_person, 1, []) - + def get_eol(self, person, gen, pedigree): """ Recursively find the end of the line for each person @@ -110,7 +110,7 @@ class EndOfLineReport(Report): new_pedigree = list(pedigree) + [person_handle] person_is_eol = False families = person.get_parent_family_handle_list() - + if person_handle in pedigree: # This is a severe error! # It indicates a loop in ancestry: A -> B -> A @@ -122,16 +122,16 @@ class EndOfLineReport(Report): family = self.database.get_family_from_handle(family_handle) father_handle = family.get_father_handle() mother_handle = family.get_mother_handle() - if father_handle: + if father_handle: father = self.database.get_person_from_handle(father_handle) self.get_eol(father, gen+1, new_pedigree) if mother_handle: mother = self.database.get_person_from_handle(mother_handle) self.get_eol(mother, gen+1, new_pedigree) - + if not father_handle or not mother_handle: person_is_eol = True - + if person_is_eol: # This person is the end of a line if gen not in self.eol_map: @@ -146,21 +146,21 @@ class EndOfLineReport(Report): At this point, the document is opened and ready for writing. """ pname = self._name_display.display(self.center_person) - + self.doc.start_paragraph("EOL-Title") # feature request 2356: avoid genitive form title = self._("End of Line Report for %s") % pname mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.write_text(title, mark) self.doc.end_paragraph() - + self.doc.start_paragraph("EOL-Subtitle") # feature request 2356: avoid genitive form title = self._("All the ancestors of %s " "who are missing a parent") % pname self.doc.write_text(title) self.doc.end_paragraph() - + self.doc.start_table('EolTable','EOL-Table') for generation, handles in self.eol_map.items(): self.write_generation_row(generation) @@ -180,7 +180,7 @@ class EndOfLineReport(Report): self.doc.end_paragraph() self.doc.end_cell() self.doc.end_row() - + def write_person_row(self, person_handle): """ Write a row in the table with information about the given person. @@ -194,16 +194,16 @@ class EndOfLineReport(Report): if birth_ref: event = self.database.get_event_from_handle(birth_ref.ref) birth_date = self._get_date(event.get_date_object()) - + death_date = "" death_ref = person.get_death_ref() if death_ref: event = self.database.get_event_from_handle(death_ref.ref) death_date = self._get_date(event.get_date_object()) - dates = self._(" (%(birth_date)s - %(death_date)s)") % { + dates = self._(" (%(birth_date)s - %(death_date)s)") % { 'birth_date' : birth_date, 'death_date' : death_date } - + self.doc.start_row() self.doc.start_cell('EOL-TableCell', 2) self.doc.start_paragraph('EOL-Normal') @@ -212,11 +212,11 @@ class EndOfLineReport(Report): self.doc.end_paragraph() self.doc.end_cell() self.doc.end_row() - + def write_pedigree_row(self, pedigree): """ Write a row in the table with with the person's family line. - + pedigree is an array containing the names of the people in the pedigree """ names = [] @@ -246,13 +246,13 @@ class EndOfLineOptions(MenuReportOptions): def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the End of Line report. """ category_name = _("Report Options") - + pid = PersonOption(_("Center Person")) pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", pid) @@ -278,7 +278,7 @@ class EndOfLineOptions(MenuReportOptions): p.set_alignment(PARA_ALIGN_CENTER) p.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("EOL-Title", p) - + font = FontStyle() font.set(face=FONT_SANS_SERIF, size=12, italic=1) p = ParagraphStyle() @@ -287,7 +287,7 @@ class EndOfLineOptions(MenuReportOptions): p.set_alignment(PARA_ALIGN_CENTER) p.set_description(_('The style used for the section headers.')) default_style.add_paragraph_style("EOL-Subtitle", p) - + font = FontStyle() font.set_size(10) p = ParagraphStyle() @@ -296,7 +296,7 @@ class EndOfLineOptions(MenuReportOptions): p.set_bottom_margin(ReportUtils.pt2cm(6)) p.set_description(_('The basic style used for the text display.')) default_style.add_paragraph_style("EOL-Normal", p) - + font = FontStyle() font.set_size(12) font.set_italic(True) @@ -305,7 +305,7 @@ class EndOfLineOptions(MenuReportOptions): p.set_top_margin(ReportUtils.pt2cm(6)) p.set_description(_('The basic style used for generation headings.')) default_style.add_paragraph_style("EOL-Generation", p) - + font = FontStyle() font.set_size(8) p = ParagraphStyle() @@ -314,11 +314,11 @@ class EndOfLineOptions(MenuReportOptions): p.set_bottom_margin(ReportUtils.pt2cm(6)) p.set_description(_('The basic style used for the text display.')) default_style.add_paragraph_style("EOL-Pedigree", p) - + #Table Styles cell = TableCellStyle() default_style.add_cell_style('EOL-TableCell', cell) - + cell = TableCellStyle() cell.set_bottom_border(1) default_style.add_cell_style('EOL_GenerationCell', cell) diff --git a/gramps/plugins/textreport/familygroup.py b/gramps/plugins/textreport/familygroup.py index d26446c17..0ef5c8633 100644 --- a/gramps/plugins/textreport/familygroup.py +++ b/gramps/plugins/textreport/familygroup.py @@ -33,7 +33,7 @@ from functools import partial #------------------------------------------------------------------------ # -# GRAMPS +# GRAMPS # #------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale @@ -46,7 +46,7 @@ from gramps.gen.plug.report import MenuReportOptions from gramps.gen.plug.report import stdoptions from gramps.gen.plug.docgen import (IndexMark, FontStyle, ParagraphStyle, TableStyle, TableCellStyle, - FONT_SANS_SERIF, FONT_SERIF, + FONT_SANS_SERIF, FONT_SERIF, INDEX_TYPE_TOC, PARA_ALIGN_CENTER) from gramps.gen.display.place import displayer as place_displayer @@ -60,7 +60,7 @@ class FamilyGroup(Report): def __init__(self, database, options, user): """ Create the FamilyGroup object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -69,7 +69,7 @@ class FamilyGroup(Report): This report needs the following parameters (class variables) that come in the options class. - + family_handle - Handle of the family to write report on. includeAttrs - Whether to include attributes name_format - Preferred format to display names @@ -90,7 +90,7 @@ class FamilyGroup(Report): self.family_handle = None get_option_by_name = menu.get_option_by_name - get_value = lambda name:get_option_by_name(name).get_value() + get_value = lambda name:get_option_by_name(name).get_value() self.gramps_ids = get_value('gramps_ids') self.recursive = get_value('recursive') self.missingInfo = get_value('missinginfo') @@ -119,7 +119,7 @@ class FamilyGroup(Report): if place is None: place = '' descr = event.get_description() - + if self.includeAttrs: for attr in event.get_attribute_list(): if descr: @@ -137,7 +137,7 @@ class FamilyGroup(Report): self.doc.write_text(name) self.doc.end_paragraph() self.doc.end_cell() - + if descr: self.doc.start_cell("FGR-TextContentsEnd",2) self.doc.start_paragraph('FGR-Normal') @@ -145,14 +145,14 @@ class FamilyGroup(Report): self.doc.end_paragraph() self.doc.end_cell() self.doc.end_row() - + if date or place: self.doc.start_row() self.doc.start_cell("FGR-TextContents") self.doc.start_paragraph('FGR-Normal') self.doc.end_paragraph() self.doc.end_cell() - + if (date or place) or not descr: self.doc.start_cell("FGR-TextContents") self.doc.start_paragraph('FGR-Normal') @@ -165,14 +165,14 @@ class FamilyGroup(Report): self.doc.end_paragraph() self.doc.end_cell() self.doc.end_row() - + def dump_parent_parents(self,person): family_handle = person.get_main_parents_family_handle() father_name = "" mother_name = "" if family_handle: family = self.database.get_family_from_handle(family_handle) - father_handle = family.get_father_handle() + father_handle = family.get_father_handle() if father_handle: father = self.database.get_person_from_handle(father_handle) father_name = self._name_display.display(father) @@ -193,7 +193,7 @@ class FamilyGroup(Report): death = self._get_date(event.get_date_object()) if birth_ref or death_ref: father_name += " (%s - %s)" % (birth, death) - mother_handle = family.get_mother_handle() + mother_handle = family.get_mother_handle() if mother_handle: mother = self.database.get_person_from_handle(mother_handle) mother_name = self._name_display.display(mother) @@ -214,7 +214,7 @@ class FamilyGroup(Report): death = self._get_date(event.get_date_object()) if birth_ref or death_ref: mother_name += " (%s - %s)" % (birth, death) - + if father_name != "": self.doc.start_row() self.doc.start_cell("FGR-TextContents") @@ -278,7 +278,7 @@ class FamilyGroup(Report): ) self.doc.end_cell() self.doc.end_row() - + def dump_parent(self,title,person_handle): if not person_handle and not self.missingInfo: @@ -288,7 +288,7 @@ class FamilyGroup(Report): else: person = self.database.get_person_from_handle(person_handle) name = self._name_display.display(person) - + self.doc.start_table(title,'FGR-ParentTable') self.doc.start_row() self.doc.start_cell('FGR-ParentHead',3) @@ -336,7 +336,7 @@ class FamilyGroup(Report): for addr in addrlist: location = ReportUtils.get_address_str(addr) date = self._get_date(addr.get_date_object()) - + self.doc.start_row() self.doc.start_cell("FGR-TextContents") self.doc.start_paragraph('FGR-Normal') @@ -359,7 +359,7 @@ class FamilyGroup(Report): for notehandle in person.get_note_list(): note = self.database.get_note_from_handle(notehandle) self.dump_parent_noteline(self._("Note"), note) - + if self.includeAttrs: for attr in person.get_attribute_list(): attr_type = self._get_type(attr.get_type()) @@ -384,7 +384,7 @@ class FamilyGroup(Report): if event_ref: event = self.database.get_event_from_handle(event_ref.ref) if event.get_type() == EventType.MARRIAGE and \ - (event_ref.get_role() == EventRoleType.FAMILY or + (event_ref.get_role() == EventRoleType.FAMILY or event_ref.get_role() == EventRoleType.PRIMARY): m = event break @@ -404,14 +404,14 @@ class FamilyGroup(Report): self.doc.end_row() self.dump_parent_event(self._("Marriage"),m) - + for event_ref in family_list: if event_ref: event = self.database.get_event_from_handle(event_ref.ref) if event.get_type() != EventType.MARRIAGE: event_type = self._get_type(event.get_type()) self.dump_parent_event(self._(event_type),event) - + if self.includeAttrs: for attr in family.get_attribute_list(): attr_type = self._get_type(attr.get_type()) @@ -451,7 +451,7 @@ class FamilyGroup(Report): self.doc.end_paragraph() self.doc.end_cell() self.doc.end_row() - + def dump_child(self,index,person_handle): person = self.database.get_person_from_handle(person_handle) @@ -466,9 +466,9 @@ class FamilyGroup(Report): death = self.database.get_event_from_handle(death_ref.ref) else: death = None - - spouse_count = 0; - if self.incChiMar: + + spouse_count = 0; + if self.incChiMar: for family_handle in person.get_family_handle_list(): family = self.database.get_family_from_handle(family_handle) spouse_id = None @@ -494,7 +494,7 @@ class FamilyGroup(Report): self.doc.write_text(self._("acronym for unknown|%dU") % index) self.doc.end_paragraph() self.doc.end_cell() - + name = self._name_display.display(person) mark = ReportUtils.get_person_mark(self.database,person) self.doc.start_cell('FGR-ChildName',3) @@ -511,7 +511,7 @@ class FamilyGroup(Report): self.dump_child_event('FGR-TextChild1',self._('Birth'),birth) else: self.dump_child_event('FGR-TextChild2',self._('Birth'),birth) - + if self.missingInfo or death is not None: if spouse_count == 0 or not self.incChiMar: self.dump_child_event('FGR-TextChild2',self._('Death'),death) @@ -530,15 +530,15 @@ class FamilyGroup(Report): event = self.database.get_event_from_handle(event_ref.ref) if event.type == EventType.MARRIAGE: m = event - break - + break + spouse_id = None if person_handle == family.get_father_handle(): spouse_id = family.get_mother_handle() else: spouse_id = family.get_father_handle() - + if spouse_id: self.doc.start_row() if m or index != families: @@ -584,14 +584,14 @@ class FamilyGroup(Report): self.doc.end_paragraph() self.doc.end_cell() self.doc.end_row() - + if m: evtName = self._("Marriage") if index == families: self.dump_child_event('FGR-TextChild2',evtName,m) else: self.dump_child_event('FGR-TextChild1',evtName,m) - + def dump_family(self,family_handle,generation): self.doc.start_paragraph('FGR-Title') if self.recursive and self.generations: @@ -607,7 +607,7 @@ class FamilyGroup(Report): self.dump_parent(self._("Husband"),family.get_father_handle()) self.doc.start_paragraph("FGR-blank") self.doc.end_paragraph() - + if self.incParMar: self.dump_marriage(family) self.doc.start_paragraph("FGR-blank") @@ -662,83 +662,83 @@ class FamilyGroupOptions(MenuReportOptions): def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): - + ########################## category_name = _("Report Options") add_option = partial(menu.add_option, category_name) ########################## - + family_id = FamilyOption(_("Center Family")) family_id.set_help(_("The center family for the report")) add_option("family_id", family_id) stdoptions.add_name_format_option(menu, category_name) - + stdoptions.add_private_data_option(menu, category_name) recursive = BooleanOption(_('Recursive'),False) recursive.set_help(_("Create reports for all descendants " "of this family.")) add_option("recursive", recursive) - + stdoptions.add_localization_option(menu, category_name) ########################## add_option = partial(menu.add_option, _("Include")) ########################## - + gramps_ids = BooleanOption(_('Gramps ID'), False) gramps_ids.set_help(_("Whether to include Gramps ID next to names.")) add_option("gramps_ids", gramps_ids) - + generations = BooleanOption(_("Generation numbers " "(recursive only)"),True) generations.set_help(_("Whether to include the generation on each " "report (recursive only).")) add_option("generations", generations) - + incParEvents = BooleanOption(_("Parent Events"),False) incParEvents.set_help(_("Whether to include events for parents.")) add_option("incParEvents", incParEvents) - + incParAddr = BooleanOption(_("Parent Addresses"),False) incParAddr.set_help(_("Whether to include addresses for parents.")) add_option("incParAddr", incParAddr) - + incParNotes = BooleanOption(_("Parent Notes"),False) incParNotes.set_help(_("Whether to include notes for parents.")) add_option("incParNotes", incParNotes) - + incattrs = BooleanOption(_("Parent Attributes"),False) incattrs.set_help(_("Whether to include attributes.")) add_option("incattrs", incattrs) - + incParNames = BooleanOption(_("Alternate Parent Names"),False) incParNames.set_help(_("Whether to include alternate " "names for parents.")) add_option("incParNames", incParNames) - + incParMar = BooleanOption(_("Parent Marriage"),False) incParMar.set_help(_("Whether to include marriage information " "for parents.")) add_option("incParMar", incParMar) - + incRelDates = BooleanOption(_("Dates of Relatives"),False) incRelDates.set_help(_("Whether to include dates for relatives " "(father, mother, spouse).")) add_option("incRelDates", incRelDates) - + incChiMar = BooleanOption(_("Children Marriages"),True) incChiMar.set_help(_("Whether to include marriage information " "for children.")) add_option("incChiMar", incChiMar) - + ########################## add_option = partial(menu.add_option, _("Missing Information")) ########################## - + missinginfo = BooleanOption(_("Print fields for missing " "information"),True) missinginfo.set_help(_("Whether to include fields for missing " @@ -804,7 +804,7 @@ class FamilyGroupOptions(MenuReportOptions): para.set_header_level(3) para.set_description(_("The style used for the parent's name")) default_style.add_paragraph_style('FGR-ParentName',para) - + #Table Styles cell = TableCellStyle() cell.set_padding(0.2) diff --git a/gramps/plugins/textreport/indivcomplete.py b/gramps/plugins/textreport/indivcomplete.py index b8677ef38..c3aee6018 100644 --- a/gramps/plugins/textreport/indivcomplete.py +++ b/gramps/plugins/textreport/indivcomplete.py @@ -90,7 +90,7 @@ 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 @@ -99,7 +99,7 @@ class IndivCompleteReport(Report): 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. @@ -121,7 +121,7 @@ class IndivCompleteReport(Report): 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() @@ -144,7 +144,7 @@ class IndivCompleteReport(Report): """ role = event_ref.get_role() description = event.get_description() - + date = self._get_date(event.get_date_object()) place_name = '' place_endnote = '' @@ -189,7 +189,7 @@ class IndivCompleteReport(Report): self.doc.write_text(endnotes) self.doc.end_superscript() self.doc.end_paragraph() - + attr_list = event.get_attribute_list() if len(attr_list): for attr in attr_list: @@ -217,7 +217,7 @@ class IndivCompleteReport(Report): 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() @@ -254,7 +254,7 @@ class IndivCompleteReport(Report): 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() @@ -267,7 +267,7 @@ class IndivCompleteReport(Report): 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) @@ -275,14 +275,14 @@ class IndivCompleteReport(Report): 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 = "" @@ -292,7 +292,7 @@ class IndivCompleteReport(Report): 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) @@ -310,7 +310,7 @@ class IndivCompleteReport(Report): 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() @@ -327,7 +327,7 @@ class IndivCompleteReport(Report): 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) @@ -335,7 +335,7 @@ class IndivCompleteReport(Report): 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() @@ -347,21 +347,21 @@ class IndivCompleteReport(Report): 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()) @@ -373,12 +373,12 @@ class IndivCompleteReport(Report): 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) @@ -397,21 +397,21 @@ class IndivCompleteReport(Report): 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 = self._get_type(attr.get_type()) self.doc.start_row() @@ -423,14 +423,14 @@ class IndivCompleteReport(Report): 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) @@ -438,7 +438,7 @@ class IndivCompleteReport(Report): 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') @@ -447,7 +447,7 @@ class IndivCompleteReport(Report): 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()) @@ -471,14 +471,14 @@ class IndivCompleteReport(Report): 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) @@ -495,13 +495,13 @@ class IndivCompleteReport(Report): 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 (len(media_list) < 2): # only show if > one return - + self.doc.start_table("images","IDS-GalleryTable") cells = 3 # the GalleryTable has 3 cells self.doc.start_row() @@ -538,13 +538,13 @@ class IndivCompleteReport(Report): 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) @@ -553,7 +553,7 @@ class IndivCompleteReport(Report): 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) @@ -577,7 +577,7 @@ class IndivCompleteReport(Report): 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) @@ -706,7 +706,7 @@ class IndivCompleteReport(Report): 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: @@ -743,7 +743,7 @@ class IndivCompleteReport(Report): 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 @@ -775,7 +775,7 @@ class IndivCompleteReport(Report): 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_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: @@ -877,7 +877,7 @@ class IndivCompleteReport(Report): 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 = "" @@ -894,7 +894,7 @@ class IndivCompleteReport(Report): return "" if not obj: return prior - + txt = Endnotes.cite_source(self.bibli, self._db, obj, self._locale) if not txt: return prior @@ -917,12 +917,12 @@ class IndivCompleteOptions(MenuReportOptions): self.__pid = None self.__filter = None MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): ################################ category_name = _("Report Options") ################################ - + self.__filter = FilterOption(_("Filter"), 0) self.__filter.set_help( _("Select the filter to be applied to the report.")) @@ -996,7 +996,7 @@ class IndivCompleteOptions(MenuReportOptions): include_single=True, name_format=nfv) self.__filter.set_filters(filter_list) - + def __filter_changed(self): """ Handle filter change. If the filter is not specific to a person, @@ -1024,7 +1024,7 @@ class IndivCompleteOptions(MenuReportOptions): para.set_font(font) para.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("IDS-Title", para) - + font = FontStyle() font.set_bold(1) font.set_type_face(FONT_SANS_SERIF) @@ -1056,7 +1056,7 @@ class IndivCompleteOptions(MenuReportOptions): para.set_bottom_margin(ReportUtils.pt2cm(3)) para.set_description(_('The basic style used for the text display.')) default_style.add_paragraph_style("IDS-Normal", para) - + font = FontStyle() font.set_size(12) font.set_italic(1) @@ -1066,7 +1066,7 @@ class IndivCompleteOptions(MenuReportOptions): para.set_bottom_margin(ReportUtils.pt2cm(3)) para.set_description(_('The style used for the section headers.')) default_style.add_paragraph_style("IDS-Section", para) - + font = FontStyle() font.set_size(8) para = ParagraphStyle() @@ -1076,7 +1076,7 @@ class IndivCompleteOptions(MenuReportOptions): para.set_bottom_margin(ReportUtils.pt2cm(3)) para.set_description(_('A style used for image facts.')) default_style.add_paragraph_style("IDS-ImageNote", para) - + font = FontStyle() font.set_size(8) para = ParagraphStyle() @@ -1086,7 +1086,7 @@ class IndivCompleteOptions(MenuReportOptions): para.set_bottom_margin(ReportUtils.pt2cm(3)) para.set_description(_('A style used for image captions.')) default_style.add_paragraph_style("IDS-ImageCaptionCenter", para) - + # Table Styles tbl = TableStyle() tbl.set_width(100) @@ -1113,7 +1113,7 @@ class IndivCompleteOptions(MenuReportOptions): cell = TableCellStyle() cell.set_longlist(1) default_style.add_cell_style("IDS-ListCell", cell) - + tbl = TableStyle() tbl.set_width(100) tbl.set_columns(3) diff --git a/gramps/plugins/textreport/kinshipreport.py b/gramps/plugins/textreport/kinshipreport.py index bdf31a0f5..ee64ea608 100644 --- a/gramps/plugins/textreport/kinshipreport.py +++ b/gramps/plugins/textreport/kinshipreport.py @@ -3,7 +3,7 @@ # # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2009 Gary Burton -# Contribution 2009 by Reinhard Mueller +# Contribution 2009 by Reinhard Mueller # Copyright (C) 2010 Jakim Friant # Copyright (C) 2013-2014 Paul Franklin # @@ -59,7 +59,7 @@ class KinshipReport(Report): def __init__(self, database, options, user): """ Create the KinshipReport object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -68,7 +68,7 @@ class KinshipReport(Report): This report needs the following parameters (class variables) that come in the options class. - + maxdescend - Maximum generations of descendants to include. maxascend - Maximum generations of ancestors to include. incspouses - Whether to include spouses. @@ -110,7 +110,7 @@ class KinshipReport(Report): is opened and ready for writing. """ pname = self._name_display.display(self.person) - + self.doc.start_paragraph("KIN-Title") # feature request 2356: avoid genitive form title = self._("Kinship Report for %s") % pname @@ -125,14 +125,14 @@ class KinshipReport(Report): # Collect all descendants of the person self.traverse_down(self.person.get_handle(), 0, 1) - + # Collect all ancestors/aunts/uncles/nephews/cousins of the person self.traverse_up(self.person.get_handle(), 1, 0) - + # Write Kin for Ga, Gbs in self.kinship_map.items(): for Gb in Gbs: - # To understand these calculations, see: + # To understand these calculations, see: # http://en.wikipedia.org/wiki/Cousin#Mathematical_definitions x = min (Ga, Gb) y = abs(Ga-Gb) @@ -141,12 +141,12 @@ class KinshipReport(Report): continue elif x > 1 and not self.inc_cousins: continue - + get_rel_str = self.rel_calc.get_plural_relationship_string - + title = get_rel_str(Ga, Gb, in_law_b=False) self.write_people(self._(title), self.kinship_map[Ga][Gb]) - + if (self.inc_spouses and Ga in self.spouse_map and Gb in self.spouse_map[Ga]): @@ -158,14 +158,14 @@ class KinshipReport(Report): Populate a map of arrays containing person handles for the descendants of the passed person. This function calls itself recursively until it reaches max_descend. - + Parameters: person_handle: the handle of the person to go to next - Ga: The number of generations from the main person to the common - ancestor. This should be incremented when going up generations, and + Ga: The number of generations from the main person to the common + ancestor. This should be incremented when going up generations, and left alone when going down generations. - Gb: The number of generations from this person (person_handle) to the - common ancestor. This should be incremented when going down + Gb: The number of generations from this person (person_handle) to the + common ancestor. This should be incremented when going down generations and set back to zero when going up generations. skip_handle: an optional handle to skip when going down. This is useful to skip the descendant that brought you this generation in the first @@ -174,27 +174,27 @@ class KinshipReport(Report): for child_handle in self.get_children_handles(person_handle): if child_handle != skip_handle: self.add_kin(child_handle, Ga, Gb) - + if self.inc_spouses: for spouse_handle in self.get_spouse_handles(child_handle): self.add_spouse(spouse_handle, Ga, Gb) - + if Gb < self.max_descend: self.traverse_down(child_handle, Ga, Gb+1) - + def traverse_up(self, person_handle, Ga, Gb): """ Populate a map of arrays containing person handles for the ancestors of the passed person. This function calls itself recursively until it reaches max_ascend. - + Parameters: person_handle: the handle of the person to go to next - Ga: The number of generations from the main person to the common - ancestor. This should be incremented when going up generations, and + Ga: The number of generations from the main person to the common + ancestor. This should be incremented when going up generations, and left alone when going down generations. - Gb: The number of generations from this person (person_handle) to the - common ancestor. This should be incremented when going down + Gb: The number of generations from this person (person_handle) to the + common ancestor. This should be incremented when going down generations and set back to zero when going up generations. """ parent_handles = self.get_parent_handles(person_handle) @@ -203,7 +203,7 @@ class KinshipReport(Report): self.traverse_down(parent_handle, Ga, Gb+1, person_handle) if Ga < self.max_ascend: self.traverse_up(parent_handle, Ga+1, 0) - + def add_kin(self, person_handle, Ga, Gb): """ Add a person handle to the kin map. @@ -214,7 +214,7 @@ class KinshipReport(Report): self.kinship_map[Ga][Gb] = [] if person_handle not in self.kinship_map[Ga][Gb]: self.kinship_map[Ga][Gb].append(person_handle) - + def add_spouse(self, spouse_handle, Ga, Gb): """ Add a person handle to the spouse map. @@ -225,10 +225,10 @@ class KinshipReport(Report): self.spouse_map[Ga][Gb] = [] if spouse_handle not in self.spouse_map[Ga][Gb]: self.spouse_map[Ga][Gb].append(spouse_handle) - + def get_parent_handles(self, person_handle): """ - Return an array of handles for all the parents of the + Return an array of handles for all the parents of the given person handle. """ parent_handles = [] @@ -243,10 +243,10 @@ class KinshipReport(Report): if mother_handle: parent_handles.append(mother_handle) return parent_handles - + def get_spouse_handles(self, person_handle): """ - Return an array of handles for all the spouses of the + Return an array of handles for all the spouses of the given person handle. """ spouses = [] @@ -260,14 +260,14 @@ class KinshipReport(Report): spouse_handle = mother_handle elif father_handle and mother_handle == person_handle: spouse_handle = father_handle - + if spouse_handle and spouse_handle not in spouses: spouses.append(spouse_handle) return spouses - + def get_children_handles(self, person_handle): """ - Return an array of handles for all the children of the + Return an array of handles for all the children of the given person handle. """ children = [] @@ -277,7 +277,7 @@ class KinshipReport(Report): for child_ref in family.get_child_ref_list(): children.append(child_ref.get_reference_handle()) return children - + def write_people(self, title, people_handles): """ Write information about a group of people - including the title. @@ -302,15 +302,15 @@ class KinshipReport(Report): birth = get_birth_or_fallback(self.database, person) if birth: birth_date = self._get_date(birth.get_date_object()) - + death_date = "" death = get_death_or_fallback(self.database, person) if death: death_date = self._get_date(death.get_date_object()) - dates = self._(" (%(birth_date)s - %(death_date)s)") % { + dates = self._(" (%(birth_date)s - %(death_date)s)") % { 'birth_date' : birth_date, 'death_date' : death_date } - + self.doc.start_paragraph('KIN-Normal') self.doc.write_text(name, mark) self.doc.write_text(dates) @@ -329,13 +329,13 @@ class KinshipOptions(MenuReportOptions): def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the kinship report. """ category_name = _("Report Options") - + pid = PersonOption(_("Center Person")) pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", pid) @@ -347,22 +347,22 @@ class KinshipOptions(MenuReportOptions): maxdescend = NumberOption(_("Max Descendant Generations"), 2, 1, 20) maxdescend.set_help(_("The maximum number of descendant generations")) menu.add_option(category_name, "maxdescend", maxdescend) - + maxascend = NumberOption(_("Max Ancestor Generations"), 2, 1, 20) maxascend.set_help(_("The maximum number of ancestor generations")) menu.add_option(category_name, "maxascend", maxascend) - + incspouses = BooleanOption(_("Include spouses"), True) incspouses.set_help(_("Whether to include spouses")) menu.add_option(category_name, "incspouses", incspouses) - + inccousins = BooleanOption(_("Include cousins"), True) inccousins.set_help(_("Whether to include cousins")) menu.add_option(category_name, "inccousins", inccousins) - + incaunts = BooleanOption(_("Include aunts/uncles/nephews/nieces"), True) incaunts.set_help(_("Whether to include aunts/uncles/nephews/nieces")) - menu.add_option(category_name, "incaunts", incaunts) + menu.add_option(category_name, "incaunts", incaunts) stdoptions.add_localization_option(menu, category_name) @@ -380,7 +380,7 @@ class KinshipOptions(MenuReportOptions): p.set_alignment(PARA_ALIGN_CENTER) p.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("KIN-Title", p) - + font = FontStyle() font.set_size(12) font.set_bold(True) @@ -390,7 +390,7 @@ class KinshipOptions(MenuReportOptions): p.set_top_margin(ReportUtils.pt2cm(6)) p.set_description(_('The basic style used for sub-headings.')) default_style.add_paragraph_style("KIN-Subtitle", p) - + font = FontStyle() font.set_size(10) p = ParagraphStyle() diff --git a/gramps/plugins/textreport/notelinkreport.py b/gramps/plugins/textreport/notelinkreport.py index e7980142d..8aac09636 100644 --- a/gramps/plugins/textreport/notelinkreport.py +++ b/gramps/plugins/textreport/notelinkreport.py @@ -53,7 +53,7 @@ from gramps.gen.simple import SimpleAccess #------------------------------------------------------------------------ class NoteLinkReport(Report): """ - This report + This report """ def write_report(self): @@ -83,7 +83,7 @@ class NoteLinkReport(Report): self.doc.write_text(_("Link Type")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('NoteLink-TableCell') self.doc.start_paragraph('NoteLink-Normal-Bold') self.doc.write_text(_("Links To")) @@ -113,7 +113,7 @@ class NoteLinkReport(Report): tagtype = _("Internet") tagvalue = lvalue tagcheck = "" - + self.doc.start_row() self.doc.start_cell('NoteLink-TableCell') @@ -172,7 +172,7 @@ class NoteLinkOptions(MenuReportOptions): p.set_alignment(PARA_ALIGN_CENTER) p.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("NoteLink-Title", p) - + font = FontStyle() font.set(face=FONT_SANS_SERIF, size=14, italic=1) para = ParagraphStyle() @@ -182,7 +182,7 @@ class NoteLinkOptions(MenuReportOptions): para.set_bottom_margin(0.25) para.set_description(_('The style used for the section headers.')) default_style.add_paragraph_style("NoteLink-Heading", para) - + font = FontStyle() font.set_size(12) p = ParagraphStyle() @@ -192,7 +192,7 @@ class NoteLinkOptions(MenuReportOptions): p.set_bottom_margin(ReportUtils.pt2cm(3)) p.set_description(_('The basic style used for the text display.')) default_style.add_paragraph_style("NoteLink-Normal", p) - + font = FontStyle() font.set_size(12) font.set_bold(True) @@ -203,7 +203,7 @@ class NoteLinkOptions(MenuReportOptions): p.set_bottom_margin(ReportUtils.pt2cm(3)) p.set_description(_('The basic style used for table headings.')) default_style.add_paragraph_style("NoteLink-Normal-Bold", p) - + #Table Styles cell = TableCellStyle() default_style.add_cell_style('NoteLink-TableCell', cell) diff --git a/gramps/plugins/textreport/numberofancestorsreport.py b/gramps/plugins/textreport/numberofancestorsreport.py index 8dd38030f..eba0e001d 100644 --- a/gramps/plugins/textreport/numberofancestorsreport.py +++ b/gramps/plugins/textreport/numberofancestorsreport.py @@ -61,13 +61,13 @@ class NumberOfAncestorsReport(Report): def __init__(self, database, options, user): """ Create the NumberOfAncestorsReport 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 - + Menu options: name_format - Preferred format to display names incl_private - Whether to include private data @@ -97,7 +97,7 @@ class NumberOfAncestorsReport(Report): total_theoretical = 0 thisgen[self.__person.get_handle()]=1 ngettext = self._locale.translation.ngettext # to see "nearby" comments - + self.doc.start_paragraph("NOA-Title") name = self._name_display.display(self.__person) # feature request 2356: avoid genitive form @@ -115,9 +115,9 @@ class NumberOfAncestorsReport(Report): gen += 1 theoretical = math.pow(2, ( gen - 1 ) ) total_theoretical += theoretical - percent = '(%s%%)' % self._locale.format('%3.2f', + percent = '(%s%%)' % self._locale.format('%3.2f', ((sum(thisgen.values()) / theoretical ) * 100)) - + # TC # English return something like: # Generation 3 has 2 individuals. (50.00%) # translators: leave all/any {...} untranslated @@ -127,11 +127,11 @@ class NumberOfAncestorsReport(Report): thisgensize).format(number=gen, count=thisgensize, percent=percent) - + self.doc.start_paragraph('NOA-Normal') self.doc.write_text(text) self.doc.end_paragraph() - + temp = thisgen thisgen = {} for person_handle, person_data in temp.items(): @@ -157,13 +157,13 @@ class NumberOfAncestorsReport(Report): ) if( total_theoretical != 1 ): - percent = '(%3.2f%%)' % (( sum(all_people.values()) + percent = '(%3.2f%%)' % (( sum(all_people.values()) / (total_theoretical-1) ) * 100) else: percent = 0 # TC # English return something like: - # Total ancestors in generations 2 to 3 is 4. (66.67%) + # Total ancestors in generations 2 to 3 is 4. (66.67%) text = self._("Total ancestors in generations %(second_generation)d to " "%(last_generation)d is %(count)d. %(percent)s") % { 'second_generation': 2, @@ -171,7 +171,7 @@ class NumberOfAncestorsReport(Report): 'count' : len(all_people), 'percent' : percent } - + self.doc.start_paragraph('NOA-Normal') self.doc.write_text(text) self.doc.end_paragraph() @@ -187,16 +187,16 @@ class NumberOfAncestorsOptions(MenuReportOptions): """ def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the Number of Ancestors report. """ category_name = _("Report Options") - + pid = PersonOption(_("Center Person")) pid.set_help(_("The center person for the report")) - menu.add_option(category_name, "pid", pid) + menu.add_option(category_name, "pid", pid) stdoptions.add_name_format_option(menu, category_name) @@ -218,7 +218,7 @@ class NumberOfAncestorsOptions(MenuReportOptions): para.set_alignment(PARA_ALIGN_CENTER) para.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("NOA-Title", para) - + font = FontStyle() font.set_size(12) para = ParagraphStyle() diff --git a/gramps/plugins/textreport/placereport.py b/gramps/plugins/textreport/placereport.py index 4d0a7901d..caaa9bd50 100644 --- a/gramps/plugins/textreport/placereport.py +++ b/gramps/plugins/textreport/placereport.py @@ -43,7 +43,7 @@ from gramps.gen.plug.report import MenuReportOptions from gramps.gen.plug.report import stdoptions from gramps.gen.plug.docgen import (IndexMark, FontStyle, ParagraphStyle, TableStyle, TableCellStyle, - FONT_SANS_SERIF, FONT_SERIF, + FONT_SANS_SERIF, FONT_SERIF, INDEX_TYPE_TOC, PARA_ALIGN_CENTER) from gramps.gen.sort import Sort from gramps.gen.utils.location import get_main_location @@ -58,7 +58,7 @@ class PlaceReport(Report): def __init__(self, database, options, user): """ Create the PlaceReport object produces the Place report. - + The arguments are: database - the GRAMPS database instance @@ -67,7 +67,7 @@ class PlaceReport(Report): This report needs the following parameters (class variables) that come in the options class. - + places - List of places to report on. center - Center of report, person or event incl_private - Whether to include private data @@ -119,7 +119,7 @@ class PlaceReport(Report): # identified as a major category if this is included in a Book report. title = self._("Place Report") - mark = IndexMark(title, INDEX_TYPE_TOC, 1) + mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.start_paragraph("PLC-ReportTitle") self.doc.write_text(title, mark) self.doc.end_paragraph() @@ -131,10 +131,10 @@ class PlaceReport(Report): """ place_nbr = 1 - with self._user.progress(_("Place Report"), - _("Generating report"), + with self._user.progress(_("Place Report"), + _("Generating report"), len(self.place_handles)) as step: - + for handle in self.place_handles: self.__write_place(handle, place_nbr) if self.center == "Event": @@ -146,7 +146,7 @@ class PlaceReport(Report): place_nbr += 1 # increment progress bar step() - + def __write_place(self, handle, place_nbr): """ @@ -166,14 +166,14 @@ class PlaceReport(Report): self._("Country: %s ") % location.get(PlaceType.COUNTRY, '')] self.doc.start_paragraph("PLC-PlaceTitle") place_title = place_displayer.display(self.database, place) - self.doc.write_text(("%(nbr)s. %(place)s") % + self.doc.write_text(("%(nbr)s. %(place)s") % {'nbr' : place_nbr, 'place' : place_title}) self.doc.end_paragraph() for item in place_details: self.doc.start_paragraph("PLC-PlaceDetails") - self.doc.write_text(item) + self.doc.write_text(item) self.doc.end_paragraph() def __write_referenced_events(self, handle): @@ -306,7 +306,7 @@ class PlaceReport(Report): else: p_handle = m_handle person = self.database.get_person_from_handle(p_handle) - + nameEntry = "%s (%s)" % \ (self._nd.display(person), person.get_gramps_id()) @@ -349,12 +349,12 @@ class PlaceReport(Report): if event_handles: self.doc.end_table() - + def __get_place_handles(self, places): """ This procedure converts a string of place GIDs to a list of handles """ - place_handles = [] + place_handles = [] for place_gid in places.split(): place = self.database.get_place_from_gramps_id(place_gid) if place is not None: @@ -362,7 +362,7 @@ class PlaceReport(Report): place_handles.append(place.get_handle()) return place_handles - + #------------------------------------------------------------------------ # # PlaceOptions @@ -376,7 +376,7 @@ class PlaceOptions(MenuReportOptions): def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the place report. @@ -438,7 +438,7 @@ class PlaceOptions(MenuReportOptions): para.set_header_level(1) para.set_top_margin(0.25) para.set_bottom_margin(0.25) - para.set_alignment(PARA_ALIGN_CENTER) + para.set_alignment(PARA_ALIGN_CENTER) para.set_description(_('The style used for the title of the report.')) self.default_style.add_paragraph_style("PLC-ReportTitle", para) @@ -452,7 +452,7 @@ class PlaceOptions(MenuReportOptions): para.set_font(font) para.set(first_indent=-1.5, lmargin=1.5) para.set_top_margin(0.75) - para.set_bottom_margin(0.25) + para.set_bottom_margin(0.25) para.set_description(_('The style used for place title.')) self.default_style.add_paragraph_style("PLC-PlaceTitle", para) @@ -490,7 +490,7 @@ class PlaceOptions(MenuReportOptions): para.set_font(font) para.set(first_indent=-1.5, lmargin=1.5) para.set_top_margin(0.5) - para.set_bottom_margin(0.25) + para.set_bottom_margin(0.25) para.set_description(_('The style used for each section.')) self.default_style.add_paragraph_style("PLC-Section", para) diff --git a/gramps/plugins/textreport/recordsreport.py b/gramps/plugins/textreport/recordsreport.py index 2e1fd48e9..c2d3e21a8 100644 --- a/gramps/plugins/textreport/recordsreport.py +++ b/gramps/plugins/textreport/recordsreport.py @@ -34,13 +34,13 @@ #------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext -from gramps.plugins.lib.librecords import (RECORDS, find_records, +from gramps.plugins.lib.librecords import (RECORDS, find_records, CALLNAME_DONTUSE, CALLNAME_REPLACE, CALLNAME_UNDERLINE_ADD) from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle, FONT_SANS_SERIF, PARA_ALIGN_CENTER, IndexMark, INDEX_TYPE_TOC) -from gramps.gen.plug.menu import (BooleanOption, EnumeratedListOption, +from gramps.gen.plug.menu import (BooleanOption, EnumeratedListOption, FilterOption, NumberOption, PersonOption, StringOption) from gramps.gen.plug.report import Report @@ -166,7 +166,7 @@ class RecordsReportOptions(MenuReportOptions): _("Determines what people are included in the report.")) menu.add_option(category_name, "filter", self.__filter) self.__filter.connect('value-changed', self.__filter_changed) - + self.__pid = PersonOption(_("Filter Person")) self.__pid.set_help(_("The center person for the filter")) menu.add_option(category_name, "pid", self.__pid) diff --git a/gramps/plugins/textreport/simplebooktitle.py b/gramps/plugins/textreport/simplebooktitle.py index a1126588e..8f9e9129f 100644 --- a/gramps/plugins/textreport/simplebooktitle.py +++ b/gramps/plugins/textreport/simplebooktitle.py @@ -52,7 +52,7 @@ class SimpleBookTitle(Report): def __init__(self, database, options, user): """ Create SimpleBookTitle object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -61,7 +61,7 @@ class SimpleBookTitle(Report): This report needs the following parameters (class variables) that come in the options class. - + title - Title string. subtitle - Subtitle string. imgid - Gramps ID of the media object to use as an image. @@ -77,7 +77,7 @@ class SimpleBookTitle(Report): self.subtitle_string = menu.get_option_by_name('subtitle').get_value() self.footer_string = menu.get_option_by_name('footer').get_value() self.object_id = menu.get_option_by_name('imgid').get_value() - + def write_report(self): """ Generate the contents of the report """ self.doc.start_paragraph('SBT-Title') @@ -96,7 +96,7 @@ class SimpleBookTitle(Report): image_size = self.image_size else: image_size = min( - 0.8 * self.doc.get_usable_width(), + 0.8 * self.doc.get_usable_width(), 0.7 * self.doc.get_usable_height() ) self.doc.add_media_object(filename, 'center', image_size, image_size) @@ -118,23 +118,23 @@ class SimpleBookTitleOptions(MenuReportOptions): """ Defines options and provides handling interface. """ - + def __init__(self, name, dbase): self.__db = dbase MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add the options for this report """ category_name = _("Report Options") - + title = StringOption(_('book|Title'), _('Title of the Book') ) title.set_help(_("Title string for the book.")) menu.add_option(category_name, "title", title) - + subtitle = StringOption(_('Subtitle'), _('Subtitle of the Book') ) subtitle.set_help(_("Subtitle string for the book.")) menu.add_option(category_name, "subtitle", subtitle) - + dateinfo = time.localtime(time.time()) rname = self.__db.get_researcher().get_name() footer_string = _('Copyright %(year)d %(name)s') % { @@ -142,11 +142,11 @@ class SimpleBookTitleOptions(MenuReportOptions): footer = StringOption(_('Footer'), footer_string ) footer.set_help(_("Footer string for the page.")) menu.add_option(category_name, "footer", footer) - + imgid = MediaOption(_('Image')) imgid.set_help( _("Gramps ID of the media object to use as an image.")) menu.add_option(category_name, "imgid", imgid) - + imgsize = NumberOption(_('Image Size'), 0, 0, 20, 0.1) imgsize.set_help(_("Size of the image in cm. A value of 0 indicates " "that the image should be fit to the page.")) @@ -163,7 +163,7 @@ class SimpleBookTitleOptions(MenuReportOptions): para.set(pad=0.5) para.set_description(_('The style used for the title of the page.')) default_style.add_paragraph_style("SBT-Title", para) - + font = FontStyle() font.set(face=FONT_SANS_SERIF, size=14, italic=1) para = ParagraphStyle() diff --git a/gramps/plugins/textreport/summary.py b/gramps/plugins/textreport/summary.py index f6b0d536d..32583a468 100644 --- a/gramps/plugins/textreport/summary.py +++ b/gramps/plugins/textreport/summary.py @@ -62,7 +62,7 @@ class SummaryReport(Report): def __init__(self, database, options, user): """ Create the SummaryReport object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -75,7 +75,7 @@ class SummaryReport(Report): stdoptions.run_private_data_option(self, options.menu) self.__db = self.database - + lang = options.menu.get_option_by_name('trans').get_value() self.set_locale(lang) @@ -88,11 +88,11 @@ class SummaryReport(Report): mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.write_text(title, mark) self.doc.end_paragraph() - + self.summarize_people() self.summarize_families() self.summarize_media() - + def summarize_people(self): """ Write a summary of all the people in the database. @@ -105,20 +105,20 @@ class SummaryReport(Report): females = 0 unknowns = 0 namelist = [] - + self.doc.start_paragraph("SR-Heading") self.doc.write_text(self._("Individuals")) self.doc.end_paragraph() - + num_people = 0 for person in self.__db.iter_people(): num_people += 1 - + # Count people with media. length = len(person.get_media_list()) if length > 0: with_media += 1 - + # Count people with incomplete names. for name in [person.get_primary_name()] + person.get_alternate_names(): if name.get_first_name().strip() == "": @@ -130,12 +130,12 @@ class SummaryReport(Report): incomp_names += 1 else: incomp_names += 1 - + # Count people without families. if (not person.get_main_parents_family_handle() and not len(person.get_family_handle_list())): disconnected += 1 - + # Count missing birthdays. birth_ref = person.get_birth_ref() if birth_ref: @@ -144,7 +144,7 @@ class SummaryReport(Report): missing_bday += 1 else: missing_bday += 1 - + # Count genders. if person.get_gender() == Person.FEMALE: females += 1 @@ -152,50 +152,50 @@ class SummaryReport(Report): males += 1 else: unknowns += 1 - + # Count unique surnames for name in [person.get_primary_name()] + person.get_alternate_names(): if not name.get_surname().strip() in namelist \ and not name.get_surname().strip() == "": namelist.append(name.get_surname().strip()) - + self.doc.start_paragraph("SR-Normal") self.doc.write_text(self._("Number of individuals: %d") % num_people) self.doc.end_paragraph() - + self.doc.start_paragraph("SR-Normal") self.doc.write_text(self._("Males: %d") % males) self.doc.end_paragraph() - + self.doc.start_paragraph("SR-Normal") self.doc.write_text(self._("Females: %d") % females) self.doc.end_paragraph() - + self.doc.start_paragraph("SR-Normal") - self.doc.write_text(self._("Individuals with unknown gender: %d") % + self.doc.write_text(self._("Individuals with unknown gender: %d") % unknowns) self.doc.end_paragraph() - + self.doc.start_paragraph("SR-Normal") self.doc.write_text(self._("Incomplete names: %d") % incomp_names) self.doc.end_paragraph() - + self.doc.start_paragraph("SR-Normal") - self.doc.write_text(self._("Individuals missing birth dates: %d") % + self.doc.write_text(self._("Individuals missing birth dates: %d") % missing_bday) self.doc.end_paragraph() self.doc.start_paragraph("SR-Normal") - self.doc.write_text(self._("Disconnected individuals: %d") % + self.doc.write_text(self._("Disconnected individuals: %d") % disconnected) self.doc.end_paragraph() - + self.doc.start_paragraph("SR-Normal") self.doc.write_text(self._("Unique surnames: %d") % len(namelist)) self.doc.end_paragraph() - + self.doc.start_paragraph("SR-Normal") - self.doc.write_text(self._("Individuals with media objects: %d") % + self.doc.write_text(self._("Individuals with media objects: %d") % with_media) self.doc.end_paragraph() @@ -206,9 +206,9 @@ class SummaryReport(Report): self.doc.start_paragraph("SR-Heading") self.doc.write_text(self._("Family Information")) self.doc.end_paragraph() - + self.doc.start_paragraph("SR-Normal") - self.doc.write_text(self._("Number of families: %d") % + self.doc.write_text(self._("Number of families: %d") % self.__db.get_number_of_families()) self.doc.end_paragraph() @@ -219,11 +219,11 @@ class SummaryReport(Report): total_media = 0 size_in_bytes = 0 notfound = [] - + self.doc.start_paragraph("SR-Heading") self.doc.write_text(self._("Media Objects")) self.doc.end_paragraph() - + total_media = len(self.__db.get_media_object_handles()) mbytes = "0" for media_id in self.__db.get_media_object_handles(): @@ -238,17 +238,17 @@ class SummaryReport(Report): mbytes = str(size_in_bytes)[:(length-6)] except: notfound.append(media.get_path()) - + self.doc.start_paragraph("SR-Normal") - self.doc.write_text(self._("Number of unique media objects: %d") % + self.doc.write_text(self._("Number of unique media objects: %d") % total_media) self.doc.end_paragraph() - + self.doc.start_paragraph("SR-Normal") - self.doc.write_text(self._("Total size of media objects: %s MB") % + self.doc.write_text(self._("Total size of media objects: %s MB") % mbytes) self.doc.end_paragraph() - + if len(notfound) > 0: self.doc.start_paragraph("SR-Heading") self.doc.write_text(self._("Missing Media Objects")) @@ -270,7 +270,7 @@ class SummaryOptions(MenuReportOptions): """ def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the summary report. @@ -298,7 +298,7 @@ class SummaryOptions(MenuReportOptions): para.set_alignment(PARA_ALIGN_CENTER) para.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("SR-Title", para) - + font = FontStyle() font.set_size(12) font.set_bold(True) @@ -307,7 +307,7 @@ class SummaryOptions(MenuReportOptions): para.set_top_margin(0) para.set_description(_('The basic style used for sub-headings.')) default_style.add_paragraph_style("SR-Heading", para) - + font = FontStyle() font.set_size(12) para = ParagraphStyle() diff --git a/gramps/plugins/textreport/tableofcontents.py b/gramps/plugins/textreport/tableofcontents.py index 651b68e82..29b5d9a8e 100644 --- a/gramps/plugins/textreport/tableofcontents.py +++ b/gramps/plugins/textreport/tableofcontents.py @@ -34,7 +34,7 @@ _ = glocale.translation.sgettext from gramps.gen.plug.report import Report from gramps.gen.plug.report import MenuReportOptions from gramps.gen.plug.report import stdoptions -from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle, TableStyle, +from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle, TableStyle, TableCellStyle, FONT_SANS_SERIF, IndexMark, INDEX_TYPE_TOC) @@ -48,7 +48,7 @@ class TableOfContents(Report): def __init__(self, database, options, user): """ Create TableOfContents object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -77,11 +77,11 @@ class TableOfContentsOptions(MenuReportOptions): """ Defines options and provides handling interface. """ - + def __init__(self, name, dbase): self.__db = dbase MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add the options for this report """ category_name = _("Report Options") @@ -96,17 +96,17 @@ class TableOfContentsOptions(MenuReportOptions): para.set_bottom_margin(0.25) para.set_description(_('The style used for the title.')) default_style.add_paragraph_style("TOC-Title", para) - + table = TableStyle() table.set_width(100) table.set_columns(2) table.set_column_width(0, 80) table.set_column_width(1, 20) default_style.add_table_style("TOC-Table", table) - + cell = TableCellStyle() default_style.add_cell_style("TOC-Cell", cell) - + para = ParagraphStyle() para.set_font(font) para.set_description(_('The style used for first level headings.')) diff --git a/gramps/plugins/textreport/tagreport.py b/gramps/plugins/textreport/tagreport.py index a12e3c8eb..2349c793e 100644 --- a/gramps/plugins/textreport/tagreport.py +++ b/gramps/plugins/textreport/tagreport.py @@ -63,7 +63,7 @@ class TagReport(Report): def __init__(self, database, options, user): """ Create the TagReport object that produces the report. - + The arguments are: database - the GRAMPS database instance @@ -72,7 +72,7 @@ class TagReport(Report): This report needs the following parameters (class variables) that come in the options class. - + tag - The tag each object must match to be included. name_format - Preferred format to display names of people incl_private - Whether to include private data @@ -86,7 +86,7 @@ class TagReport(Report): if not self.tag: raise ReportError(_('Tag Report'), _('You must first create a tag before running this report.')) - + self.set_locale(menu.get_option_by_name('trans').get_value()) stdoptions.run_name_format_option(self, menu) @@ -98,7 +98,7 @@ class TagReport(Report): mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.write_text(title, mark) self.doc.end_paragraph() - + self.write_people() self.write_families() self.write_events() @@ -115,10 +115,10 @@ class TagReport(Report): filter = FilterClass() filter.add_rule(rules.person.HasTag([self.tag])) ind_list = filter.apply(self.database, plist) - + if not ind_list: return - + self.doc.start_paragraph("TR-Heading") header = self._("People") mark = IndexMark(header, INDEX_TYPE_TOC, 2) @@ -126,9 +126,9 @@ class TagReport(Report): self.doc.end_paragraph() self.doc.start_table('PeopleTable','TR-Table') - + self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Id")) @@ -140,26 +140,26 @@ class TagReport(Report): self.doc.write_text(self._("Name")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Birth")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Death")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.end_row() for person_handle in ind_list: person = self.database.get_person_from_handle(person_handle) self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') self.doc.write_text(person.get_gramps_id()) @@ -173,7 +173,7 @@ class TagReport(Report): self.doc.write_text(name, mark) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') birth_ref = person.get_birth_ref() @@ -182,7 +182,7 @@ class TagReport(Report): self.doc.write_text(get_date( event )) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') death_ref = person.get_death_ref() @@ -191,21 +191,21 @@ class TagReport(Report): self.doc.write_text(get_date( event )) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.end_row() - + self.doc.end_table() - + def write_families(self): flist = self.database.iter_family_handles() FilterClass = GenericFilterFactory('Family') filter = FilterClass() filter.add_rule(rules.family.HasTag([self.tag])) fam_list = filter.apply(self.database, flist) - + if not fam_list: return - + self.doc.start_paragraph("TR-Heading") header = self._("Families") mark = IndexMark(header,INDEX_TYPE_TOC, 2) @@ -213,9 +213,9 @@ class TagReport(Report): self.doc.end_paragraph() self.doc.start_table('FamilyTable','TR-Table') - + self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Id")) @@ -227,26 +227,26 @@ class TagReport(Report): self.doc.write_text(self._("Father")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Mother")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Relationship")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.end_row() for family_handle in fam_list: family = self.database.get_family_from_handle(family_handle) - + self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') self.doc.write_text(family.get_gramps_id()) @@ -262,7 +262,7 @@ class TagReport(Report): self.doc.write_text(self._name_display.display(father), mark) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') mother_handle = family.get_mother_handle() @@ -272,16 +272,16 @@ class TagReport(Report): self.doc.write_text(self._name_display.display(mother), mark) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') relation = family.get_relationship() self.doc.write_text(str(relation) ) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.end_row() - + self.doc.end_table() def write_events(self): @@ -290,10 +290,10 @@ class TagReport(Report): filter = FilterClass() filter.add_rule(rules.event.HasTag([self.tag])) event_list = filter.apply(self.database, elist) - + if not event_list: return - + self.doc.start_paragraph("TR-Heading") header = self._("Events") mark = IndexMark(header, INDEX_TYPE_TOC, 2) @@ -301,9 +301,9 @@ class TagReport(Report): self.doc.end_paragraph() self.doc.start_table('EventTable','TR-Table') - + self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Id")) @@ -315,32 +315,32 @@ class TagReport(Report): self.doc.write_text(self._("Type")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Participants")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Date")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.end_row() for event_handle in event_list: event = self.database.get_event_from_handle(event_handle) - + self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') self.doc.write_text(event.get_gramps_id()) self.doc.end_paragraph() - self.doc.end_cell() - + self.doc.end_cell() + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') self.doc.write_text(str(event.get_type())) @@ -452,10 +452,10 @@ class TagReport(Report): filter = FilterClass() filter.add_rule(rules.note.HasTag([self.tag])) note_list = filter.apply(self.database, nlist) - + if not note_list: return - + self.doc.start_paragraph("TR-Heading") header = self._("Notes") mark = IndexMark(header, INDEX_TYPE_TOC, 2) @@ -463,9 +463,9 @@ class TagReport(Report): self.doc.end_paragraph() self.doc.start_table('NoteTable','TR-Table') - + self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Id")) @@ -477,33 +477,33 @@ class TagReport(Report): self.doc.write_text(self._("Type")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell', 2) self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Text")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.end_row() for note_handle in note_list: note = self.database.get_note_from_handle(note_handle) - + self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') self.doc.write_text(note.get_gramps_id()) self.doc.end_paragraph() - self.doc.end_cell() - + self.doc.end_cell() + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') type = note.get_type() self.doc.write_text(str(type)) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell', 2) self.doc.write_styled_note(note.get_styledtext(), note.get_format(), 'TR-Note', @@ -511,9 +511,9 @@ class TagReport(Report): == NoteType.HTML_CODE) ) self.doc.end_cell() - + self.doc.end_row() - + self.doc.end_table() def write_media(self): @@ -522,10 +522,10 @@ class TagReport(Report): filter = FilterClass() filter.add_rule(rules.media.HasTag([self.tag])) media_list = filter.apply(self.database, mlist) - + if not media_list: return - + self.doc.start_paragraph("TR-Heading") header = self._("Media") mark = IndexMark(header, INDEX_TYPE_TOC, 2) @@ -533,9 +533,9 @@ class TagReport(Report): self.doc.end_paragraph() self.doc.start_table('MediaTable','TR-Table') - + self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Id")) @@ -547,46 +547,46 @@ class TagReport(Report): self.doc.write_text(self._("Title")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Type")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal-Bold') self.doc.write_text(self._("Date")) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.end_row() for media_handle in media_list: media = self.database.get_object_from_handle(media_handle) self.doc.start_row() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') self.doc.write_text(media.get_gramps_id()) self.doc.end_paragraph() - self.doc.end_cell() - + self.doc.end_cell() + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') title = media.get_description() self.doc.write_text(str(title)) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') mime_type = media.get_mime_type() self.doc.write_text(str(mime_type)) self.doc.end_paragraph() self.doc.end_cell() - + self.doc.start_cell('TR-TableCell') self.doc.start_paragraph('TR-Normal') date = get_date(media) @@ -596,7 +596,7 @@ class TagReport(Report): self.doc.end_cell() self.doc.end_row() - + self.doc.end_table() def write_repositories(self): @@ -855,7 +855,7 @@ class TagOptions(MenuReportOptions): def __init__(self, name, dbase): self.__db = dbase MenuReportOptions.__init__(self, name, dbase) - + def add_menu_options(self, menu): """ Add options to the menu for the tag report. @@ -900,7 +900,7 @@ class TagOptions(MenuReportOptions): p.set_alignment(PARA_ALIGN_CENTER) p.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("TR-Title", p) - + font = FontStyle() font.set(face=FONT_SANS_SERIF, size=14, italic=1) para = ParagraphStyle() @@ -910,7 +910,7 @@ class TagOptions(MenuReportOptions): para.set_bottom_margin(0.25) para.set_description(_('The style used for the section headers.')) default_style.add_paragraph_style("TR-Heading", para) - + font = FontStyle() font.set_size(12) p = ParagraphStyle() @@ -920,7 +920,7 @@ class TagOptions(MenuReportOptions): p.set_bottom_margin(ReportUtils.pt2cm(3)) p.set_description(_('The basic style used for the text display.')) default_style.add_paragraph_style("TR-Normal", p) - + font = FontStyle() font.set_size(12) font.set_bold(True) @@ -931,14 +931,14 @@ class TagOptions(MenuReportOptions): p.set_bottom_margin(ReportUtils.pt2cm(3)) p.set_description(_('The basic style used for table headings.')) default_style.add_paragraph_style("TR-Normal-Bold", p) - + para = ParagraphStyle() p.set(first_indent=-0.75, lmargin=.75) para.set_top_margin(ReportUtils.pt2cm(3)) para.set_bottom_margin(ReportUtils.pt2cm(3)) para.set_description(_('The basic style used for the note display.')) default_style.add_paragraph_style("TR-Note",para) - + #Table Styles cell = TableCellStyle() default_style.add_cell_style('TR-TableCell', cell) diff --git a/gramps/plugins/textreport/textplugins.gpr.py b/gramps/plugins/textreport/textplugins.gpr.py index 0ac2df1e2..da0fd3987 100644 --- a/gramps/plugins/textreport/textplugins.gpr.py +++ b/gramps/plugins/textreport/textplugins.gpr.py @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # diff --git a/gramps/plugins/tool/changenames.py b/gramps/plugins/tool/changenames.py index bfb95f585..7b3b69f0f 100644 --- a/gramps/plugins/tool/changenames.py +++ b/gramps/plugins/tool/changenames.py @@ -74,7 +74,7 @@ class ChangeNames(tool.BatchTool, ManagedWindow): uistate = user.uistate self.label = _('Capitalization changes') self.cb = callback - + ManagedWindow.__init__(self,uistate,[],self.__class__) self.set_window(Gtk.Window(),Gtk.Label(),'') @@ -86,9 +86,9 @@ class ChangeNames(tool.BatchTool, ManagedWindow): self.progress.set_pass(_('Searching family names'), len(self.db.get_surname_list())) self.name_list = [] - + for name in self.db.get_surname_list(): - name.strip() + name.strip() namesplitSP= name.split() lSP = len(namesplitSP) namesplitHY= name.split('-') @@ -131,10 +131,10 @@ class ChangeNames(tool.BatchTool, ManagedWindow): if notcap: # Multiple surnames possibly after frefix self.name_list.append(name) - + if uistate: self.progress.step() - + if self.name_list: self.display() else: @@ -145,7 +145,7 @@ class ChangeNames(tool.BatchTool, ManagedWindow): parent=uistate.window) def name_cap(self, name): - name.strip() + name.strip() namesplitSP = name.split() lSP = len(namesplitSP) lHY = len(name.split('-')) @@ -158,10 +158,10 @@ class ChangeNames(tool.BatchTool, ManagedWindow): #if name != name.capitalize(): # Single surname without space(s) or hyphen(s), normal case return name.capitalize() - else: + else: # more than one string in surname but no hyphen # check if first string is in prefix_list, if so CAP the rest - # Names like (von) Kohl(-)Brandt + # Names like (von) Kohl(-)Brandt result = "" s1 = 0 if namesplitSP[0].lower() in prefix_list: @@ -182,11 +182,11 @@ class ChangeNames(tool.BatchTool, ManagedWindow): "on_help_clicked" : self.on_help_clicked, "on_delete_event" : self.close, }) - + self.list = self.top.get_object("list") self.set_window(window,self.top.get_object('title'),self.label) - self.model = Gtk.ListStore(GObject.TYPE_BOOLEAN, GObject.TYPE_STRING, + self.model = Gtk.ListStore(GObject.TYPE_BOOLEAN, GObject.TYPE_STRING, GObject.TYPE_STRING) r = Gtk.CellRendererToggle() @@ -215,7 +215,7 @@ class ChangeNames(tool.BatchTool, ManagedWindow): self.iter_list.append(handle) self.progress.step() self.progress.close() - + self.show() def toggled(self,cell,path_string): @@ -262,10 +262,10 @@ class ChangeNames(tool.BatchTool, ManagedWindow): # self.parent.bookmarks.redraw() self.close() self.cb() - + #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class ChangeNamesOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/changetypes.py b/gramps/plugins/tool/changetypes.py index 333876e54..1c865b217 100644 --- a/gramps/plugins/tool/changetypes.py +++ b/gramps/plugins/tool/changetypes.py @@ -63,16 +63,16 @@ class ChangeTypes(tool.BatchTool, ManagedWindow): def init_gui(self): # Draw dialog and make it handle everything - + self.glade = Glade() - + self.auto1 = self.glade.get_object("original") self.auto2 = self.glade.get_object("new") # Need to display localized event names etype = EventType() event_names = sorted(etype.get_standard_names(), key=glocale.sort_key) - + fill_combo(self.auto1,event_names) fill_combo(self.auto2,event_names) @@ -90,7 +90,7 @@ class ChangeTypes(tool.BatchTool, ManagedWindow): "on_apply_clicked" : self.on_apply_clicked, "on_delete_event" : self.close, }) - + self.show() def build_menu_names(self, obj): @@ -139,17 +139,17 @@ class ChangeTypes(tool.BatchTool, ManagedWindow): the_type.set(self.auto2.get_child().get_text()) self.options.handler.options_dict['totype'] = the_type.xml_str() - + self.run_tool(self.window) # Save options self.options.handler.save_options() - + self.close() #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class ChangeTypesOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/check.py b/gramps/plugins/tool/check.py index 9f20106b6..d7e68bfcc 100644 --- a/gramps/plugins/tool/check.py +++ b/gramps/plugins/tool/check.py @@ -110,7 +110,7 @@ def cross_table_duplicates(db, uistate): total_nr_handles = 0 all_handles = set([]) for the_map in [db.person_map, db.family_map, db.event_map, db.place_map, - db.source_map, db.citation_map, db.media_map, db.repository_map, + db.source_map, db.citation_map, db.media_map, db.repository_map, db.note_map]: handle_list = list(the_map.keys()) total_nr_handles += len(handle_list) @@ -141,7 +141,7 @@ class Check(tool.BatchTool): cli = uistate is None if uistate: from gramps.gui.utils import ProgressMeter as PM - global ProgressMeter + global ProgressMeter ProgressMeter = PM if self.db.readonly: @@ -159,7 +159,7 @@ class Check(tool.BatchTool): "This is bad and can be fixed by making a backup of your\n" "Family Tree and importing that backup in an empty family\n" "tree. The rest of the checking is skipped, the Check and\n" - "Repair tool should be run anew on this new Family Tree."), + "Repair tool should be run anew on this new Family Tree."), cli) return with DbTxn(_("Check Integrity"), self.db, batch=True) as trans: @@ -174,18 +174,18 @@ class Check(tool.BatchTool): checker.fix_ctrlchars_in_notes() checker.cleanup_missing_photos(cli) checker.cleanup_deleted_name_formats() - + prev_total = -1 total = 0 - + while prev_total != total: prev_total = total - + checker.check_for_broken_family_links() checker.check_parent_relationships() checker.cleanup_empty_families(cli) checker.cleanup_duplicate_spouses() - + total = checker.family_errors() checker.check_events() @@ -213,7 +213,7 @@ class Check(tool.BatchTool): # #------------------------------------------------------------------------- class CheckIntegrity(object): - + def __init__(self, dbstate, uistate, trans): self.uistate = uistate if self.uistate: @@ -265,7 +265,7 @@ class CheckIntegrity(object): def cleanup_deleted_name_formats(self): """ Permanently remove deleted name formats from db. - + When user deletes custom name format those are not removed only marked as "inactive". This method does the cleanup of the name format table, as well as fixes the display_as, sort_as values for each Name in the db. @@ -274,10 +274,10 @@ class CheckIntegrity(object): self.progress.set_pass(_('Looking for invalid name format references'), self.db.get_number_of_people()) logging.info('Looking for invalid name format references') - + deleted_name_formats = [number for (number, name, fmt_str,act) in self.db.name_formats if not act] - + # remove the invalid references from all Name objects for person_handle in self.db.get_person_handles(): person = self.db.get_person_from_handle(person_handle) @@ -305,18 +305,18 @@ class CheckIntegrity(object): name_list.append(name) if a_changed: person.set_alternate_names(name_list) - + if p_changed or a_changed: self.db.commit_person(person, self.trans) self.removed_name_format.append(person_handle) - + self.progress.step() # update the custom name name format table for number in deleted_name_formats: _nd.del_name_format(number) self.db.name_formats = _nd.get_name_format(only_custom=True, - only_active=False) + only_active=False) if len(self.removed_name_format) == 0: logging.info(' OK: no invalid name formats found found') @@ -364,7 +364,7 @@ class CheckIntegrity(object): '"%(gid)s" path "%(path)s"' % {'gid' : obj.gramps_id, 'path' : obj.path}) if not isinstance(data[4], str): - logging.warning(' FAIL: encoding error on media object ' + logging.warning(' FAIL: encoding error on media object ' '"%(gid)s" description "%(desc)s"' % {'gid' : obj.gramps_id, 'desc' : obj.desc}) error_count += 1 @@ -380,7 +380,7 @@ class CheckIntegrity(object): obj.mime = "" self.db.commit_media_object(obj, self.trans) logging.warning(' FAIL: encoding error on media object ' - '"%(desc)s" mime "%(mime)s"' % + '"%(desc)s" mime "%(mime)s"' % {'desc' : obj.desc, 'mime' : obj.mime}) error_count += 1 self.progress.step() @@ -403,7 +403,7 @@ class CheckIntegrity(object): self.db.note_map[bhandle][1]) error_count += 1 # Commit only if ctrl char found. - note.set_styledtext(StyledText(text=new_text, + note.set_styledtext(StyledText(text=new_text, tags=stext.get_tags())) self.db.commit_note(note, self.trans) self.progress.step() @@ -419,7 +419,7 @@ class CheckIntegrity(object): self.db.get_number_of_people()) logging.info('Looking for broken family links') previous_errors = len(self.broken_parent_links + self.broken_links) - + for bfamily_handle in fhandle_list: family_handle = handle2internal(bfamily_handle) family = self.db.get_family_from_handle(family_handle) @@ -436,8 +436,8 @@ class CheckIntegrity(object): self.db.commit_family(family, self.trans) self.broken_parent_links.append((father_handle, family_handle)) logging.warning(" FAIL: family '%(fam_gid)s' " - "father handle '%(hand)s' does not exist" % - {'fam_gid' : family.gramps_id, + "father handle '%(hand)s' does not exist" % + {'fam_gid' : family.gramps_id, 'hand' : father_handle}) father_handle = None if mother_handle: @@ -451,8 +451,8 @@ class CheckIntegrity(object): self.db.commit_family(family, self.trans) self.broken_parent_links.append((mother_handle, family_handle)) logging.warning(" FAIL: family '%(fam_gid)s' " - "mother handle '%(hand)s' does not exist" % - {'fam_gid' : family.gramps_id, + "mother handle '%(hand)s' does not exist" % + {'fam_gid' : family.gramps_id, 'hand' : mother_handle}) mother_handle = None @@ -465,7 +465,7 @@ class CheckIntegrity(object): father.add_family_handle(family_handle) self.db.commit_person(father, self.trans) logging.warning(" FAIL: family '%(fam_gid)s' father " - "'%(hand)s' does not refer back to the family" % + "'%(hand)s' does not refer back to the family" % {'fam_gid' : family.gramps_id, 'hand' : father_handle}) @@ -478,10 +478,10 @@ class CheckIntegrity(object): mother.add_family_handle(family_handle) self.db.commit_person(mother, self.trans) logging.warning(" FAIL: family '%(fam_gid)s' mother " - "'%(hand)s' does not refer back to the family" % + "'%(hand)s' does not refer back to the family" % {'fam_gid' : family.gramps_id, 'hand' : mother_handle}) - + for child_ref in family.get_child_ref_list(): child_handle = child_ref.ref child = self.db.get_person_from_handle(child_handle) @@ -493,7 +493,7 @@ class CheckIntegrity(object): # is "Broken19" logging.warning(" FAIL: family '%(fam_gid)s' " "child '%(child_gid)s' is one of the " - "parents" % + "parents" % {'fam_gid' : family.gramps_id, 'child_gid' : child.gramps_id}) family.remove_child_ref(child_ref) @@ -509,7 +509,7 @@ class CheckIntegrity(object): # is "Broken8" logging.warning(" FAIL: family '%(fam_gid)s' " "child '%(child_gid)s' has no reference" - " to the family. Reference added" % + " to the family. Reference added" % {'fam_gid' : family.gramps_id, 'child_gid' : child.gramps_id}) child.add_parent_family_handle(family_handle) @@ -520,7 +520,7 @@ class CheckIntegrity(object): # This is tested by TestcaseGenerator where the father # is "Broken20" logging.warning(" FAIL: family '%(fam_gid)s' child " - "'%(hand)s' does not exist in the database" % + "'%(hand)s' does not exist in the database" % {'fam_gid' : family.gramps_id, 'hand' : child_handle}) family.remove_child_ref(child_ref) @@ -543,7 +543,7 @@ class CheckIntegrity(object): self.db.commit_family(family, self.trans) self.progress.step() - + # Check persons membership in referenced families for bperson_handle in self.db.get_person_handles(): person_handle = handle2internal(bperson_handle) @@ -571,7 +571,7 @@ class CheckIntegrity(object): # is "Broken9" logging.warning(" FAIL: family '%(fam_gid)s' person " "'%(pers_gid)s' is not a child in the " - "referenced parent family" % + "referenced parent family" % {'fam_gid' : family.gramps_id, 'pers_gid' :person.gramps_id}) person.remove_parent_family_handle(par_family_handle) @@ -585,7 +585,7 @@ class CheckIntegrity(object): # is "Broken20" logging.warning(" FAIL: person '%(pers_gid)s' refers to " "family '%(hand)s' which is not in the " - "database" % + "database" % {'pers_gid' : person.gramps_id, 'hand' : family_handle}) person.remove_family_handle(family_handle) @@ -603,7 +603,7 @@ class CheckIntegrity(object): # to the mother logging.warning(" FAIL: family '%(fam_gid)s' person " "'%(pers_gid)s' is not member of the referenced" - " family" % + " family" % {'fam_gid' : family.gramps_id, 'pers_gid' : person.gramps_id}) person.remove_family_handle(family_handle) @@ -613,18 +613,18 @@ class CheckIntegrity(object): if previous_errors == len(self.broken_parent_links + self.broken_links): logging.info(' OK: no broken family links found') - + def cleanup_missing_photos(self, cl=0): self.progress.set_pass(_('Looking for unused objects'), len(self.db.get_media_object_handles())) logging.info('Looking for missing photos') - + missmedia_action = 0 #------------------------------------------------------------------------- def remove_clicked(): # File is lost => remove all references and the object itself - + for handle in self.db.get_person_handles(sort_handles=False): person = self.db.get_person_from_handle(handle) if person.has_media_reference(ObjectId): @@ -636,25 +636,25 @@ class CheckIntegrity(object): if family.has_media_reference(ObjectId): family.remove_media_references([ObjectId]) self.db.commit_family(family, self.trans) - + for handle in self.db.get_event_handles(): event = self.db.get_event_from_handle(handle) if event.has_media_reference(ObjectId): event.remove_media_references([ObjectId]) self.db.commit_event(event, self.trans) - + for handle in self.db.get_source_handles(): source = self.db.get_source_from_handle(handle) if source.has_media_reference(ObjectId): source.remove_media_references([ObjectId]) self.db.commit_source(source, self.trans) - + for handle in self.db.get_citation_handles(): citation = self.db.get_citation_from_handle(handle) if citation.has_media_reference(ObjectId): citation.remove_media_references([ObjectId]) self.db.commit_citation(citation, self.trans) - + for handle in self.db.get_place_handles(): place = self.db.get_place_from_handle(handle) if place.has_media_reference(ObjectId): @@ -662,10 +662,10 @@ class CheckIntegrity(object): self.db.commit_place(place, self.trans) self.removed_photo.append(ObjectId) - self.db.remove_object(ObjectId,self.trans) + self.db.remove_object(ObjectId,self.trans) logging.warning(' FAIL: media object and all references to ' 'it removed') - + def leave_clicked(): self.bad_photo.append(ObjectId) logging.warning(' FAIL: references to missing file kept') @@ -703,7 +703,7 @@ class CheckIntegrity(object): fs_top.destroy() #------------------------------------------------------------------------- - + for bObjectId in self.db.get_media_object_handles(): ObjectId = handle2internal(bObjectId) obj = self.db.get_object_from_handle(ObjectId) @@ -720,18 +720,18 @@ class CheckIntegrity(object): logging.warning(' FAIL: media object "%(desc)s" ' 'reference to missing file "%(name)s" ' 'found' % - {'desc' : photo_desc, + {'desc' : photo_desc, 'name' : photo_name}) mmd = MissingMediaDialog( _("Media object could not be found"), _("The file:\n%(file_name)s\nis referenced in " - "the database, but no longer exists.\n" + "the database, but no longer exists.\n" "The file may have been deleted or moved to " - "a different location.\n" + "a different location.\n" "You may choose to either remove the " - "reference from the database,\n" + "reference from the database,\n" "keep the reference to the missing file, " - "or select a new file." + "or select a new file." ) % {'file_name' : '%s' % photo_name}, remove_clicked, leave_clicked, select_clicked, parent=self.uistate.window) @@ -760,7 +760,7 @@ class CheckIntegrity(object): self.progress.step() if len(self.bad_photo + self.removed_photo) == 0: logging.info(' OK: no missing photos found') - + def cleanup_empty_objects(self): #the position of the change column in the primary objects CHANGE_PERSON = 17 @@ -772,7 +772,7 @@ class CheckIntegrity(object): CHANGE_MEDIA = 8 CHANGE_REPOS = 7 CHANGE_NOTE = 5 - + empty_person_data = Person().serialize() empty_family_data = Family().serialize() empty_event_data = Event().serialize() @@ -789,7 +789,7 @@ class CheckIntegrity(object): def _f(value): return self._check_empty(value, empty, flag) return _f - + table = ( # Dispatch table for cleaning up empty objects. Each entry is @@ -801,7 +801,7 @@ class CheckIntegrity(object): # 4. text identifying the object being cleaned up # 5. function to check if the data is empty # 6. function to remove the object, if empty - + ('persons', _db.get_person_from_handle, _db.get_person_cursor, @@ -890,7 +890,7 @@ class CheckIntegrity(object): self.progress.step() if check_func(data): # we cannot remove here as that would destroy cursor - # so save the handles for later removal + # so save the handles for later removal logging.warning(' FAIL: empty %(type)s record with ' 'handle "%(hand)s" was found' % {'type' : the_type, 'hand' : handle}) @@ -901,12 +901,12 @@ class CheckIntegrity(object): remove_func(handle, self.trans) if len(self.empty_objects[the_type]) == 0: logging.info(' OK: no empty %s found' % the_type) - + def _check_empty(self, data, empty_data, changepos): """compare the data with the data of an empty object change, handle and gramps_id are not compared """ if changepos is not None: - return (data[2:changepos] == empty_data[2:changepos] and + return (data[2:changepos] == empty_data[2:changepos] and data[changepos+1:] == empty_data[changepos+1:] ) else : @@ -923,7 +923,7 @@ class CheckIntegrity(object): for bfamily_handle in fhandle_list: family_handle = handle2internal(bfamily_handle) self.progress.step() - + family = self.db.get_family_from_handle(family_handle) family_id = family.get_gramps_id() father_handle = family.get_father_handle() @@ -976,7 +976,7 @@ class CheckIntegrity(object): else: mgender = None - if (fgender == Person.FEMALE + if (fgender == Person.FEMALE or mgender == Person.MALE) and fgender != mgender: # swap. note: (at most) one handle may be None logging.warning(' FAIL: the family "%s" has a father=female or ' @@ -994,11 +994,11 @@ class CheckIntegrity(object): self.db.get_number_of_people() +self.db.get_number_of_families()) logging.info('Looking for event problems') - + for bkey in self.db.get_person_handles(sort_handles=False): key = handle2internal(bkey) self.progress.step() - + person = self.db.get_person_from_handle(key) birth_ref = person.get_birth_ref() none_handle = False @@ -1018,7 +1018,7 @@ class CheckIntegrity(object): type=EventType.BIRTH) logging.warning(' FAIL: the person "%(gid)s" refers to ' 'a birth event "%(hand)s" which does not ' - 'exist in the database' % + 'exist in the database' % {'gid' : person.gramps_id, 'hand' : birth_handle}) self.invalid_events.add(key) @@ -1028,7 +1028,7 @@ class CheckIntegrity(object): # This is tested by TestcaseGenerator person "Broken14" logging.warning(' FAIL: the person "%(gid)s" refers ' 'to a birth event which is of type ' - '"%(type)s" instead of Birth' % + '"%(type)s" instead of Birth' % {'gid' : person.gramps_id, 'type' : int(birth.get_type())}) birth.set_type(EventType(EventType.BIRTH)) @@ -1053,7 +1053,7 @@ class CheckIntegrity(object): # This is tested by TestcaseGenerator person "Broken12" logging.warning(' FAIL: the person "%(gid)s" refers to ' 'a death event "%(hand)s" which does not ' - 'exist in the database' % + 'exist in the database' % {'gid' : person.gramps_id, 'hand' : death_handle}) make_unknown(death_handle, self.explanation.handle, @@ -1066,7 +1066,7 @@ class CheckIntegrity(object): # This is tested by TestcaseGenerator person "Broken15" logging.warning(' FAIL: the person "%(gid)s" refers ' 'to a death event which is of type ' - '"%(type)s" instead of Death' % + '"%(type)s" instead of Death' % {'gid' : person.gramps_id, 'type' : int(death.get_type())}) death.set_type(EventType(EventType.DEATH)) @@ -1095,7 +1095,7 @@ class CheckIntegrity(object): # This is tested by TestcaseGenerator person "Broken13" logging.warning(' FAIL: the person "%(gid)s" refers ' 'to an event "%(hand)s" which does not ' - 'exist in the database' % + 'exist in the database' % { 'gid' : person.gramps_id, 'hand' : event_handle}) make_unknown(event_handle, @@ -1132,7 +1132,7 @@ class CheckIntegrity(object): # does not exist in the database logging.warning(' FAIL: the family "%(gid)s" refers ' 'to an event "%(hand)s" which does not ' - 'exist in the database' % + 'exist in the database' % {'gid' : family.gramps_id, 'hand' : event_handle}) make_unknown(event_handle, self.explanation.handle, @@ -1155,11 +1155,11 @@ class CheckIntegrity(object): def check_person_references(self): plist = self.db.get_person_handles() - + self.progress.set_pass(_('Looking for person reference problems'), len(plist)) logging.info('Looking for person reference problems') - + for bkey in plist: key = handle2internal(bkey) self.progress.step() @@ -1211,11 +1211,11 @@ class CheckIntegrity(object): def check_repo_references(self): slist = self.db.get_source_handles() - + self.progress.set_pass(_('Looking for repository reference problems'), len(slist)) logging.info('Looking for repository reference problems') - + for bkey in slist: key = handle2internal(bkey) self.progress.step() @@ -1294,7 +1294,7 @@ class CheckIntegrity(object): self.commit_place, self.trans) logging.warning(' FAIL: the person "%(gid)s" refers ' 'to an LdsOrd place "%(hand)s" which ' - 'does not exist in the database' % + 'does not exist in the database' % {'gid' : person.gramps_id, 'hand' : place_handle}) self.invalid_place_references.add(key) @@ -1314,7 +1314,7 @@ class CheckIntegrity(object): self.commit_place, self.trans) logging.warning(' FAIL: the family "%(gid)s" refers ' 'to an LdsOrd place "%(hand)s" which ' - 'does not exist in the database' % + 'does not exist in the database' % {'gid' : family.gramps_id, 'hand' : place_handle}) self.invalid_place_references.add(key) @@ -1333,7 +1333,7 @@ class CheckIntegrity(object): self.commit_place, self.trans) logging.warning(' FAIL: the event "%(gid)s" refers ' 'to an LdsOrd place "%(hand)s" which ' - 'does not exist in the database' % + 'does not exist in the database' % {'gid' : event.gramps_id, 'hand' : place_handle}) self.invalid_place_references.add(key) @@ -1342,7 +1342,7 @@ class CheckIntegrity(object): logging.info(' OK: no place reference problems found') def check_citation_references(self): - known_handles = [handle2internal(key) for key in + known_handles = [handle2internal(key) for key in self.db.get_citation_handles()] total = ( @@ -1521,13 +1521,13 @@ class CheckIntegrity(object): logging.info(' OK: no source reference problems found') def check_media_references(self): - known_handles = [handle2internal(key) for key in + known_handles = [handle2internal(key) for key in self.db.get_media_object_handles(False)] total = ( - self.db.get_number_of_people() + + self.db.get_number_of_people() + self.db.get_number_of_families() + - self.db.get_number_of_events() + + self.db.get_number_of_events() + self.db.get_number_of_places() + self.db.get_number_of_citations() + self.db.get_number_of_sources() @@ -1536,7 +1536,7 @@ class CheckIntegrity(object): self.progress.set_pass(_('Looking for media object reference problems'), total) logging.info('Looking for media object reference problems') - + for bhandle in self.db.person_map.keys(): handle = handle2internal(bhandle) self.progress.step() @@ -1587,7 +1587,7 @@ class CheckIntegrity(object): self.invalid_media_references.add(new_handle) elif item[1] not in known_handles: self.invalid_media_references.add(item[1]) - + for bhandle in self.db.event_map.keys(): handle = handle2internal(bhandle) self.progress.step() @@ -1604,7 +1604,7 @@ class CheckIntegrity(object): self.invalid_media_references.add(new_handle) elif item[1] not in known_handles: self.invalid_media_references.add(item[1]) - + for bhandle in self.db.citation_map.keys(): handle = handle2internal(bhandle) self.progress.step() @@ -1661,14 +1661,14 @@ class CheckIntegrity(object): if missing_references: self.db.add_note(self.explanation, self.trans, set_gid=True) - known_handles = [handle2internal(key) for key in + known_handles = [handle2internal(key) for key in self.db.get_note_handles()] bad_handles = [] total = ( - self.db.get_number_of_people() + + self.db.get_number_of_people() + self.db.get_number_of_families() + - self.db.get_number_of_events() + + self.db.get_number_of_events() + self.db.get_number_of_places() + self.db.get_number_of_media_objects() + self.db.get_number_of_citations() + @@ -1679,7 +1679,7 @@ class CheckIntegrity(object): self.progress.set_pass(_('Looking for note reference problems'), total) logging.info('Looking for note reference problems') - + for bhandle in self.db.person_map.keys(): handle = handle2internal(bhandle) self.progress.step() @@ -1841,7 +1841,7 @@ class CheckIntegrity(object): self.db.commit_media_object(obj, self.trans) def check_tag_references(self): - known_handles = [handle2internal(key) for key in + known_handles = [handle2internal(key) for key in self.db.get_tag_handles()] total = ( @@ -1976,12 +1976,12 @@ class CheckIntegrity(object): 'reference with a source citation ' 'which is invalid' % (source.gramps_id)) self.db.add_citation(new_citation, self.trans) - + new_citation_list.append(citation_handle) - + media_ref.set_citation_list(new_citation_list) new_media_ref_list.append(media_ref) - + source.set_media_list(new_media_ref_list) self.db.commit_source(source, self.trans) @@ -2104,7 +2104,7 @@ class CheckIntegrity(object): note_references + tag_references + name_format + empty_objs + invalid_dates + source_references ) - + if errors == 0: if uistate: OkDialog(_("No errors were found"), @@ -2203,7 +2203,7 @@ class CheckIntegrity(object): if rel: self.text.write( # translators: leave all/any {...} untranslated - ngettext("{quantity} corrupted family relationship fixed\n", + ngettext("{quantity} corrupted family relationship fixed\n", "{quantity} corrupted family relationships fixed\n", rel).format(quantity=rel) ) @@ -2212,29 +2212,29 @@ class CheckIntegrity(object): self.text.write( # translators: leave all/any {...} untranslated ngettext( - "{quantity} person was referenced but not found\n", - "{quantity} persons were referenced, but not found\n", + "{quantity} person was referenced but not found\n", + "{quantity} persons were referenced, but not found\n", person_references).format(quantity=person_references) ) - + if family_references: self.text.write( # translators: leave all/any {...} untranslated ngettext("{quantity} family was " - "referenced but not found\n", + "referenced but not found\n", "{quantity} families were " - "referenced, but not found\n", + "referenced, but not found\n", family_references).format(quantity=family_references) ) - + if invalid_dates: self.text.write( # translators: leave all/any {...} untranslated - ngettext("{quantity} date was corrected\n", - "{quantity} dates were corrected\n", + ngettext("{quantity} date was corrected\n", + "{quantity} dates were corrected\n", invalid_dates).format(quantity=invalid_dates) ) - + if repo_references: self.text.write( # translators: leave all/any {...} untranslated @@ -2403,7 +2403,7 @@ class CheckIntegrity(object): " %(place)d place objects\n" " %(repo)d repository objects\n" " %(note)d note objects\n") % { - 'empty_obj' : empty_objs, + 'empty_obj' : empty_objs, 'person' : len(self.empty_objects['persons']), 'family' : len(self.empty_objects['families']), 'event' : len(self.empty_objects['events']), @@ -2449,7 +2449,7 @@ class Report(ManagedWindow): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class CheckOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/dateparserdisplaytest.py b/gramps/plugins/tool/dateparserdisplaytest.py index 92661c1da..e22887033 100644 --- a/gramps/plugins/tool/dateparserdisplaytest.py +++ b/gramps/plugins/tool/dateparserdisplaytest.py @@ -130,7 +130,7 @@ class DateParserDisplayTest(tool.Tool): "This is a textual date") dates.append( d) self.progress.step() - + # test invalid dates #dateval = (4,7,1789,False,5,8,1876,False) #for l in range(1,len(dateval)): @@ -177,7 +177,7 @@ class DateParserDisplayTest(tool.Tool): # Date.CAL_GREGORIAN, # (4,7,1789,False,5,88,1876,False),"Text comment") #dates.append( d) - + with DbTxn(_("Date Test Plugin"), self.db, batch=True) as self.trans: self.db.disable_signals() self.progress.set_pass(_('Generating dates'), @@ -227,7 +227,7 @@ class DateParserDisplayTest(tool.Tool): ndate = Date() ndate.set_as_text("DateDisplay Exception: %s" % ("".join(traceback.format_exception(*sys.exc_info())),)) person.add_tag(fail_handle) - + if dateval.get_modifier() != Date.MOD_TEXTONLY \ and ndate.get_modifier() == Date.MOD_TEXTONLY: # parser was unable to correctly parse the string @@ -237,7 +237,7 @@ class DateParserDisplayTest(tool.Tool): and dateval.get_text().count("Traceback") \ and pass_handle in person.get_tag_list(): person.add_tag(fail_handle) - + devent = Event() devent.set_type(EventType.DEATH) devent.set_date_object(ndate) diff --git a/gramps/plugins/tool/dumpgenderstats.py b/gramps/plugins/tool/dumpgenderstats.py index 8c505301e..1be4712d8 100644 --- a/gramps/plugins/tool/dumpgenderstats.py +++ b/gramps/plugins/tool/dumpgenderstats.py @@ -21,7 +21,7 @@ # """ Dump Gender Statistics. - + Tools/Debug/Dump Gender Statistics """ from gramps.gen.const import GRAMPS_LOCALE as glocale @@ -40,7 +40,7 @@ _GENDER = [ _('female'), _('male'), _('unknown') ] # #------------------------------------------------------------------------- class DumpGenderStats(tool.Tool, ManagedWindow): - + def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate self.label = _("Gender Statistics tool") @@ -65,12 +65,12 @@ class DumpGenderStats(tool.Tool, ManagedWindow): (_('Unknown'),3,70,INTEGER), (_('Guess'),4,70) ] - + treeview = Gtk.TreeView() model = ListModel(treeview, titles) for entry in stats_list: model.add(entry, entry[0]) - + window = Gtk.Window() window.set_default_size(400, 300) s = Gtk.ScrolledWindow() @@ -79,7 +79,7 @@ class DumpGenderStats(tool.Tool, ManagedWindow): window.show_all() self.set_window(window, None, self.label) self.show() - + else: print('\t%s'*5 % ('Name','Male','Female','Unknown','Guess')) print() @@ -88,10 +88,10 @@ class DumpGenderStats(tool.Tool, ManagedWindow): def build_menu_names(self, obj): return (self.label,None) - + #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class DumpGenderStatsOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/eventnames.py b/gramps/plugins/tool/eventnames.py index a9b8d9e83..4f7746e1f 100644 --- a/gramps/plugins/tool/eventnames.py +++ b/gramps/plugins/tool/eventnames.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -57,12 +57,12 @@ from gramps.gen.display.name import displayer as name_displayer #------------------------------------------------------------------------- class EventNames(tool.BatchTool): """ - Look for events that do not have a description, and build the description - from the item that contains it. - - Looks for a PRIMARY role type for events attached to a persons, and a + Look for events that do not have a description, and build the description + from the item that contains it. + + Looks for a PRIMARY role type for events attached to a persons, and a FAMILY role for an event that is attached to a family. - + """ def __init__(self, dbstate, user, options_class, name, callback=None): @@ -80,7 +80,7 @@ class EventNames(tool.BatchTool): self.db.disable_signals() self.change = False counter = 0 - + with self.user.progress( _("Extract Event Description"), '', 2) as step: @@ -113,12 +113,12 @@ class EventNames(tool.BatchTool): if self.change == True: # translators: leave all/any {...} untranslated - message = ngettext("{quantity} event description has been added", + message = ngettext("{quantity} event description has been added", "{quantity} event descriptions have been added", counter).format(quantity=counter) self.user.info(_('Modifications made'), message) else: - self.user.info(_('No modifications made'), + self.user.info(_('No modifications made'), _("No event description has been added.")) #------------------------------------------------------------------------- @@ -138,8 +138,8 @@ def person_event_name(event, person): """ if not event.get_description(): text = EVENT_PERSON_STR % { - 'event_name' : str(event.get_type()), - 'person' : name_displayer.display(person), + 'event_name' : str(event.get_type()), + 'person' : name_displayer.display(person), } event.set_description(text) @@ -149,14 +149,14 @@ def family_event_name(event, family, dbase): """ if not event.get_description(): text = EVENT_FAMILY_STR % { - 'event_name' : str(event.get_type()), - 'family' : family_name(family, dbase), + 'event_name' : str(event.get_type()), + 'family' : family_name(family, dbase), } event.set_description(text) - + #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class EventNamesOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/extractcity.py b/gramps/plugins/tool/extractcity.py index 87dbe5be8..f2ff7c446 100644 --- a/gramps/plugins/tool/extractcity.py +++ b/gramps/plugins/tool/extractcity.py @@ -11,7 +11,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -65,238 +65,238 @@ STATE_ZIP = re.compile("(.+)\s+([\d-]+)", re.UNICODE) COUNTRY = ( _("United States of America"), _("Canada"), _("France"),_("Sweden")) STATE_MAP = { - "AL" : ("Alabama", 0), - "AL." : ("Alabama", 0), - "ALABAMA" : ("Alabama", 0), - "AK" : ("Alaska" , 0), - "AK." : ("Alaska" , 0), - "ALASKA" : ("Alaska" , 0), - "AS" : ("American Samoa", 0), - "AS." : ("American Samoa", 0), - "AMERICAN SAMOA": ("American Samoa", 0), - "AZ" : ("Arizona", 0), - "AZ." : ("Arizona", 0), - "ARIZONA" : ("Arizona", 0), - "AR" : ("Arkansas" , 0), - "AR." : ("Arkansas" , 0), - "ARKANSAS" : ("Arkansas" , 0), - "ARK." : ("Arkansas" , 0), - "ARK" : ("Arkansas" , 0), - "CA" : ("California" , 0), - "CA." : ("California" , 0), - "CALIFORNIA" : ("California" , 0), - "CO" : ("Colorado" , 0), - "COLO" : ("Colorado" , 0), - "COLO." : ("Colorado" , 0), - "COLORADO" : ("Colorado" , 0), - "CT" : ("Connecticut" , 0), - "CT." : ("Connecticut" , 0), - "CONNECTICUT" : ("Connecticut" , 0), - "DE" : ("Delaware" , 0), - "DE." : ("Delaware" , 0), - "DELAWARE" : ("Delaware" , 0), - "DC" : ("District of Columbia" , 0), - "D.C." : ("District of Columbia" , 0), - "DC." : ("District of Columbia" , 0), - "DISTRICT OF COLUMBIA" : ("District of Columbia" , 0), - "FL" : ("Florida" , 0), - "FL." : ("Florida" , 0), - "FLA" : ("Florida" , 0), - "FLA." : ("Florida" , 0), - "FLORIDA" : ("Florida" , 0), - "GA" : ("Georgia" , 0), - "GA." : ("Georgia" , 0), - "GEORGIA" : ("Georgia" , 0), - "GU" : ("Guam" , 0), - "GU." : ("Guam" , 0), - "GUAM" : ("Guam" , 0), - "HI" : ("Hawaii" , 0), - "HI." : ("Hawaii" , 0), - "HAWAII" : ("Hawaii" , 0), - "ID" : ("Idaho" , 0), - "ID." : ("Idaho" , 0), - "IDAHO" : ("Idaho" , 0), - "IL" : ("Illinois" , 0), - "IL." : ("Illinois" , 0), - "ILLINOIS" : ("Illinois" , 0), - "ILL" : ("Illinois" , 0), - "ILL." : ("Illinois" , 0), - "ILLS" : ("Illinois" , 0), - "ILLS." : ("Illinois" , 0), - "IN" : ("Indiana" , 0), - "IN." : ("Indiana" , 0), - "INDIANA" : ("Indiana" , 0), - "IA" : ("Iowa" , 0), - "IA." : ("Iowa" , 0), - "IOWA" : ("Iowa" , 0), - "KS" : ("Kansas" , 0), - "KS." : ("Kansas" , 0), - "KANSAS" : ("Kansas" , 0), - "KY" : ("Kentucky" , 0), - "KY." : ("Kentucky" , 0), - "KENTUCKY" : ("Kentucky" , 0), - "LA" : ("Louisiana" , 0), - "LA." : ("Louisiana" , 0), - "LOUISIANA" : ("Louisiana" , 0), - "ME" : ("Maine" , 0), - "ME." : ("Maine" , 0), - "MAINE" : ("Maine" , 0), - "MD" : ("Maryland" , 0), - "MD." : ("Maryland" , 0), - "MARYLAND" : ("Maryland" , 0), - "MA" : ("Massachusetts" , 0), - "MA." : ("Massachusetts" , 0), - "MASSACHUSETTS" : ("Massachusetts" , 0), - "MI" : ("Michigan" , 0), - "MI." : ("Michigan" , 0), - "MICH." : ("Michigan" , 0), - "MICH" : ("Michigan" , 0), - "MN" : ("Minnesota" , 0), - "MN." : ("Minnesota" , 0), - "MINNESOTA" : ("Minnesota" , 0), - "MS" : ("Mississippi" , 0), - "MS." : ("Mississippi" , 0), - "MISSISSIPPI" : ("Mississippi" , 0), - "MO" : ("Missouri" , 0), - "MO." : ("Missouri" , 0), - "MISSOURI" : ("Missouri" , 0), - "MT" : ("Montana" , 0), - "MT." : ("Montana" , 0), - "MONTANA" : ("Montana" , 0), - "NE" : ("Nebraska" , 0), - "NE." : ("Nebraska" , 0), - "NEBRASKA" : ("Nebraska" , 0), - "NV" : ("Nevada" , 0), - "NV." : ("Nevada" , 0), - "NEVADA" : ("Nevada" , 0), - "NH" : ("New Hampshire" , 0), - "NH." : ("New Hampshire" , 0), - "N.H." : ("New Hampshire" , 0), - "NEW HAMPSHIRE" : ("New Hampshire" , 0), - "NJ" : ("New Jersey" , 0), - "NJ." : ("New Jersey" , 0), - "N.J." : ("New Jersey" , 0), - "NEW JERSEY" : ("New Jersey" , 0), - "NM" : ("New Mexico" , 0), - "NM." : ("New Mexico" , 0), - "NEW MEXICO" : ("New Mexico" , 0), - "NY" : ("New York" , 0), - "N.Y." : ("New York" , 0), - "NY." : ("New York" , 0), - "NEW YORK" : ("New York" , 0), - "NC" : ("North Carolina" , 0), - "NC." : ("North Carolina" , 0), - "N.C." : ("North Carolina" , 0), - "NORTH CAROLINA": ("North Carolina" , 0), - "ND" : ("North Dakota" , 0), - "ND." : ("North Dakota" , 0), - "N.D." : ("North Dakota" , 0), - "NORTH DAKOTA" : ("North Dakota" , 0), - "OH" : ("Ohio" , 0), - "OH." : ("Ohio" , 0), - "OHIO" : ("Ohio" , 0), - "OK" : ("Oklahoma" , 0), - "OKLA" : ("Oklahoma" , 0), - "OKLA." : ("Oklahoma" , 0), - "OK." : ("Oklahoma" , 0), - "OKLAHOMA" : ("Oklahoma" , 0), - "OR" : ("Oregon" , 0), - "OR." : ("Oregon" , 0), - "OREGON" : ("Oregon" , 0), - "PA" : ("Pennsylvania" , 0), - "PA." : ("Pennsylvania" , 0), - "PENNSYLVANIA" : ("Pennsylvania" , 0), - "PR" : ("Puerto Rico" , 0), - "PUERTO RICO" : ("Puerto Rico" , 0), - "RI" : ("Rhode Island" , 0), - "RI." : ("Rhode Island" , 0), - "R.I." : ("Rhode Island" , 0), - "RHODE ISLAND" : ("Rhode Island" , 0), - "SC" : ("South Carolina" , 0), - "SC." : ("South Carolina" , 0), - "S.C." : ("South Carolina" , 0), - "SOUTH CAROLINA": ("South Carolina" , 0), - "SD" : ("South Dakota" , 0), - "SD." : ("South Dakota" , 0), - "S.D." : ("South Dakota" , 0), - "SOUTH DAKOTA" : ("South Dakota" , 0), - "TN" : ("Tennessee" , 0), - "TN." : ("Tennessee" , 0), - "TENNESSEE" : ("Tennessee" , 0), - "TENN." : ("Tennessee" , 0), - "TENN" : ("Tennessee" , 0), - "TX" : ("Texas" , 0), - "TX." : ("Texas" , 0), - "TEXAS" : ("Texas" , 0), - "UT" : ("Utah" , 0), - "UT." : ("Utah" , 0), - "UTAH" : ("Utah" , 0), - "VT" : ("Vermont" , 0), - "VT." : ("Vermont" , 0), - "VERMONT" : ("Vermont" , 0), - "VI" : ("Virgin Islands" , 0), - "VIRGIN ISLANDS": ("Virgin Islands" , 0), - "VA" : ("Virginia" , 0), - "VA." : ("Virginia" , 0), - "VIRGINIA" : ("Virginia" , 0), - "WA" : ("Washington" , 0), - "WA." : ("Washington" , 0), - "WASHINGTON" : ("Washington" , 0), - "WV" : ("West Virginia" , 0), - "WV." : ("West Virginia" , 0), - "W.V." : ("West Virginia" , 0), - "WEST VIRGINIA" : ("West Virginia" , 0), - "WI" : ("Wisconsin" , 0), - "WI." : ("Wisconsin" , 0), - "WISCONSIN" : ("Wisconsin" , 0), - "WY" : ("Wyoming" , 0), - "WY." : ("Wyoming" , 0), - "WYOMING" : ("Wyoming" , 0), - "AB" : ("Alberta", 1), - "AB." : ("Alberta", 1), - "ALBERTA" : ("Alberta", 1), - "BC" : ("British Columbia", 1), - "BC." : ("British Columbia", 1), - "B.C." : ("British Columbia", 1), - "MB" : ("Manitoba", 1), - "MB." : ("Manitoba", 1), - "MANITOBA" : ("Manitoba", 1), - "NB" : ("New Brunswick", 1), - "N.B." : ("New Brunswick", 1), - "NB." : ("New Brunswick", 1), - "NEW BRUNSWICK" : ("New Brunswick", 1), - "NL" : ("Newfoundland and Labrador", 1), - "NL." : ("Newfoundland and Labrador", 1), - "N.L." : ("Newfoundland and Labrador", 1), - "NEWFOUNDLAND" : ("Newfoundland and Labrador", 1), - "NEWFOUNDLAND AND LABRADOR" : ("Newfoundland and Labrador", 1), - "LABRADOR" : ("Newfoundland and Labrador", 1), - "NT" : ("Northwest Territories", 1), - "NT." : ("Northwest Territories", 1), - "N.T." : ("Northwest Territories", 1), - "NORTHWEST TERRITORIES" : ("Northwest Territories", 1), - "NS" : ("Nova Scotia", 1), - "NS." : ("Nova Scotia", 1), - "N.S." : ("Nova Scotia", 1), - "NOVA SCOTIA" : ("Nova Scotia", 1), - "NU" : ("Nunavut", 1), - "NU." : ("Nunavut", 1), - "NUNAVUT" : ("Nunavut", 1), - "ON" : ("Ontario", 1), - "ON." : ("Ontario", 1), - "ONTARIO" : ("Ontario", 1), - "PE" : ("Prince Edward Island", 1), - "PE." : ("Prince Edward Island", 1), - "PRINCE EDWARD ISLAND" : ("Prince Edward Island", 1), - "QC" : ("Quebec", 1), - "QC." : ("Quebec", 1), - "QUEBEC" : ("Quebec", 1), - "SK" : ("Saskatchewan", 1), - "SK." : ("Saskatchewan", 1), - "SASKATCHEWAN" : ("Saskatchewan", 1), - "YT" : ("Yukon", 1), - "YT." : ("Yukon", 1), - "YUKON" : ("Yukon", 1), + "AL" : ("Alabama", 0), + "AL." : ("Alabama", 0), + "ALABAMA" : ("Alabama", 0), + "AK" : ("Alaska" , 0), + "AK." : ("Alaska" , 0), + "ALASKA" : ("Alaska" , 0), + "AS" : ("American Samoa", 0), + "AS." : ("American Samoa", 0), + "AMERICAN SAMOA": ("American Samoa", 0), + "AZ" : ("Arizona", 0), + "AZ." : ("Arizona", 0), + "ARIZONA" : ("Arizona", 0), + "AR" : ("Arkansas" , 0), + "AR." : ("Arkansas" , 0), + "ARKANSAS" : ("Arkansas" , 0), + "ARK." : ("Arkansas" , 0), + "ARK" : ("Arkansas" , 0), + "CA" : ("California" , 0), + "CA." : ("California" , 0), + "CALIFORNIA" : ("California" , 0), + "CO" : ("Colorado" , 0), + "COLO" : ("Colorado" , 0), + "COLO." : ("Colorado" , 0), + "COLORADO" : ("Colorado" , 0), + "CT" : ("Connecticut" , 0), + "CT." : ("Connecticut" , 0), + "CONNECTICUT" : ("Connecticut" , 0), + "DE" : ("Delaware" , 0), + "DE." : ("Delaware" , 0), + "DELAWARE" : ("Delaware" , 0), + "DC" : ("District of Columbia" , 0), + "D.C." : ("District of Columbia" , 0), + "DC." : ("District of Columbia" , 0), + "DISTRICT OF COLUMBIA" : ("District of Columbia" , 0), + "FL" : ("Florida" , 0), + "FL." : ("Florida" , 0), + "FLA" : ("Florida" , 0), + "FLA." : ("Florida" , 0), + "FLORIDA" : ("Florida" , 0), + "GA" : ("Georgia" , 0), + "GA." : ("Georgia" , 0), + "GEORGIA" : ("Georgia" , 0), + "GU" : ("Guam" , 0), + "GU." : ("Guam" , 0), + "GUAM" : ("Guam" , 0), + "HI" : ("Hawaii" , 0), + "HI." : ("Hawaii" , 0), + "HAWAII" : ("Hawaii" , 0), + "ID" : ("Idaho" , 0), + "ID." : ("Idaho" , 0), + "IDAHO" : ("Idaho" , 0), + "IL" : ("Illinois" , 0), + "IL." : ("Illinois" , 0), + "ILLINOIS" : ("Illinois" , 0), + "ILL" : ("Illinois" , 0), + "ILL." : ("Illinois" , 0), + "ILLS" : ("Illinois" , 0), + "ILLS." : ("Illinois" , 0), + "IN" : ("Indiana" , 0), + "IN." : ("Indiana" , 0), + "INDIANA" : ("Indiana" , 0), + "IA" : ("Iowa" , 0), + "IA." : ("Iowa" , 0), + "IOWA" : ("Iowa" , 0), + "KS" : ("Kansas" , 0), + "KS." : ("Kansas" , 0), + "KANSAS" : ("Kansas" , 0), + "KY" : ("Kentucky" , 0), + "KY." : ("Kentucky" , 0), + "KENTUCKY" : ("Kentucky" , 0), + "LA" : ("Louisiana" , 0), + "LA." : ("Louisiana" , 0), + "LOUISIANA" : ("Louisiana" , 0), + "ME" : ("Maine" , 0), + "ME." : ("Maine" , 0), + "MAINE" : ("Maine" , 0), + "MD" : ("Maryland" , 0), + "MD." : ("Maryland" , 0), + "MARYLAND" : ("Maryland" , 0), + "MA" : ("Massachusetts" , 0), + "MA." : ("Massachusetts" , 0), + "MASSACHUSETTS" : ("Massachusetts" , 0), + "MI" : ("Michigan" , 0), + "MI." : ("Michigan" , 0), + "MICH." : ("Michigan" , 0), + "MICH" : ("Michigan" , 0), + "MN" : ("Minnesota" , 0), + "MN." : ("Minnesota" , 0), + "MINNESOTA" : ("Minnesota" , 0), + "MS" : ("Mississippi" , 0), + "MS." : ("Mississippi" , 0), + "MISSISSIPPI" : ("Mississippi" , 0), + "MO" : ("Missouri" , 0), + "MO." : ("Missouri" , 0), + "MISSOURI" : ("Missouri" , 0), + "MT" : ("Montana" , 0), + "MT." : ("Montana" , 0), + "MONTANA" : ("Montana" , 0), + "NE" : ("Nebraska" , 0), + "NE." : ("Nebraska" , 0), + "NEBRASKA" : ("Nebraska" , 0), + "NV" : ("Nevada" , 0), + "NV." : ("Nevada" , 0), + "NEVADA" : ("Nevada" , 0), + "NH" : ("New Hampshire" , 0), + "NH." : ("New Hampshire" , 0), + "N.H." : ("New Hampshire" , 0), + "NEW HAMPSHIRE" : ("New Hampshire" , 0), + "NJ" : ("New Jersey" , 0), + "NJ." : ("New Jersey" , 0), + "N.J." : ("New Jersey" , 0), + "NEW JERSEY" : ("New Jersey" , 0), + "NM" : ("New Mexico" , 0), + "NM." : ("New Mexico" , 0), + "NEW MEXICO" : ("New Mexico" , 0), + "NY" : ("New York" , 0), + "N.Y." : ("New York" , 0), + "NY." : ("New York" , 0), + "NEW YORK" : ("New York" , 0), + "NC" : ("North Carolina" , 0), + "NC." : ("North Carolina" , 0), + "N.C." : ("North Carolina" , 0), + "NORTH CAROLINA": ("North Carolina" , 0), + "ND" : ("North Dakota" , 0), + "ND." : ("North Dakota" , 0), + "N.D." : ("North Dakota" , 0), + "NORTH DAKOTA" : ("North Dakota" , 0), + "OH" : ("Ohio" , 0), + "OH." : ("Ohio" , 0), + "OHIO" : ("Ohio" , 0), + "OK" : ("Oklahoma" , 0), + "OKLA" : ("Oklahoma" , 0), + "OKLA." : ("Oklahoma" , 0), + "OK." : ("Oklahoma" , 0), + "OKLAHOMA" : ("Oklahoma" , 0), + "OR" : ("Oregon" , 0), + "OR." : ("Oregon" , 0), + "OREGON" : ("Oregon" , 0), + "PA" : ("Pennsylvania" , 0), + "PA." : ("Pennsylvania" , 0), + "PENNSYLVANIA" : ("Pennsylvania" , 0), + "PR" : ("Puerto Rico" , 0), + "PUERTO RICO" : ("Puerto Rico" , 0), + "RI" : ("Rhode Island" , 0), + "RI." : ("Rhode Island" , 0), + "R.I." : ("Rhode Island" , 0), + "RHODE ISLAND" : ("Rhode Island" , 0), + "SC" : ("South Carolina" , 0), + "SC." : ("South Carolina" , 0), + "S.C." : ("South Carolina" , 0), + "SOUTH CAROLINA": ("South Carolina" , 0), + "SD" : ("South Dakota" , 0), + "SD." : ("South Dakota" , 0), + "S.D." : ("South Dakota" , 0), + "SOUTH DAKOTA" : ("South Dakota" , 0), + "TN" : ("Tennessee" , 0), + "TN." : ("Tennessee" , 0), + "TENNESSEE" : ("Tennessee" , 0), + "TENN." : ("Tennessee" , 0), + "TENN" : ("Tennessee" , 0), + "TX" : ("Texas" , 0), + "TX." : ("Texas" , 0), + "TEXAS" : ("Texas" , 0), + "UT" : ("Utah" , 0), + "UT." : ("Utah" , 0), + "UTAH" : ("Utah" , 0), + "VT" : ("Vermont" , 0), + "VT." : ("Vermont" , 0), + "VERMONT" : ("Vermont" , 0), + "VI" : ("Virgin Islands" , 0), + "VIRGIN ISLANDS": ("Virgin Islands" , 0), + "VA" : ("Virginia" , 0), + "VA." : ("Virginia" , 0), + "VIRGINIA" : ("Virginia" , 0), + "WA" : ("Washington" , 0), + "WA." : ("Washington" , 0), + "WASHINGTON" : ("Washington" , 0), + "WV" : ("West Virginia" , 0), + "WV." : ("West Virginia" , 0), + "W.V." : ("West Virginia" , 0), + "WEST VIRGINIA" : ("West Virginia" , 0), + "WI" : ("Wisconsin" , 0), + "WI." : ("Wisconsin" , 0), + "WISCONSIN" : ("Wisconsin" , 0), + "WY" : ("Wyoming" , 0), + "WY." : ("Wyoming" , 0), + "WYOMING" : ("Wyoming" , 0), + "AB" : ("Alberta", 1), + "AB." : ("Alberta", 1), + "ALBERTA" : ("Alberta", 1), + "BC" : ("British Columbia", 1), + "BC." : ("British Columbia", 1), + "B.C." : ("British Columbia", 1), + "MB" : ("Manitoba", 1), + "MB." : ("Manitoba", 1), + "MANITOBA" : ("Manitoba", 1), + "NB" : ("New Brunswick", 1), + "N.B." : ("New Brunswick", 1), + "NB." : ("New Brunswick", 1), + "NEW BRUNSWICK" : ("New Brunswick", 1), + "NL" : ("Newfoundland and Labrador", 1), + "NL." : ("Newfoundland and Labrador", 1), + "N.L." : ("Newfoundland and Labrador", 1), + "NEWFOUNDLAND" : ("Newfoundland and Labrador", 1), + "NEWFOUNDLAND AND LABRADOR" : ("Newfoundland and Labrador", 1), + "LABRADOR" : ("Newfoundland and Labrador", 1), + "NT" : ("Northwest Territories", 1), + "NT." : ("Northwest Territories", 1), + "N.T." : ("Northwest Territories", 1), + "NORTHWEST TERRITORIES" : ("Northwest Territories", 1), + "NS" : ("Nova Scotia", 1), + "NS." : ("Nova Scotia", 1), + "N.S." : ("Nova Scotia", 1), + "NOVA SCOTIA" : ("Nova Scotia", 1), + "NU" : ("Nunavut", 1), + "NU." : ("Nunavut", 1), + "NUNAVUT" : ("Nunavut", 1), + "ON" : ("Ontario", 1), + "ON." : ("Ontario", 1), + "ONTARIO" : ("Ontario", 1), + "PE" : ("Prince Edward Island", 1), + "PE." : ("Prince Edward Island", 1), + "PRINCE EDWARD ISLAND" : ("Prince Edward Island", 1), + "QC" : ("Quebec", 1), + "QC." : ("Quebec", 1), + "QUEBEC" : ("Quebec", 1), + "SK" : ("Saskatchewan", 1), + "SK." : ("Saskatchewan", 1), + "SASKATCHEWAN" : ("Saskatchewan", 1), + "YT" : ("Yukon", 1), + "YT." : ("Yukon", 1), + "YUKON" : ("Yukon", 1), "ALSACE" : ("Alsace", 2), "ALS" : ("ALS-Alsace", 2), "AQUITAINE" : ("Aquitaine", 2), @@ -342,15 +342,15 @@ STATE_MAP = { "RHONE-ALPES" : ("Rhône-Alpes", 2), "RAL" : ("RAL-Rhône-Alpes", 2), "AOM" : ("AOM-Autres Territoires d'Outre-Mer", 2), - "COM" : ("COM-Collectivité Territoriale d'Outre-Mer", 2), - "DOM" : ("DOM-Départements d'Outre-Mer", 2), + "COM" : ("COM-Collectivité Territoriale d'Outre-Mer", 2), + "DOM" : ("DOM-Départements d'Outre-Mer", 2), "TOM" : ("TOM-Territoires d'Outre-Mer", 2), "GUA" : ("GUA-Guadeloupe", 2), "GUADELOUPE" : ("Guadeloupe", 2), "MAR" : ("MAR-Martinique", 2), - "MARTINIQUE" : ("Martinique", 2), + "MARTINIQUE" : ("Martinique", 2), "GUY" : ("GUY-Guyane", 2), - "GUYANE" : ("Guyane", 2), + "GUYANE" : ("Guyane", 2), "REU" : ("REU-Réunion", 2), "REUNION" : ("Réunion", 2), "MIQ" : ("MIQ-Saint-Pierre et Miquelon", 2), @@ -384,11 +384,11 @@ STATE_MAP = { "(BD)" : ("Norrbottens län", 3), } -COLS = [ - (_('Place title'), 1), - (_('City'), 2), - (_('State'), 3), - (_('ZIP/Postal Code'), 4), +COLS = [ + (_('Place title'), 1), + (_('City'), 2), + (_('State'), 3), + (_('ZIP/Postal Code'), 4), (_('Country'), 5) ] @@ -417,7 +417,7 @@ class ExtractCity(tool.BatchTool, ManagedWindow): def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate self.label = _('Extract Place data') - + ManagedWindow.__init__(self, uistate, [], self.__class__) self.set_window(Gtk.Window(), Gtk.Label(), '') @@ -434,7 +434,7 @@ class ExtractCity(tool.BatchTool, ManagedWindow): """ self.progress = ProgressMeter(_('Checking Place Titles'), '') - self.progress.set_pass(_('Looking for place fields'), + self.progress.set_pass(_('Looking for place fields'), self.db.get_number_of_places()) self.name_list = [] @@ -452,23 +452,23 @@ class ExtractCity(tool.BatchTool, ManagedWindow): (loc.get(PlaceType.COUNTY, '')), (loc.get(PlaceType.STATE, '')), (loc.get(PlaceType.COUNTRY, ''))) - self.place_import.store_location(location, place.handle) + self.place_import.store_location(location, place.handle) if len(place.get_placeref_list()) == 0: match = CITY_STATE_ZIP.match(descr.strip()) if match: data = match.groups() - city = data[0] + city = data[0] state = data[2] postal = data[5] - + val = " ".join(state.strip().split()).upper() if state: new_state = STATE_MAP.get(val.upper()) if new_state: self.name_list.append( - (place.handle, (city, new_state[0], postal, + (place.handle, (city, new_state[0], postal, COUNTRY[new_state[1]]))) continue @@ -476,7 +476,7 @@ class ExtractCity(tool.BatchTool, ManagedWindow): match = CITY_LAEN.match(descr.strip().replace(","," ")) if match: data = match.groups() - city = data[0] + city = data[0] state = '(' + data[1] + ')' postal = None val = " ".join(state.strip().split()).upper() @@ -484,26 +484,26 @@ class ExtractCity(tool.BatchTool, ManagedWindow): new_state = STATE_MAP.get(val.upper()) if new_state: self.name_list.append( - (place.handle, (city, new_state[0], postal, + (place.handle, (city, new_state[0], postal, COUNTRY[new_state[1]]))) continue match = CITY_STATE.match(descr.strip()) if match: data = match.groups() - city = data[0] + city = data[0] state = data[1] postal = None if state: m0 = STATE_ZIP.match(state) if m0: - (state, postal) = m0.groups() + (state, postal) = m0.groups() val = " ".join(state.strip().split()).upper() if state: new_state = STATE_MAP.get(val.upper()) if new_state: self.name_list.append( - (place.handle, (city, new_state[0], postal, + (place.handle, (city, new_state[0], postal, COUNTRY[new_state[1]]))) continue @@ -511,7 +511,7 @@ class ExtractCity(tool.BatchTool, ManagedWindow): new_state = STATE_MAP.get(val) if new_state: self.name_list.append( - (place.handle, (None, new_state[0], None, + (place.handle, (None, new_state[0], None, COUNTRY[new_state[1]]))) self.progress.close() @@ -520,7 +520,7 @@ class ExtractCity(tool.BatchTool, ManagedWindow): else: self.close() from gramps.gui.dialog import OkDialog - OkDialog(_('No modifications made'), + OkDialog(_('No modifications made'), _("No place information could be extracted.")) def display(self): @@ -528,12 +528,12 @@ class ExtractCity(tool.BatchTool, ManagedWindow): self.top = Glade("changenames.glade") window = self.top.toplevel self.top.connect_signals({ - "destroy_passed_object" : self.close, - "on_ok_clicked" : self.on_ok_clicked, - "on_help_clicked" : self.on_help_clicked, + "destroy_passed_object" : self.close, + "on_ok_clicked" : self.on_ok_clicked, + "on_help_clicked" : self.on_help_clicked, "on_delete_event" : self.close, }) - + self.list = self.top.get_object("list") self.set_window(window, self.top.get_object('title'), self.label) lbl = self.top.get_object('info') @@ -543,9 +543,9 @@ class ExtractCity(tool.BatchTool, ManagedWindow): 'be extracted from the place title. Select the places you ' 'wish Gramps to convert.')) - self.model = Gtk.ListStore(GObject.TYPE_BOOLEAN, GObject.TYPE_STRING, - GObject.TYPE_STRING, GObject.TYPE_STRING, - GObject.TYPE_STRING, GObject.TYPE_STRING, + self.model = Gtk.ListStore(GObject.TYPE_BOOLEAN, GObject.TYPE_STRING, + GObject.TYPE_STRING, GObject.TYPE_STRING, + GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) r = Gtk.CellRendererToggle() @@ -558,7 +558,7 @@ class ExtractCity(tool.BatchTool, ManagedWindow): if col > 1: render.set_property('editable', True) render.connect('edited', self.__change_name, col) - + self.list.append_column( Gtk.TreeViewColumn(title, render, text=col)) self.list.set_model(self.model) @@ -585,7 +585,7 @@ class ExtractCity(tool.BatchTool, ManagedWindow): self.iter_list.append(handle) self.progress.step() self.progress.close() - + self.show() def __change_name(self, text, path, new_text, col): @@ -627,10 +627,10 @@ class ExtractCity(tool.BatchTool, ManagedWindow): self.db.enable_signals() self.db.request_rebuild() self.close() - + #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class ExtractCityOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/finddupes.py b/gramps/plugins/tool/finddupes.py index 092492bc4..5692e18bd 100644 --- a/gramps/plugins/tool/finddupes.py +++ b/gramps/plugins/tool/finddupes.py @@ -85,10 +85,10 @@ def is_initial(name): # #------------------------------------------------------------------------- class Merge(tool.Tool,ManagedWindow): - + def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate - + tool.Tool.__init__(self, dbstate, options_class, name) ManagedWindow.__init__(self, uistate, [], self.__class__) @@ -116,7 +116,7 @@ class Merge(tool.Tool,ManagedWindow): self.soundex_obj = top.get_object("soundex") self.soundex_obj.set_active(use_soundex) self.soundex_obj.show() - + self.menu = top.get_object("menu") self.menu.set_model(my_menu) self.menu.set_active(0) @@ -143,7 +143,7 @@ class Merge(tool.Tool,ManagedWindow): def on_help_clicked(self, obj): """Display the relevant portion of GRAMPS manual""" - + display_help(WIKI_HELP_PAGE , WIKI_HELP_SEC) def ancestors_of(self, p1_id, id_list): @@ -182,7 +182,7 @@ class Merge(tool.Tool,ManagedWindow): self.list,self.map,self.update) except WindowActiveError: pass - + def find_potentials(self, thresh): self.progress = ProgressMeter(_('Find Duplicates'), _('Looking for duplicate people'), @@ -196,7 +196,7 @@ class Merge(tool.Tool,ManagedWindow): self.progress.set_pass(_('Pass 1: Building preliminary lists'), length) - + for p1_id in self.db.iter_person_handles(): self.progress.step() p1 = self.db.get_person_from_handle(p1_id) @@ -211,7 +211,7 @@ class Merge(tool.Tool,ManagedWindow): females[key].append(p1_id) else: females[key] = [p1_id] - + self.progress.set_pass(_('Pass 2: Calculating potential matches'), length) @@ -235,7 +235,7 @@ class Merge(tool.Tool,ManagedWindow): (v,c) = self.map[p2key] if v == p1key: continue - + chance = self.compare_people(p1,p2) if chance >= thresh: if p1key in self.map: @@ -298,19 +298,19 @@ class Merge(tool.Tool,ManagedWindow): chance += value value = self.date_match(death1.get_date_object(), - death2.get_date_object()) + death2.get_date_object()) if value == -1 : return -1 chance += value value = self.place_match(birth1.get_place_handle(), - birth2.get_place_handle()) + birth2.get_place_handle()) if value == -1 : return -1 chance += value value = self.place_match(death1.get_place_handle(), - death2.get_place_handle()) + death2.get_place_handle()) if value == -1 : return -1 chance += value @@ -324,7 +324,7 @@ class Merge(tool.Tool,ManagedWindow): self.ancestors_of(p2.get_handle(),ancestors) if p1.get_handle() in ancestors: return -1 - + f1_id = p1.get_main_parents_family_handle() f2_id = p2.get_main_parents_family_handle() @@ -341,14 +341,14 @@ class Merge(tool.Tool,ManagedWindow): dad2 = get_name_obj(self.db.get_person_from_handle(dad2_id)) else: dad2 = None - + value = self.name_match(dad1,dad2) - + if value == -1: return -1 chance += value - + mom1_id = f1.get_mother_handle() if mom1_id: mom1 = get_name_obj(self.db.get_person_from_handle(mom1_id)) @@ -363,7 +363,7 @@ class Merge(tool.Tool,ManagedWindow): value = self.name_match(mom1,mom2) if value == -1: return -1 - + chance += value for f1_id in p1.get_family_handle_list(): @@ -456,7 +456,7 @@ class Merge(tool.Tool,ManagedWindow): if not name1 or not name: return 0 - + srn1 = get_surnames(name) sfx1 = name.get_suffix() srn2 = get_surnames(name1) @@ -478,11 +478,11 @@ class Merge(tool.Tool,ManagedWindow): return self.list_reduce(list1,list2) else: return self.list_reduce(list2,list1) - + def place_match(self, p1_id, p2_id): if p1_id == p2_id: return 1 - + if not p1_id: name1 = "" else: @@ -494,7 +494,7 @@ class Merge(tool.Tool,ManagedWindow): else: p2 = self.db.get_place_from_handle(p2_id) name2 = p2.get_title() - + if not (name1 and name2): return 0 if name1 == name2: @@ -511,7 +511,7 @@ class Merge(tool.Tool,ManagedWindow): elif name[0] == name2[0] and self.name_compare(name, name2): value += 0.25 return min(value,1) if value else -1 - + def list_reduce(self, list1, list2): value = 0 for name in list1: @@ -531,7 +531,7 @@ class Merge(tool.Tool,ManagedWindow): both toplevel windows and all signals must be handled. """ pass - + class ShowMatches(ManagedWindow): @@ -546,12 +546,12 @@ class ShowMatches(ManagedWindow): self.db = dbstate.db self.dbstate = dbstate self.uistate = uistate - + top = Glade(toplevel="mergelist") window = top.toplevel self.set_window(window, top.get_object('title'), _('Potential Merges')) - + self.mlist = top.get_object("mlist") top.connect_signals({ "destroy_passed_object" : self.close, @@ -572,7 +572,7 @@ class ShowMatches(ManagedWindow): ] self.list = ListModel(self.mlist,mtitles, event_func=self.on_do_merge_clicked) - + self.redraw() self.show() @@ -581,8 +581,8 @@ class ShowMatches(ManagedWindow): def on_help_clicked(self, obj): """Display the relevant portion of GRAMPS manual""" - - display_help(WIKI_HELP_PAGE , WIKI_HELP_SEC) + + display_help(WIKI_HELP_PAGE , WIKI_HELP_SEC) def redraw(self): list = [] for p1key, p1data in self.map.items(): @@ -628,7 +628,7 @@ class ShowMatches(ManagedWindow): self.dellist[key] = phoenix self.update() self.redraw() - + def update_and_destroy(self, obj): self.update(1) self.close() @@ -638,7 +638,7 @@ class ShowMatches(ManagedWindow): both toplevel windows and all signals must be handled. """ pass - + #------------------------------------------------------------------------- # @@ -662,7 +662,7 @@ def get_surnames(name): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class MergeOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/mediamanager.py b/gramps/plugins/tool/mediamanager.py index 5355ce16b..3bee97ea0 100644 --- a/gramps/plugins/tool/mediamanager.py +++ b/gramps/plugins/tool/mediamanager.py @@ -94,16 +94,16 @@ class MediaMan(tool.Tool): intro = IntroductionPage() self.add_page(intro, Gtk.AssistantPageType.INTRO, _('Introduction')) self.selection = SelectionPage(self.batch_ops) - self.add_page(self.selection, Gtk.AssistantPageType.CONTENT, + self.add_page(self.selection, Gtk.AssistantPageType.CONTENT, _('Selection')) self.settings = SettingsPage(self.batch_ops, self.assistant) self.add_page(self.settings, Gtk.AssistantPageType.CONTENT) self.confirmation = ConfirmationPage(self.batch_ops) - self.add_page(self.confirmation, Gtk.AssistantPageType.CONFIRM, + self.add_page(self.confirmation, Gtk.AssistantPageType.CONFIRM, _('Final confirmation')) self.conclusion = ConclusionPage(self.assistant) self.add_page(self.conclusion, Gtk.AssistantPageType.SUMMARY) - + self.assistant.show() self.assistant.set_forward_page_func(self.forward_page, None) @@ -173,7 +173,7 @@ class MediaMan(tool.Tool): success = self.batch_ops[index].run_tool() self.conclusion.set_result(success) self.post_run() - + def pre_run(self): """ Code to run prior to the batch op. @@ -200,7 +200,7 @@ class IntroductionPage(Gtk.Box): def __init__(self): Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL) - # Using set_page_side_image causes window sizing problems, so put the + # Using set_page_side_image causes window sizing problems, so put the # image in the main page instead. image = Gtk.Image() image.set_from_file(SPLASH) @@ -245,7 +245,7 @@ class SelectionPage(Gtk.Box): """ def __init__(self, batch_ops): Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL) - + self.batch_op_buttons = [] self.set_spacing(12) @@ -253,7 +253,7 @@ class SelectionPage(Gtk.Box): grid = Gtk.Grid() grid.set_row_spacing(6) grid.set_column_spacing(6) - + button = None for index in range(len(batch_ops)): title = batch_ops[index].title @@ -263,13 +263,13 @@ class SelectionPage(Gtk.Box): button.set_tooltip_text(description) self.batch_op_buttons.append(button) grid.attach(button, 0, 2 * index, 2, 1) - + self.add(grid) def get_index(self): """ - Query the selection radiobuttons and return the index number - of the selected batch op. + Query the selection radiobuttons and return the index number + of the selected batch op. """ for index in range(len(self.batch_op_buttons)): button = self.batch_op_buttons[index] @@ -305,7 +305,7 @@ class SettingsPage(Gtk.Box): class ConfirmationPage(Gtk.Box): """ - A page to display the summary of the proposed action, as well as the + A page to display the summary of the proposed action, as well as the list of affected paths. """ def __init__(self, batch_ops): @@ -354,7 +354,7 @@ class ConfirmationPage(Gtk.Box): class ConclusionPage(Gtk.Box): """ - A page to display the summary of the proposed action, as well as the + A page to display the summary of the proposed action, as well as the list of affected paths. """ def __init__(self, assistant): @@ -370,7 +370,7 @@ class ConclusionPage(Gtk.Box): self.pack_start(image, False, False, 0) self.pack_start(self.label, False, False, 5) - + def set_result(self, success): if success: conclusion_title = _('Operation successfully finished') @@ -491,7 +491,7 @@ class PathChange(BatchOp): self.from_entry = Gtk.Entry() self.from_entry.set_hexpand(True) grid.attach(self.from_entry, 1, 0, 1, 1) - + from_label = Gtk.Label(label=_('_Replace:')) from_label.set_halign(Gtk.Align.START) from_label.set_use_underline(True) @@ -520,11 +520,11 @@ class PathChange(BatchOp): 'Operation:\t%(title)s\n' 'Replace:\t\t%(src_fname)s\n' 'With:\t\t%(dest_fname)s') % { - 'title' : self.title.replace('_',''), - 'src_fname' : from_text, + 'title' : self.title.replace('_',''), + 'src_fname' : from_text, 'dest_fname' : to_text } return text - + def _prepare(self): from_text = str(self.from_entry.get_text()) self.set_total(self.db.get_number_of_media_objects()) @@ -692,7 +692,7 @@ class ImagesNotIncluded(BatchOp): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class MediaManOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/mergecitations.py b/gramps/plugins/tool/mergecitations.py index a5ba539d3..6877129b6 100644 --- a/gramps/plugins/tool/mergecitations.py +++ b/gramps/plugins/tool/mergecitations.py @@ -58,7 +58,7 @@ from gramps.gen.merge import MergeCitationQuery from gramps.gui.glade import Glade from gramps.gen.db import DbTxn -from gramps.gen.lib import (Person, Family, Event, Place, MediaObject, Citation, +from gramps.gen.lib import (Person, Family, Event, Place, MediaObject, Citation, Repository) from gramps.gen.errors import MergeError @@ -88,10 +88,10 @@ WIKI_HELP_SEC = _('manual|Merge_citations...') # #------------------------------------------------------------------------- class MergeCitations(tool.BatchTool,ManagedWindow): - + def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate - + ManagedWindow.__init__(self, uistate, [], self.__class__) self.dbstate = dbstate self.set_window(Gtk.Window(), Gtk.Label(), '') @@ -102,7 +102,7 @@ class MergeCitations(tool.BatchTool,ManagedWindow): uistate.set_busy_cursor(True) self.run() uistate.set_busy_cursor(False) - + def run(self): top = Glade(toplevel="mergecitations") @@ -118,7 +118,7 @@ class MergeCitations(tool.BatchTool,ManagedWindow): self.notes_obj = top.get_object("notes") self.notes_obj.set_active(dont_merge_notes) self.notes_obj.show() - + self.menu = top.get_object("menu") self.menu.set_model(my_menu) self.menu.set_active(fields) @@ -130,7 +130,7 @@ class MergeCitations(tool.BatchTool,ManagedWindow): self.set_window(window, top.get_object('title2'), _("Notes, media objects and data-items of matching " "citations will be combined.")) - + top.connect_signals({ "on_merge_ok_clicked" : self.on_merge_ok_clicked, "destroy_passed_object" : self.cancel, @@ -147,22 +147,22 @@ class MergeCitations(tool.BatchTool,ManagedWindow): """ fields = self.menu.get_model()[self.menu.get_active()][1] dont_merge_notes = int(self.notes_obj.get_active()) - LOG.debug("cancel fields %d dont_merge_notes %d" % + LOG.debug("cancel fields %d dont_merge_notes %d" % (fields, dont_merge_notes)) self.options.handler.options_dict['fields'] = fields self.options.handler.options_dict['dont_merge_notes'] = dont_merge_notes # Save options self.options.handler.save_options() - + self.close(obj) - + def build_menu_names(self, obj): return (_("Tool settings"),_("Merge citations tool")) def on_help_clicked(self, obj): """Display the relevant portion of GRAMPS manual""" - + display_help(WIKI_HELP_PAGE , WIKI_HELP_SEC) def on_merge_ok_clicked(self, obj): @@ -180,11 +180,11 @@ class MergeCitations(tool.BatchTool,ManagedWindow): self.options.handler.save_options() self.progress = ProgressMeter(_('Checking Sources'), '') - self.progress.set_pass(_('Looking for citation fields'), + self.progress.set_pass(_('Looking for citation fields'), self.db.get_number_of_citations()) db = self.dbstate.db - + db.disable_signals() num_merges = 0 for handle in db.iter_source_handles(): @@ -235,7 +235,7 @@ class MergeCitations(tool.BatchTool,ManagedWindow): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class MergeCitationsOptions(tool.ToolOptions): @@ -252,9 +252,9 @@ class MergeCitationsOptions(tool.ToolOptions): 'dont_merge_notes' : 0, } self.options_help = { - 'dont_merge_notes' : - ("=0/1","Whether to merge citations if they have notes", - ["Merge citations with notes", + 'dont_merge_notes' : + ("=0/1","Whether to merge citations if they have notes", + ["Merge citations with notes", "Do not merge citations with notes"], False), 'fields' : ("=num","Threshold for matching", diff --git a/gramps/plugins/tool/notrelated.py b/gramps/plugins/tool/notrelated.py index 8a2c0ed0e..fa7b48094 100644 --- a/gramps/plugins/tool/notrelated.py +++ b/gramps/plugins/tool/notrelated.py @@ -81,9 +81,9 @@ class NotRelated(tool.ActivePersonTool, ManagedWindow) : self.dbstate = dbstate self.uistate = uistate self.db = dbstate.db - + topDialog = Glade() - + topDialog.connect_signals({ "destroy_passed_object" : self.close, "on_help_clicked" : self.on_help_clicked, @@ -229,7 +229,7 @@ class NotRelated(tool.ActivePersonTool, ManagedWindow) : def on_help_clicked(self, obj): """Display the relevant portion of GRAMPS manual""" - display_help(WIKI_HELP_PAGE , WIKI_HELP_SEC) + display_help(WIKI_HELP_PAGE , WIKI_HELP_SEC) def applyTagClicked(self, button) : @@ -258,18 +258,18 @@ class NotRelated(tool.ActivePersonTool, ManagedWindow) : # translators: leave all/any {...} untranslated #TRANS: no singular form needed, as rows is always > 1 ngettext("Setting tag for {number_of} person", - "Setting tag for {number_of} people", + "Setting tag for {number_of} people", rows).format(number_of=rows), rows) - + # iterate through all of the selected rows (model, paths) = self.treeSelection.get_selected_rows() for path in paths: if progress: progress.step() - + # for the current row, get the GID and the person from the database iter = self.model.get_iter(path) personGid = self.model.get_value(iter, 1) @@ -475,7 +475,7 @@ class NotRelated(tool.ActivePersonTool, ManagedWindow) : def get_tag_list(self, person): """ - Return a sorted list of tag names for the given person. + Return a sorted list of tag names for the given person. """ tags = [] for handle in person.get_tag_list(): diff --git a/gramps/plugins/tool/ownereditor.py b/gramps/plugins/tool/ownereditor.py index 4152ec383..27f62ceae 100644 --- a/gramps/plugins/tool/ownereditor.py +++ b/gramps/plugins/tool/ownereditor.py @@ -88,7 +88,7 @@ class OwnerEditor(tool.Tool, ManagedWindow): uistate = user.uistate ManagedWindow.__init__(self, uistate, [], self.__class__) tool.Tool.__init__(self, dbstate, options_class, name) - + self.display() def display(self): @@ -105,7 +105,7 @@ class OwnerEditor(tool.Tool, ManagedWindow): action_area = topDialog.get_object("action_area") help_button = topDialog.get_object("help_button") action_area.set_child_secondary(help_button, True) - + # connect signals topDialog.connect_signals({ "on_ok_button_clicked": self.on_ok_button_clicked, @@ -122,7 +122,7 @@ class OwnerEditor(tool.Tool, ManagedWindow): # get current db owner and attach it to the entries of the window self.owner = self.db.get_researcher() - + self.entries = [] entry = [ ("name", self.owner.set_name, self.owner.get_name), @@ -167,11 +167,11 @@ class OwnerEditor(tool.Tool, ManagedWindow): self.owner.set_from(get_researcher()) for entry in self.entries: entry.update() - + elif menuitem.props.name == 'copy_from_db_to_preferences': for i in range(len(config_keys)): config.set(config_keys[i], self.owner.get()[i]) - + #------------------------------------------------------------------------- # # OwnerEditorOptions (None at the moment) diff --git a/gramps/plugins/tool/patchnames.py b/gramps/plugins/tool/patchnames.py index d2b2b46c0..18b172627 100644 --- a/gramps/plugins/tool/patchnames.py +++ b/gramps/plugins/tool/patchnames.py @@ -100,7 +100,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): nickid = 2 pref1id = 3 compid = 4 - + def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate self.label = _('Name and title extraction tool') @@ -110,12 +110,12 @@ class PatchNames(tool.BatchTool, ManagedWindow): tool.BatchTool.__init__(self, dbstate, user, options_class, name) if self.fail: return - + winprefix = Gtk.Dialog(_("Default prefix and connector settings"), self.uistate.window, Gtk.DialogFlags.MODAL|Gtk.DialogFlags.DESTROY_WITH_PARENT, (_('_OK'), Gtk.ResponseType.ACCEPT)) - + winprefix.vbox.set_spacing(5) hboxpref = Gtk.Box() label = Gtk.Label(label=_('Prefixes to search for:')) @@ -151,7 +151,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): self.connector_list_nonsplit = self.connsbox.get_text().split(',') self.connector_list_nonsplit = list(map(strip, self.connector_list_nonsplit)) self.connsbox = None - + # Find a prefix in the first_name self._fn_prefix_re = re.compile("(\S+)\s+(%s)\s*$" % '|'.join(self.prefix_list), re.IGNORECASE) @@ -177,7 +177,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): name = person.get_primary_name() first = name.get_first_name() sname = name.get_surname() - + old_prefix = [] old_surn = [] old_con = [] @@ -257,7 +257,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): self.handle_to_action[key] = {self.compid: compoundval} #we cannot check compound surnames, so continue the loop continue - + # Next, try to split surname in compounds: prefix surname connector found = False new_prefix_list = [] @@ -267,7 +267,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): new_orig_list = [] ind = 0 cont = True - for pref, surn, con, prim, orig in zip(old_prefix, old_surn, + for pref, surn, con, prim, orig in zip(old_prefix, old_surn, old_con, old_prim, old_orig): surnval = surn.split() if surnval == []: @@ -285,7 +285,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): new_connector_list.append(con) new_prim_list.append(prim) new_orig_list.append(orig) - + while cont and (val.lower() in self.prefix_list): found = True if new_prefix_list[-1]: @@ -336,7 +336,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): except IndexError: val = '' cont = False - #initialize for a next surname in case there are still + #initialize for a next surname in case there are still #val if cont: found = True # we split surname @@ -346,7 +346,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): orig = NameOriginType() ind += 1 if found: - compoundval = (new_surname_list, new_prefix_list, + compoundval = (new_surname_list, new_prefix_list, new_connector_list, new_prim_list, new_orig_list) if key in self.handle_to_action: self.handle_to_action[key][self.compid] = compoundval @@ -429,7 +429,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): self.model.set_value(handle, 3, nick) self.model.set_value(handle, 4, p.get_primary_name().get_name()) self.nick_hash[key] = handle - + if self.titleid in data: title, given = data[self.titleid] handle = self.model.append() @@ -439,7 +439,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): self.model.set_value(handle, 3, title) self.model.set_value(handle, 4, p.get_primary_name().get_name()) self.title_hash[key] = handle - + if self.pref1id in data: given, prefixtotal, new_prefix = data[self.pref1id] handle = self.model.append() @@ -449,7 +449,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): self.model.set_value(handle, 3, prefixtotal) self.model.set_value(handle, 4, p.get_primary_name().get_name()) self.prefix1_hash[key] = handle - + if self.compid in data: surn_list, pref_list, con_list, prims, origs = data[self.compid] handle = self.model.append() @@ -470,7 +470,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): self.model.set_value(handle, 3, newval) self.model.set_value(handle, 4, p.get_primary_name().get_name()) self.compound_hash[key] = handle - + self.progress.step() self.progress.close() @@ -495,7 +495,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): name = p.get_primary_name() name.set_first_name(given.strip()) name.set_nick_name(nick.strip()) - + if self.titleid in data: modelhandle = self.title_hash[key] val = self.model.get_value(modelhandle, 0) @@ -504,7 +504,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): name = p.get_primary_name() name.set_first_name(given.strip()) name.set_title(title.strip()) - + if self.pref1id in data: modelhandle = self.prefix1_hash[key] val = self.model.get_value(modelhandle, 0) @@ -517,7 +517,7 @@ class PatchNames(tool.BatchTool, ManagedWindow): name.get_surname_list()[0].set_prefix(prefix) else: name.get_surname_list()[0].set_prefix('%s %s' % (prefix, oldpref)) - + if self.compid in data: modelhandle = self.compound_hash[key] val = self.model.get_value(modelhandle, 0) @@ -534,9 +534,9 @@ class PatchNames(tool.BatchTool, ManagedWindow): new_surn_list[-1].set_primary(prim) new_surn_list[-1].set_origintype(orig) name.set_surname_list(new_surn_list) - + self.db.commit_person(p, trans) - + self.db.enable_signals() self.db.request_rebuild() self.close() diff --git a/gramps/plugins/tool/populatesources.py b/gramps/plugins/tool/populatesources.py index 9faac18ed..c7a0a87f1 100644 --- a/gramps/plugins/tool/populatesources.py +++ b/gramps/plugins/tool/populatesources.py @@ -53,18 +53,18 @@ class PopulateSources(tool.Tool, ManagedWindow): """ Gramplet that populates the database with sources and citations. """ - + def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate self.label = 'Populate sources and citations tool' ManagedWindow.__init__(self, uistate, [], self.__class__) self.set_window(Gtk.Window(), Gtk.Label(), '') tool.Tool.__init__(self, dbstate, options_class, name) - + dialog = self.display() response = dialog.run() dialog.destroy() - + if response == Gtk.ResponseType.ACCEPT: self.on_ok_clicked() OkDialog('Data generated', @@ -107,7 +107,7 @@ class PopulateSources(tool.Tool, ManagedWindow): self.citations_entry.set_text("%d" % num_citations) hbox2.pack_start(label_citations, False, True, 0) hbox2.pack_start(self.citations_entry, True, True, 0) - + vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) vbox.pack_start(label, True, True, 0) vbox.pack_start(hbox1, False, True, 0) @@ -117,14 +117,14 @@ class PopulateSources(tool.Tool, ManagedWindow): dialog.vbox.pack_start(vbox, True, True, 0) dialog.show_all() return dialog - + def on_ok_clicked(self): """ Method that is run when you click the OK button. The numbers of sources and citations are retrieved from the entry box and used to govern the amount of data generated """ - + num_sources_text = self.sources_entry.get_text() try: num_sources = int(num_sources_text) @@ -132,17 +132,17 @@ class PopulateSources(tool.Tool, ManagedWindow): return num_citations_text = self.citations_entry.get_text() num_citations = int(num_citations_text) - + self.progress = ProgressMeter( 'Generating data', '') self.progress.set_pass('Generating data', num_sources*num_citations) - LOG.debug("sources %04d citations %04d" % (num_sources, + LOG.debug("sources %04d citations %04d" % (num_sources, num_citations)) - + source = Source() citation = Citation() - + self.db.disable_signals() with DbTxn('Populate sources and citations', self.db) as trans: for i in range(num_sources): @@ -150,7 +150,7 @@ class PopulateSources(tool.Tool, ManagedWindow): source.handle = None source.title = "Source %04d" % (i + 1) source_handle = self.db.add_source(source, trans) - + for j in range(num_citations): citation.gramps_id = None citation.handle = None @@ -162,7 +162,7 @@ class PopulateSources(tool.Tool, ManagedWindow): self.db.enable_signals() self.db.request_rebuild() self.progress.close() - + self.options.handler.options_dict['sources'] = num_sources self.options.handler.options_dict['citations'] = num_citations # Save options @@ -182,8 +182,8 @@ class PopulateSourcesOptions(tool.ToolOptions): 'citations' : 2, } self.options_help = { - 'sources' : ("=num", - "Number of sources to generate", + 'sources' : ("=num", + "Number of sources to generate", "Integer number"), 'citations' : ("=num", "Number of citations to generate for each source", diff --git a/gramps/plugins/tool/rebuild.py b/gramps/plugins/tool/rebuild.py index 4c5a9aa7f..2bee3a538 100644 --- a/gramps/plugins/tool/rebuild.py +++ b/gramps/plugins/tool/rebuild.py @@ -62,25 +62,25 @@ class Rebuild(tool.Tool, UpdateCallback): def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate - + tool.Tool.__init__(self, dbstate, options_class, name) if self.db.readonly: return self.db.disable_signals() - + if uistate: self.callback = uistate.pulse_progressbar uistate.set_busy_cursor(True) uistate.progress.show() uistate.push_message(dbstate, _("Rebuilding secondary indexes...")) - + UpdateCallback.__init__(self, self.callback) self.set_total(12) self.db.rebuild_secondary(self.update) self.reset() - + uistate.set_busy_cursor(False) uistate.progress.hide() OkDialog(_("Secondary indexes rebuilt"), @@ -95,7 +95,7 @@ class Rebuild(tool.Tool, UpdateCallback): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class RebuildOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/rebuildgenderstat.py b/gramps/plugins/tool/rebuildgenderstat.py index 1d3694975..86f11c0a2 100644 --- a/gramps/plugins/tool/rebuildgenderstat.py +++ b/gramps/plugins/tool/rebuildgenderstat.py @@ -68,7 +68,7 @@ class RebuildGenderStat(tool.Tool, UpdateCallback): def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate - + tool.Tool.__init__(self, dbstate, options_class, name) if self.db.readonly: @@ -83,7 +83,7 @@ class RebuildGenderStat(tool.Tool, UpdateCallback): else: self.callback = None print("Rebuilding gender statistics for name gender guessing...") - + UpdateCallback.__init__(self, self.callback) self.set_total(self.db.get_number_of_people()) self.rebuild_genderstats() @@ -104,20 +104,20 @@ class RebuildGenderStat(tool.Tool, UpdateCallback): Function to rebuild the gender stats """ self.db.genderStats.clear_stats() - with self.db.get_person_cursor() as cursor: + with self.db.get_person_cursor() as cursor: #loop over database and store the sort field, and the handle, and #allow for a third iter for key, data in cursor: rawprimname = data[COLUMN_NAME] rawaltnames = data[COLUMN_ALTNAMES] primary_name = Name().unserialize(rawprimname).get_first_name() - alternate_names = [Name().unserialize(name).get_first_name() + alternate_names = [Name().unserialize(name).get_first_name() for name in rawaltnames] self.db.genderStats.count_name(primary_name, data[COLUMN_GENDER]) #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class RebuildGenderStatOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/rebuildrefmap.py b/gramps/plugins/tool/rebuildrefmap.py index c8228b3e8..44b9be7c3 100644 --- a/gramps/plugins/tool/rebuildrefmap.py +++ b/gramps/plugins/tool/rebuildrefmap.py @@ -64,7 +64,7 @@ class RebuildRefMap(tool.Tool, UpdateCallback): def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate - + tool.Tool.__init__(self, dbstate, options_class, name) if self.db.readonly: @@ -79,7 +79,7 @@ class RebuildRefMap(tool.Tool, UpdateCallback): else: self.callback = None print(_("Rebuilding reference maps...")) - + UpdateCallback.__init__(self, self.callback) self.set_total(6) self.db.reindex_reference_map(self.update) @@ -97,7 +97,7 @@ class RebuildRefMap(tool.Tool, UpdateCallback): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class RebuildRefMapOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/relcalc.py b/gramps/plugins/tool/relcalc.py index 388bbd855..6b7b371b4 100644 --- a/gramps/plugins/tool/relcalc.py +++ b/gramps/plugins/tool/relcalc.py @@ -68,13 +68,13 @@ column_names = [column[0] for column in BasePersonView.COLUMNS] # #------------------------------------------------------------------------- class RelCalc(tool.Tool, ManagedWindow): - + def __init__(self, dbstate, user, options_class, name, callback=None): uistate = user.uistate """ Relationship calculator class. """ - + tool.Tool.__init__(self, dbstate, options_class, name) ManagedWindow.__init__(self,uistate,[],self.__class__) @@ -111,12 +111,12 @@ class RelCalc(tool.Tool, ManagedWindow): _('Relationship to %(person_name)s' ) % {'person_name' : name}, self.title) - + self.tree = self.glade.get_object("peopleList") self.text = self.glade.get_object("text1") self.textbuffer = Gtk.TextBuffer() self.text.set_buffer(self.textbuffer) - + self.model = PersonTreeModel(self.db) self.tree.set_model(self.model) @@ -169,14 +169,14 @@ class RelCalc(tool.Tool, ManagedWindow): model, iter_ = self.tree.get_selection().get_selected() if not iter_: return - + handle = model.get_handle_from_iter(iter_) - other_person = self.db.get_person_from_handle(handle) + other_person = self.db.get_person_from_handle(handle) if other_person is None : self.textbuffer.set_text("") return - - #now determine the relation, and print it out + + #now determine the relation, and print it out rel_strings, common_an = self.relationship.get_all_relationships( self.db, self.person, other_person) @@ -184,7 +184,7 @@ class RelCalc(tool.Tool, ManagedWindow): p2 = name_displayer.display(other_person) text = [] - if other_person is None: + if other_person is None: pass elif self.person.handle == other_person.handle: rstr = _("%(person)s and %(active_person)s are the same person.") % { @@ -240,7 +240,7 @@ class RelCalc(tool.Tool, ManagedWindow): for val in text: textval += "%s %s\n" % (val[0], val[1]) self.textbuffer.set_text(textval) - + def _key_press(self, obj, event): if event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter): store, paths = self.selection.get_selected_rows() @@ -254,7 +254,7 @@ class RelCalc(tool.Tool, ManagedWindow): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class RelCalcOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/removeunused.py b/gramps/plugins/tool/removeunused.py index 66d556dca..3365cfc65 100644 --- a/gramps/plugins/tool/removeunused.py +++ b/gramps/plugins/tool/removeunused.py @@ -158,7 +158,7 @@ class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback): self.warn_tree.connect('button_press_event', self.double_click) self.selection = self.warn_tree.get_selection() - + self.mark_button = self.top.get_object('mark_button') self.mark_button.connect('clicked', self.mark_clicked) @@ -168,10 +168,10 @@ class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback): self.invert_button = self.top.get_object('invert_button') self.invert_button.connect('clicked', self.invert_clicked) - self.real_model = Gtk.ListStore(GObject.TYPE_BOOLEAN, - GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, + self.real_model = Gtk.ListStore(GObject.TYPE_BOOLEAN, + GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_STRING, GObject.TYPE_STRING) self.sort_model = self.real_model.sort_new_with_model() self.warn_tree.set_model(self.sort_model) @@ -186,11 +186,11 @@ class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback): active=RemoveUnused.MARK_COL) mark_column.set_sort_column_id(RemoveUnused.MARK_COL) self.warn_tree.append_column(mark_column) - + # Add image column img_column = Gtk.TreeViewColumn(None, self.img_renderer ) img_column.set_cell_data_func(self.img_renderer, self.get_image) - self.warn_tree.append_column(img_column) + self.warn_tree.append_column(img_column) # Add column with object gramps_id id_column = Gtk.TreeViewColumn(_('ID'), self.renderer, @@ -249,7 +249,7 @@ class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback): self.uistate.set_busy_cursor(False) self.window.get_window().set_cursor(None) self.reset() - + # Save options self.options.handler.save_options() @@ -277,7 +277,7 @@ class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback): fbh = db.find_backlink_handles for handle, data in cursor: if not any(h for h in fbh(handle)): - self.add_results((the_type, handle2internal(handle), + self.add_results((the_type, handle2internal(handle), data)) self.update() self.reset() @@ -345,7 +345,7 @@ class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback): editor_str = 'from gramps.gui.editors import %s as editor' % ( self.tables[the_type]['editor'] ) - exec(editor_str, globals()) + exec(editor_str, globals()) editor(self.dbstate, self.uistate, [], obj) except WindowActiveError: pass @@ -370,7 +370,7 @@ class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback): name_ix = self.tables[the_type]['name_ix'] text = data[name_ix] - # insert a new row into the table + # insert a new row into the table self.real_model.append(row=[False, gramps_id, text, the_type, handle]) def get_event_text(self, the_type, handle, data): @@ -402,7 +402,7 @@ class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback): text += '; %s' % _pd.display_event(self.db, event) return text - + def get_note_text(self, the_type, handle, data): """ We need just the first few words of a note as a summary. @@ -424,7 +424,7 @@ class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class CheckOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/reorderids.py b/gramps/plugins/tool/reorderids.py index 1e9144897..700cc7f78 100644 --- a/gramps/plugins/tool/reorderids.py +++ b/gramps/plugins/tool/reorderids.py @@ -40,7 +40,7 @@ _ = glocale.translation.gettext # #------------------------------------------------------------------------ from gramps.gui.utils import ProgressMeter -from gramps.gen.lib import (Event, Family, MediaObject, Note, +from gramps.gen.lib import (Event, Family, MediaObject, Note, Person, Place, Repository, Source, Citation) from gramps.gen.db import DbTxn from gramps.gui.plug import tool @@ -168,10 +168,10 @@ class ReorderIds(tool.BatchTool): self.progress.close() else: print(_("Done.")) - + db.enable_signals() db.request_rebuild() - + def reorder(self, class_type, find_from_id, find_from_handle, find_next_id, table, commit, prefix): dups = [] @@ -227,7 +227,7 @@ class ReorderIds(tool.BatchTool): # go through the duplicates, looking for the first available # handle that matches the new scheme. - + if self.uistate: self.progress.set_pass(_('Finding and assigning unused IDs'), len(dups)) @@ -237,10 +237,10 @@ class ReorderIds(tool.BatchTool): obj = find_from_handle(handle) obj.set_gramps_id(find_next_id()) commit(obj, self.trans) - + #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class ReorderIdsOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/sortevents.py b/gramps/plugins/tool/sortevents.py index d93eae222..d9ef46bb5 100644 --- a/gramps/plugins/tool/sortevents.py +++ b/gramps/plugins/tool/sortevents.py @@ -9,7 +9,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -145,7 +145,7 @@ class SortEvents(PluginWindows.ToolManagedWindowBatch): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class SortEventOptions(MenuToolOptions): @@ -167,14 +167,14 @@ class SortEventOptions(MenuToolOptions): self.__filter.set_help(_("Select the people to sort")) menu.add_option(category_name, "filter", self.__filter) self.__filter.connect('value-changed', self.__filter_changed) - + self.__pid = PersonOption(_("Filter Person")) self.__pid.set_help(_("The center person for the filter")) menu.add_option(category_name, "pid", self.__pid) self.__pid.connect('value-changed', self.__update_filters) self.__update_filters() - + sort_by = EnumeratedListOption(_('Sort by'), 0 ) idx = 0 for item in _get_sort_functions(Sort(self.__db)): diff --git a/gramps/plugins/tool/testcasegenerator.py b/gramps/plugins/tool/testcasegenerator.py index 8d09f217a..a09c9ce67 100644 --- a/gramps/plugins/tool/testcasegenerator.py +++ b/gramps/plugins/tool/testcasegenerator.py @@ -39,16 +39,16 @@ import time # GNOME libraries # #------------------------------------------------------------------------- -from gi.repository import Gtk +from gi.repository import Gtk #------------------------------------------------------------------------- # # GRAMPS modules # #------------------------------------------------------------------------- -from gramps.gen.lib import (Address, Attribute, AttributeType, ChildRef, - ChildRefType, Citation, Date, Event, EventRef, EventRoleType, - EventType, Family, FamilyRelType, GrampsType, LdsOrd, Location, +from gramps.gen.lib import (Address, Attribute, AttributeType, ChildRef, + ChildRefType, Citation, Date, Event, EventRef, EventRoleType, + EventType, Family, FamilyRelType, GrampsType, LdsOrd, Location, MediaObject, MediaRef, Name, NameOriginType, NameType, Note, NoteType, Person, PersonRef, Place, PlaceType, PlaceRef, PlaceName, RepoRef, Repository, RepositoryType, Source, SourceMediaType, @@ -92,9 +92,9 @@ class TestcaseGenerator(tool.BatchTool): LONG = 7 TAG = 8 STYLED_TEXT = 9 - + # GEDCON definition: -# +# # FAMILY_EVENT_STRUCTURE:= # [ # n [ ANUL | CENS | DIV | DIVF ] [Y|] {1:1} @@ -153,7 +153,7 @@ class TestcaseGenerator(tool.BatchTool): self.generated_notes = [] self.generated_tags = [] self.text_serial_number = 1 - + self.parent_places = {} for type_num in range(1, 8): self.parent_places[type_num] = [] @@ -182,7 +182,7 @@ class TestcaseGenerator(tool.BatchTool): if death and not birth: birth = death - randint(20,90) self.person_dates[self.person.get_handle()] = (birth,death) - + self.persons_todo.append(self.person.get_handle()) self.parents_todo.append(self.person.get_handle()) @@ -274,17 +274,17 @@ class TestcaseGenerator(tool.BatchTool): def on_dummy_data_clicked(self, obj): self.label.set_sensitive(obj.get_active()) self.entry_count.set_sensitive(obj.get_active()) - + def run_tool(self, cli=False): self.cli = cli if( not cli): while Gtk.events_pending(): Gtk.main_iteration() - + self.progress = ProgressMeter(_('Generating testcases'),'', parent=self.window) self.transaction_count = 0; - + if self.options.handler.options_dict['lowlevel']: self.progress.set_pass(_('Generating low level database errors'), 1) @@ -296,7 +296,7 @@ class TestcaseGenerator(tool.BatchTool): if self.options.handler.options_dict['bugs']: self.generate_data_errors() - + if self.options.handler.options_dict['persons']: self.progress.set_pass(_('Generating families'), self.options.handler.options_dict['person_count']) @@ -321,13 +321,13 @@ class TestcaseGenerator(tool.BatchTool): if self.person_count > self.options.handler.options_dict['person_count']: break self.progress.close() - + if( not cli): self.top.destroy() - + def generate_data_errors(self): """This generates errors in the database to test src/plugins/tool/Check - The module names correspond to the checking methods in + The module names correspond to the checking methods in src/plugins/tool/Check.CheckIntegrity """ self.progress.set_pass(_('Generating database errors'), 18) @@ -356,7 +356,7 @@ class TestcaseGenerator(tool.BatchTool): self.test_check_repo_references(); self.progress.step() self.test_check_note_references(); self.progress.step() self.progress.close() - + def test_low_level(self): with DbTxn(_("Testcase generator step %d") % self.transaction_count, self.db) as self.trans: @@ -367,11 +367,11 @@ class TestcaseGenerator(tool.BatchTool): o.set_format( choice( (Note.FLOWED,Note.FORMATTED))) o.set_type( self.rand_type(NoteType())) h = self.db.add_note(o, self.trans) - print("object %s, handle %s, Gramps_Id %s" % (o, o.handle, + print("object %s, handle %s, Gramps_Id %s" % (o, o.handle, o.gramps_id)) - + handle = o.get_handle() - + o = Source() o.set_title("dup 2" + self.rand_text(self.SHORT)) if randint(0,1) == 1: @@ -387,7 +387,7 @@ class TestcaseGenerator(tool.BatchTool): o.add_attribute(sattr) o.set_handle(handle) self.db.add_source(o, self.trans) - print("object %s, handle %s, Gramps_Id %s" % (o, o.handle, + print("object %s, handle %s, Gramps_Id %s" % (o, o.handle, o.gramps_id)) def test_fix_encoding(self): @@ -410,16 +410,16 @@ class TestcaseGenerator(tool.BatchTool): m.set_path("/tmp/click_on_select_file.png\x9f") m.set_mime_type("image/png\x9f") self.db.add_object(m, self.trans) - + # setup media attached to Source and Citation to be removed - + m = MediaObject() self.fill_object(m) m.set_description('remove this media object') m.set_path("/tmp/click_on_remove_object.png") m.set_mime_type("image/png") self.db.add_object(m, self.trans) - + s = Source() s.set_title('media should be removed from this source') r = MediaRef() @@ -451,10 +451,10 @@ class TestcaseGenerator(tool.BatchTool): def test_cleanup_missing_photos(self): pass - + def test_cleanup_deleted_name_formats(self): pass - + def test_cleanup_empty_objects(self): # Generate empty objects to test their deletion with DbTxn(_("Testcase generator step %d") % self.transaction_count, @@ -463,31 +463,31 @@ class TestcaseGenerator(tool.BatchTool): p = Person() self.db.add_person( p, self.trans) - + f = Family() self.db.add_family( f, self.trans) - + e = Event() self.db.add_event( e, self.trans) - + p = Place() self.db.add_place( p, self.trans) - + s = Source() self.db.add_source( s, self.trans) - + c = Citation() self.db.add_citation( c, self.trans) - + m = MediaObject() self.db.add_object( m, self.trans) - + r = Repository() self.db.add_repository( r, self.trans) - + n = Note() self.db.add_note( n, self.trans) - + def test_check_for_broken_family_links(self): # Create a family, that links to father and mother, but father does not # link back @@ -724,13 +724,13 @@ class TestcaseGenerator(tool.BatchTool): def test_check_parent_relationships(self): pass - + def test_cleanup_empty_families(self): pass - + def test_cleanup_duplicate_spouses(self): pass - + def test_check_events(self): # Creates a person having a non existing birth event handle set with DbTxn(_("Testcase generator step %d") % self.transaction_count, @@ -816,10 +816,10 @@ class TestcaseGenerator(tool.BatchTool): def test_check_person_references(self): pass - + def test_check_family_references(self): pass - + def test_check_place_references(self): # Creates a person with a birth event pointing to nonexisting place with DbTxn(_("Testcase generator step %d") % self.transaction_count, @@ -864,19 +864,19 @@ class TestcaseGenerator(tool.BatchTool): c.set_reference_handle("unknownsourcehandle") c.set_page('unreferenced citation with invalid source ref') self.db.add_citation(c, self.trans) - + c = Citation() self.fill_object(c) c.set_reference_handle(None) c.set_page('unreferenced citation with invalid source ref') self.db.add_citation(c, self.trans) - + c = Citation() self.fill_object(c) c.set_reference_handle("unknownsourcehandle") c.set_page('citation and references to it should be removed') c_h1 = self.db.add_citation(c, self.trans) - + c = Citation() self.fill_object(c) c.set_reference_handle(None) @@ -891,11 +891,11 @@ class TestcaseGenerator(tool.BatchTool): with DbTxn(_("Testcase generator step %d") % self.transaction_count, self.db) as self.trans: self.transaction_count += 1 - + c_h = "unknowncitationhandle" self.create_all_possible_citations([c_h, None], "Broken22", 'non-existent citation') - + def create_all_possible_citations(self, c_h_list, name, message): # Create citations attached to each of the following objects: # Person @@ -906,26 +906,26 @@ class TestcaseGenerator(tool.BatchTool): # MediaRef # Attribute # LdsOrd - # + # # Family # Attribute # ChildRef # MediaRef # Attribute # LdsOrd - # + # # Event # Attribute # MediaRef # Attribute - # + # # MediaObject # Attribute - # + # # Place # MediaRef # Attribute - # + # # Repository (Repositories themselves do not have SourceRefs) # Address m = MediaObject() @@ -940,7 +940,7 @@ class TestcaseGenerator(tool.BatchTool): a.add_citation(choice(c_h_list)) m.add_attribute(a) self.db.add_object(m, self.trans) - + person1_h = self.generate_person(Person.MALE,name,None) person2_h = self.generate_person(Person.FEMALE,name,None) child_h = self.generate_person(None,name,None) @@ -1126,13 +1126,13 @@ class TestcaseGenerator(tool.BatchTool): def test_check_media_references(self): pass - + def test_check_repo_references(self): pass - + def test_check_note_references(self): pass - + def generate_person(self,gender=None,lastname=None, note=None, alive_in_year=None): if not self.cli: @@ -1142,7 +1142,7 @@ class TestcaseGenerator(tool.BatchTool): np = Person() self.fill_object(np) - + # Gender if gender is None: gender = randint(0,1) @@ -1150,7 +1150,7 @@ class TestcaseGenerator(tool.BatchTool): np.set_gender(Person.UNKNOWN) else: np.set_gender(gender) - + # Name name = Name() (firstname,lastname) = self.rand_name(lastname, gender) @@ -1160,7 +1160,7 @@ class TestcaseGenerator(tool.BatchTool): name.add_surname(surname) self.fill_object( name) np.set_primary_name(name) - + # generate some slightly different alternate name firstname2 = firstname.replace("m", "n").replace("l", "i").replace("b", "d") if firstname2 != firstname: @@ -1224,7 +1224,7 @@ class TestcaseGenerator(tool.BatchTool): by = alive_in_year - randint(0,60) dy = alive_in_year + randint(0,60) - + # birth if randint(0,1) == 1: (birth_year, eref) = self.rand_personal_event( EventType.BIRTH, by,by) @@ -1247,7 +1247,7 @@ class TestcaseGenerator(tool.BatchTool): (bur_year, eref) = self.rand_personal_event( choice( (EventType.BURIAL, EventType.CREMATION)), dy, dy+2) np.add_event_ref(eref) - + # some other events while randint(0,5) == 1: (birth_year, eref) = self.rand_personal_event( None, by,dy) @@ -1261,7 +1261,7 @@ class TestcaseGenerator(tool.BatchTool): self.fill_object( eref) eref.set_reference_handle(e_h) np.add_event_ref(eref) - + # PersonRef if randint(0,3) == 1: for i in range(0,randint(1,2)): @@ -1278,9 +1278,9 @@ class TestcaseGenerator(tool.BatchTool): np.add_person_ref(asso) if randint(0,2) == 0: self.persons_todo.append(asso_h) - + person_handle = self.db.add_person(np,self.trans) - + self.person_count = self.person_count+1 self.progress_step() if self.person_count % 10 == 1: @@ -1288,7 +1288,7 @@ class TestcaseGenerator(tool.BatchTool): self.person_dates[person_handle] = (by,dy) return( person_handle) - + def generate_family(self,person1_h): person1 = self.db.get_person_from_handle(person1_h) if not person1: @@ -1297,7 +1297,7 @@ class TestcaseGenerator(tool.BatchTool): if person1_h in self.person_dates: (born, died) = self.person_dates[person1_h] alive_in_year = min( born+randint(10,50), died + randint(-10,10)) - + if person1.get_gender() == 1: if randint(0,7)==1: person2_h = None @@ -1315,12 +1315,12 @@ class TestcaseGenerator(tool.BatchTool): person1_h = self.generate_person(1, alive_in_year = alive_in_year) else: person1_h = self.generate_person(1) - + if person1_h and randint(0,2) > 0: self.parents_todo.append(person1_h) if person2_h and randint(0,2) > 0: self.parents_todo.append(person2_h) - + with DbTxn(_("Testcase generator step %d") % self.transaction_count, self.db) as self.trans: self.transaction_count += 1 @@ -1330,16 +1330,16 @@ class TestcaseGenerator(tool.BatchTool): fam.set_father_handle(person1_h) if person2_h: fam.set_mother_handle(person2_h) - + # Avoid adding the same event more than once to the same family event_set = set() - + # Generate at least one family event with a probability of 75% if randint(0, 3) > 0: (birth_year, eref) = self.rand_family_event(None) fam.add_event_ref(eref) event_set.add(eref.get_reference_handle()) - + # generate some more events with a lower probability while randint(0, 3) == 1: (birth_year, eref) = self.rand_family_event(None) @@ -1347,7 +1347,7 @@ class TestcaseGenerator(tool.BatchTool): continue fam.add_event_ref(eref) event_set.add(eref.get_reference_handle()) - + # some shared events if self.generated_events: while randint(0, 5) == 1: @@ -1375,8 +1375,8 @@ class TestcaseGenerator(tool.BatchTool): person2.add_family_handle(fam_h) self.db.commit_person(person2,self.trans) - lastname = person1.get_primary_name().get_surname() - + lastname = person1.get_primary_name().get_surname() + for i in range(0,randint(1,10)): if self.person_count > self.options.handler.options_dict['person_count']: break @@ -1397,7 +1397,7 @@ class TestcaseGenerator(tool.BatchTool): self.db.commit_person(child,self.trans) if randint(0,3) > 0: self.persons_todo.append(child_h) - + def generate_parents(self,child_h): if not child_h: return @@ -1421,7 +1421,7 @@ class TestcaseGenerator(tool.BatchTool): self.parents_todo.append(person1_h) if randint(0,2) > 1: self.parents_todo.append(person2_h) - + with DbTxn(_("Testcase generator step %d") % self.transaction_count, self.db) as self.trans: self.transaction_count += 1 @@ -1459,7 +1459,7 @@ class TestcaseGenerator(tool.BatchTool): def add_defaults(self, object): self.fill_object( object) - + def rand_name( self, lastname=None, gender=None): if gender == Person.MALE: firstname = self.rand_text( self.FIRSTNAME_MALE) @@ -1470,7 +1470,7 @@ class TestcaseGenerator(tool.BatchTool): if not lastname: lastname = self.rand_text( self.LASTNAME) return (firstname,lastname) - + def rand_date( self, start=None, end=None): """ Generates a random date object between the given years start and end @@ -1482,7 +1482,7 @@ class TestcaseGenerator(tool.BatchTool): if end and not start: start = end - randint(0,100) year = randint(start,end) - + ndate = Date() if randint(0,10) == 1: # Some get a textual date @@ -1508,7 +1508,7 @@ class TestcaseGenerator(tool.BatchTool): month = randint(1,12) else: month = randint(0,12) - + if modifier in (Date.MOD_RANGE, Date.MOD_SPAN): day2 = randint(0,28) if day2 > 0: @@ -1519,12 +1519,12 @@ class TestcaseGenerator(tool.BatchTool): ndate.set(quality,modifier,calendar,(day,month,year,False,day2,month2,year2,False),"") else: ndate.set(quality,modifier,calendar,(day,month,year,False),"") - + return (year, ndate) - + def fill_object( self, o): - - + + if issubclass(o.__class__, AddressBase): while randint(0,1) == 1: a = Address() @@ -1629,7 +1629,7 @@ class TestcaseGenerator(tool.BatchTool): o.set_reference_handle( choice( self.generated_media)) if randint(0,1) == 1: o.set_rectangle( (randint(0,200),randint(0,200),randint(0,200),randint(0,200))) - + if isinstance(o,Name): o.set_type( self.rand_type( NameType())) if randint(0,1) == 1: @@ -1668,7 +1668,7 @@ class TestcaseGenerator(tool.BatchTool): self.generated_notes.append( n.get_handle()) n_h = choice(self.generated_notes) o.add_note(n_h) - + if isinstance(o, Place): o.set_title(self.rand_text(self.LONG)) o.set_name(PlaceName(value=self.rand_text(self.SHORT))) @@ -1696,7 +1696,7 @@ class TestcaseGenerator(tool.BatchTool): if issubclass(o.__class__, PrivacyBase): o.set_privacy( randint(0,5) == 1) - + if isinstance(o,RepoRef): if not self.generated_repos or randint(0,10) == 1: r = Repository() @@ -1765,7 +1765,7 @@ class TestcaseGenerator(tool.BatchTool): u = Url() self.fill_object(u) o.add_url(u) - + if isinstance(o,Url): o.set_path("http://www.gramps-project.org/?test=%s" % self.rand_text(self.SHORT)) o.set_description( self.rand_text(self.SHORT)) @@ -1779,7 +1779,7 @@ class TestcaseGenerator(tool.BatchTool): else: typeval = self.rand_type(EventType()) return self._rand_event( typeval, start, end) - + def rand_family_event( self, type=None, start=None, end=None): if type: typeval = EventType(type) @@ -1788,7 +1788,7 @@ class TestcaseGenerator(tool.BatchTool): while int(typeval) not in self.FAMILY_EVENTS: typeval = self.rand_type(EventType()) return self._rand_event( typeval, start, end) - + def _rand_event( self, type, start, end): e = Event() self.fill_object(e) @@ -1801,7 +1801,7 @@ class TestcaseGenerator(tool.BatchTool): self.fill_object(event_ref) event_ref.set_reference_handle(event_h) return (year, event_ref) - + def rand_type(self, gtype): if issubclass(gtype.__class__, GrampsType): map = gtype.get_map() @@ -1870,23 +1870,23 @@ class TestcaseGenerator(tool.BatchTool): result = StyledText("") else: result = "" - + if self.options.handler.options_dict['specialchars']: result = result + "ä<ö&ü%ß'\"" if self.options.handler.options_dict['add_serial'] and type != self.TAG: result = result + "#+#%06d#-#" % self.text_serial_number self.text_serial_number = self.text_serial_number + 1 - + if not type: type = self.SHORT - + if type == self.SHORT or type == self.TAG: minwords = 1 maxwords = 3 minsyllables = 2 maxsyllables = 4 - + if type == self.LONG: minwords = 5 maxwords = 8 @@ -1969,7 +1969,7 @@ class TestcaseGenerator(tool.BatchTool): result = StyledText("").join((result, word)) else: result += word - + if type == self.LASTNAME: n = randint(0,2) if n == 0: @@ -1982,7 +1982,7 @@ class TestcaseGenerator(tool.BatchTool): result = result + "\nNEWLINE" return result - + def rand_color(self): return '#%012X' % randint(0, 281474976710655) @@ -1997,7 +1997,7 @@ class TestcaseGenerator(tool.BatchTool): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class TestcaseGeneratorOptions(tool.ToolOptions): diff --git a/gramps/plugins/tool/tools.gpr.py b/gramps/plugins/tool/tools.gpr.py index 7a135b657..8ff1f9696 100644 --- a/gramps/plugins/tool/tools.gpr.py +++ b/gramps/plugins/tool/tools.gpr.py @@ -22,7 +22,7 @@ GRAMPS registration file """ -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # @@ -30,7 +30,7 @@ MODULE_VERSION="5.0" # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'chname', name = _("Fix Capitalization of Family Names"), description = _("Searches the entire database and attempts to " @@ -53,7 +53,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'chtype', name = _("Rename Event Types"), description = _("Allows all the events of a certain name " @@ -76,7 +76,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'check', name = _("Check and Repair Database"), description = _("Checks the database for integrity problems, fixing the " @@ -99,7 +99,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'eventcmp', name = _("Compare Individual Events"), description = _("Aids in the analysis of data by allowing the " @@ -123,7 +123,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'evname', name = _("Extract Event Description"), description = _("Extracts event descriptions from the event data"), @@ -145,7 +145,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'excity', name = _("Extract Place Data from a Place Title"), description = _("Attempts to extract city and state/province " @@ -168,7 +168,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'dupfind', name = _("Find Possible Duplicate People"), description = _("Searches the entire database, looking for " @@ -191,7 +191,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'mediaman', name = _("Media Manager"), description = _("Manages batch operations on media files"), @@ -213,7 +213,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'not_related', name = _("Not Related"), description = _("Find people who are not in any way related to the " @@ -236,7 +236,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'editowner', name = _("Edit Database Owner Information"), description = _("Allow editing database owner information."), @@ -258,7 +258,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'patchnames', name = _("Extract Information from Names"), description = _("Extract titles, prefixes and compound surnames from given name or family name."), @@ -280,7 +280,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'rebuild', name = _("Rebuild Secondary Indexes"), description = _("Rebuilds secondary indexes"), @@ -302,7 +302,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'rebuild_refmap', name = _("Rebuild Reference Maps"), description = _("Rebuilds reference maps"), @@ -346,7 +346,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'relcalc', name = _("Relationship Calculator"), description = _("Calculates the relationship between two people"), @@ -368,7 +368,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'remove_unused', name = _("Remove Unused Objects"), description = _("Removes unused objects from the database"), @@ -390,7 +390,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'reorder_ids', name = _("Reorder Gramps IDs"), description = _("Reorders the Gramps IDs " @@ -413,7 +413,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'sortevents', name = _("Sorts events"), description = _("Sorts events"), @@ -435,7 +435,7 @@ tool_modes = [TOOL_MODE_GUI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'verify', name = _("Verify the Data"), description = _("Verifies the data against user-defined tests"), @@ -457,7 +457,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'mergecitations', name = _("Merge Citations"), description = _("Searches the entire database, looking for " diff --git a/gramps/plugins/tool/toolsdebug.gpr.py b/gramps/plugins/tool/toolsdebug.gpr.py index 72023ba50..e5c295c3c 100644 --- a/gramps/plugins/tool/toolsdebug.gpr.py +++ b/gramps/plugins/tool/toolsdebug.gpr.py @@ -22,7 +22,7 @@ GRAMPS registration file """ -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # @@ -30,7 +30,7 @@ MODULE_VERSION="5.0" # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'test_for_date_parser_and_displayer', name = "Check Localized Date Displayer and Parser", description = ("This test tool will create many people showing all" @@ -56,7 +56,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'dgenstats', name = "Dump Gender Statistics", description = ("Will dump the statistics for the gender guessing " @@ -79,7 +79,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'testcasegenerator', name = "Generate Testcases for Persons and Families", description = ("The testcase generator will generate some persons " @@ -103,7 +103,7 @@ tool_modes = [TOOL_MODE_GUI, TOOL_MODE_CLI] # #------------------------------------------------------------------------ -register(TOOL, +register(TOOL, id = 'populatesources', name = "Populate Sources and Citations", description = ("This tool generates sources and citations for each source in " diff --git a/gramps/plugins/tool/verify.py b/gramps/plugins/tool/verify.py index 7d80cf2d0..f1ce9d47b 100644 --- a/gramps/plugins/tool/verify.py +++ b/gramps/plugins/tool/verify.py @@ -110,7 +110,7 @@ def find_family(db, handle): def clear_cache(): _person_cache.clear() _family_cache.clear() - _event_cache.clear() + _event_cache.clear() #------------------------------------------------------------------------- # @@ -148,7 +148,7 @@ def get_date_from_event_type(db, person, event_type, estimate=False): return 0 def get_bapt_date(db, person, estimate=False): - return get_date_from_event_type(db, person, + return get_date_from_event_type(db, person, EventType.BAPTISM, estimate) def get_bury_date(db, person, estimate=False): @@ -157,7 +157,7 @@ def get_bury_date(db, person, estimate=False): event = find_event(db, event_ref.ref) if event and event.get_type() == EventType.BURIAL and \ event_ref.get_role() == EventRoleType.PRIMARY: - return get_date_from_event_type(db, person, + return get_date_from_event_type(db, person, EventType.BURIAL, estimate) def get_birth_date(db, person, estimate=False): @@ -230,7 +230,7 @@ def get_marriage_date(db, family): for event_ref in family.get_event_ref_list(): event = find_event(db,event_ref.ref) if event.get_type() == EventType.MARRIAGE and \ - (event_ref.get_role() == EventRoleType.FAMILY or + (event_ref.get_role() == EventRoleType.FAMILY or event_ref.get_role() == EventRoleType.PRIMARY ): date_obj = event.get_date_object() return date_obj.get_sort_value() @@ -280,7 +280,7 @@ class Verify(tool.Tool, ManagedWindow, UpdateCallback): def init_gui(self): # Draw dialog and make it handle everything - self.vr = None + self.vr = None self.top = Glade() self.top.connect_signals({ "destroy_passed_object" : self.close, @@ -350,14 +350,14 @@ class Verify(tool.Tool, ManagedWindow, UpdateCallback): run_button.set_sensitive(True) close_button.set_sensitive(True) self.reset() - + # Save options self.options.handler.save_options() def run_tool(self,cli=False): person_handles = self.db.iter_person_handles() - + for option, value in \ self.options.handler.options_dict.items(): exec('%s = %s' % (option, value), globals()) @@ -424,7 +424,7 @@ class Verify(tool.Tool, ManagedWindow, UpdateCallback): for rule in rule_list: if rule.broken(): self.add_results(rule.report_itself()) - + clear_cache() if not cli: self.update() @@ -455,7 +455,7 @@ class VerifyResults(ManagedWindow): self.top = Glade(toplevel="verify_result") window = self.top.toplevel self.set_window(window,self.top.get_object('title2'),self.title) - + self.top.connect_signals({ "destroy_passed_object" : self.close, "on_verify_ok_clicked" : self.__dummy, @@ -466,7 +466,7 @@ class VerifyResults(ManagedWindow): self.warn_tree.connect('button_press_event', self.double_click) self.selection = self.warn_tree.get_selection() - + self.hide_button = self.top.get_object('hide_button') self.hide_button.connect('toggled',self.hide_toggled) @@ -479,14 +479,14 @@ class VerifyResults(ManagedWindow): self.invert_button = self.top.get_object('invert_all') self.invert_button.connect('clicked',self.invert_clicked) - self.real_model = Gtk.ListStore(GObject.TYPE_BOOLEAN, - GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, - GObject.TYPE_STRING, object, - GObject.TYPE_STRING, + self.real_model = Gtk.ListStore(GObject.TYPE_BOOLEAN, GObject.TYPE_STRING, - GObject.TYPE_BOOLEAN, + GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_STRING, object, + GObject.TYPE_STRING, + GObject.TYPE_STRING, + GObject.TYPE_BOOLEAN, GObject.TYPE_BOOLEAN) self.filt_model = self.real_model.filter_new() self.filt_model.set_visible_column(VerifyResults.TRUE_COL) @@ -503,11 +503,11 @@ class VerifyResults(ManagedWindow): active=VerifyResults.IGNORE_COL) ignore_column.set_sort_column_id(VerifyResults.IGNORE_COL) self.warn_tree.append_column(ignore_column) - + # Add image column img_column = Gtk.TreeViewColumn(None, self.img_renderer ) img_column.set_cell_data_func(self.img_renderer,self.get_image) - self.warn_tree.append_column(img_column) + self.warn_tree.append_column(img_column) # Add column with the warning text warn_column = Gtk.TreeViewColumn(_('Warning'), self.renderer, @@ -529,7 +529,7 @@ class VerifyResults(ManagedWindow): foreground=VerifyResults.FG_COLOR_COL) name_column.set_sort_column_id(VerifyResults.OBJ_NAME_COL) self.warn_tree.append_column(name_column) - + self.show() self.window_shown = False @@ -543,7 +543,7 @@ class VerifyResults(ManagedWindow): if isinstance(db_filename, str): db_filename = db_filename.encode('utf-8') md5sum = md5(db_filename) - ## a new Gramps major version means recreating the .vfm file. + ## a new Gramps major version means recreating the .vfm file. ## User can copy over old one, with name of new one, but no guarantee ## that will work. self.ignores_filename = os.path.join( @@ -616,7 +616,7 @@ class VerifyResults(ManagedWindow): self.sort_model = self.filt_model.sort_new_with_model() self.warn_tree.set_model(self.sort_model) button.set_label(_("_Hide marked")) - + def selection_toggled(self, cell, path_string): sort_path = tuple(map(int, path_string.split(':'))) filt_path = self.sort_model.convert_path_to_child_path(Gtk.TreePath(sort_path)) @@ -694,7 +694,7 @@ class VerifyResults(ManagedWindow): self.real_model.append(row=[ignore,msg,gramps_id, name, the_type,rule_id, handle,fg, True, not ignore]) - + if not self.window_shown: self.window.show() self.window_shown = True @@ -704,7 +704,7 @@ class VerifyResults(ManagedWindow): #------------------------------------------------------------------------ # -# +# # #------------------------------------------------------------------------ class VerifyOptions(tool.ToolOptions): @@ -770,7 +770,7 @@ class VerifyOptions(tool.ToolOptions): ["Do not estimate","Estimate dates"], True), 'invdate' : ("=0/1","Whether to check for invalid dates" - "Do not identify invalid dates", + "Do not identify invalid dates", "Identify invalid dates", True), } @@ -787,7 +787,7 @@ class Rule(object): """ ID = 0 TYPE = '' - + ERROR = 1 WARNING = 2 @@ -1078,7 +1078,7 @@ class SameSurnameFamily(FamilyRule): mother = get_mother(self.db, self.obj) father = get_father(self.db, self.obj) _broken = False - + # Make sure both mother and father exist. if mother and father: mname = mother.get_primary_name() @@ -1427,9 +1427,9 @@ class DeadParent(FamilyRule): if not child_birth_date_ok: continue - hasBirthRelToMother = child_ref.mrel == ChildRefType.BIRTH + hasBirthRelToMother = child_ref.mrel == ChildRefType.BIRTH hasBirthRelToFather = child_ref.frel == ChildRefType.BIRTH - + father_broken = (hasBirthRelToFather and father_death_date_ok and ((father_death_date + 294) < child_birth_date)) @@ -1464,7 +1464,7 @@ class LargeChildrenSpan(FamilyRule): def broken(self): child_birh_dates = get_child_birth_dates(self.db,self.obj,self.est) child_birh_dates.sort() - + return (child_birh_dates and ((child_birh_dates[-1] - child_birh_dates[0])/365 > self.cb_span)) @@ -1487,7 +1487,7 @@ class LargeChildrenAgeDiff(FamilyRule): child_birh_dates = get_child_birth_dates(self.db,self.obj,self.est) child_birh_dates_diff = [child_birh_dates[i+1] - child_birh_dates[i] for i in range(len(child_birh_dates)-1) ] - + return (child_birh_dates_diff and max(child_birh_dates_diff)/365 > self.c_space) @@ -1547,14 +1547,14 @@ class InvalidDeathDate(PersonRule): def get_message(self): return _("Invalid death date") - + class MarriedRelation(FamilyRule): ID = 31 SEVERITY = Rule.WARNING def __init__(self,db, obj): FamilyRule.__init__(self,db, obj) - def broken(self): + def broken(self): marr_date = get_marriage_date(self.db,self.obj) marr_date_ok = marr_date > 0 married = self.obj.get_relationship() == FamilyRelType.MARRIED diff --git a/gramps/plugins/view/citationlistview.py b/gramps/plugins/view/citationlistview.py index f78d66d34..a7a7f70f5 100644 --- a/gramps/plugins/view/citationlistview.py +++ b/gramps/plugins/view/citationlistview.py @@ -1,7 +1,7 @@ # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2001-2006 Donald N. Allingham -# Copyright (C) 2008 Gary Burton +# Copyright (C) 2008 Gary Burton # Copyright (C) 2011 Tim G L Lyons # # This program is free software; you can redistribute it and/or modify @@ -73,8 +73,8 @@ _ = glocale.translation.gettext class CitationListView(ListView): """ A list view of citations. - - The citation list view only shows the citations (it does not show + + The citation list view only shows the citations (it does not show sources as separate list entries). """ # The data items here have to correspond, in order, to the items in @@ -116,11 +116,11 @@ class CitationListView(ListView): COL_CONFIDENCE]), ('columns.rank', [COL_TITLE_PAGE, COL_ID, COL_DATE, COL_CONFIDENCE, COL_PRIV, COL_TAGS, COL_CHAN, COL_SRC_TITLE, - COL_SRC_ID, COL_SRC_AUTH, COL_SRC_ABBR, COL_SRC_PINFO, + COL_SRC_ID, COL_SRC_AUTH, COL_SRC_ABBR, COL_SRC_PINFO, COL_SRC_PRIV, COL_SRC_CHAN]), - ('columns.size', [200, 75, 100, 100, 40, 100, 100, 200, 75, 75, 100, + ('columns.size', [200, 75, 100, 100, 40, 100, 100, 200, 75, 75, 100, 150, 40, 100]) - ) + ) ADD_MSG = _("Add a new citation and a new source") ADD_SOURCE_MSG = _("Add a new source") ADD_CITATION_MSG = _("Add a new citation to an existing source") @@ -140,7 +140,7 @@ class CitationListView(ListView): } ListView.__init__( - self, _('Citation View'), pdata, dbstate, uistate, + self, _('Citation View'), pdata, dbstate, uistate, CitationListModel, signal_map, CitationBookmarks, nav_group, multiple=True, @@ -158,19 +158,19 @@ class CitationListView(ListView): def drag_info(self): return DdTargets.CITATION_LINK - + def define_actions(self): """ This defines the possible actions for the citation views. Possible actions are: - add: Add a new citation and a new source (this can also be done - by source view add a source, then citation view add a new + add: Add a new citation and a new source (this can also be done + by source view add a source, then citation view add a new citation to an existing source) edit: Edit a citation. merge: Merge the selected citations. remove: Delete the selected citations. - - + + """ ListView.define_actions(self) @@ -223,8 +223,8 @@ class CitationListView(ListView): - - + + @@ -248,19 +248,19 @@ class CitationListView(ListView): def add(self, obj): """ - add: Add a new citation and a new source (this can also be done - by source view add a source, then citation view add a new + add: Add a new citation and a new source (this can also be done + by source view add a source, then citation view add a new citation to an existing source) - - Create a new Source instance and Citation instance and call the - EditCitation editor with the new source and new citation. - - Called when the Add button is clicked. - If the window already exists (WindowActiveError), we ignore it. + + Create a new Source instance and Citation instance and call the + EditCitation editor with the new source and new citation. + + Called when the Add button is clicked. + If the window already exists (WindowActiveError), we ignore it. This prevents the dialog from coming up twice on the same object. - + However, since the window is identified by the Source object, and - we have just created a new one, it seems to be impossible for the + we have just created a new one, it seems to be impossible for the window to already exist, so this is just an extra safety measure. """ try: @@ -275,7 +275,7 @@ class CitationListView(ListView): def remove_object_from_handle(self, handle): the_lists = get_citation_referents(handle, self.dbstate.db) object = self.dbstate.db.get_citation_from_handle(handle) - query = DeleteCitationQuery(self.dbstate, self.uistate, object, + query = DeleteCitationQuery(self.dbstate, self.uistate, object, the_lists) is_used = any(the_lists) return (query, is_used, object) @@ -306,7 +306,7 @@ class CitationListView(ListView): Merge the selected citations. """ mlist = self.selected_handles() - + if len(mlist) != 2: msg = _("Cannot merge citations.") msg2 = _("Exactly two citations must be selected to perform a " @@ -318,7 +318,7 @@ class CitationListView(ListView): citation1 = self.dbstate.db.get_citation_from_handle(mlist[0]) citation2 = self.dbstate.db.get_citation_from_handle(mlist[1]) if not citation1.get_reference_handle() == \ - citation2.get_reference_handle(): + citation2.get_reference_handle(): msg = _("Cannot merge citations.") msg2 = _("The two selected citations must have the same " "source to perform a merge. If you want to merge " @@ -354,7 +354,7 @@ class CitationListView(ListView): citation = self.dbstate.db.get_citation_from_handle(citation_handle) citation.add_tag(tag_handle) self.dbstate.db.commit_citation(citation, transaction) - + def get_default_gramplets(self): """ Define the default gramplets for the sidebar and bottombar. diff --git a/gramps/plugins/view/citationtreeview.py b/gramps/plugins/view/citationtreeview.py index 372ba8591..a0d73ab7e 100644 --- a/gramps/plugins/view/citationtreeview.py +++ b/gramps/plugins/view/citationtreeview.py @@ -48,7 +48,7 @@ from gramps.gui.views.treemodels.citationtreemodel import CitationTreeModel from gramps.gen.plug import CATEGORY_QR_SOURCE_OR_CITATION from gramps.gen.lib import Citation, Source from gramps.gui.views.listview import ListView -from gramps.gen.utils.db import (get_source_and_citation_referents, +from gramps.gen.utils.db import (get_source_and_citation_referents, get_citation_referents) from gramps.gui.views.bookmarks import CitationBookmarks from gramps.gen.errors import WindowActiveError @@ -82,9 +82,9 @@ class CitationTreeView(ListView): COL_ID = 1 COL_DATE = 2 COL_CONFIDENCE = 3 - COL_PRIV = 4 - COL_TAGS = 5 - COL_CHAN = 6 + COL_PRIV = 4 + COL_TAGS = 5 + COL_CHAN = 6 COL_SRC_AUTH = 7 COL_SRC_ABBR = 8 COL_SRC_PINFO = 9 @@ -102,7 +102,7 @@ class CitationTreeView(ListView): (_('Source: Publication Information'), TEXT, None), ] COLUMN_FILTERABLE = [ - COL_TITLE_PAGE, + COL_TITLE_PAGE, COL_ID, COL_CHAN, COL_SRC_AUTH, @@ -117,7 +117,7 @@ class CitationTreeView(ListView): COL_PRIV, COL_TAGS, COL_CHAN, COL_SRC_AUTH, COL_SRC_ABBR, COL_SRC_PINFO]), ('columns.size', [200, 75, 100, 75, 40, 100, 100, 150, 100, 150]) - ) + ) ADD_MSG = _("Add a new citation and a new source") ADD_SOURCE_MSG = _("Add a new source") ADD_CITATION_MSG = _("Add a new citation to an existing source") @@ -126,9 +126,9 @@ class CitationTreeView(ListView): MERGE_MSG = _("Merge the selected citations or selected sources") FILTER_TYPE = "Citation" QR_CATEGORY = CATEGORY_QR_SOURCE_OR_CITATION - + def __init__(self, pdata, dbstate, uistate, nav_group=0): - + signal_map = { 'citation-add' : self._citation_row_add, 'citation-update' : self._citation_row_update, @@ -141,7 +141,7 @@ class CitationTreeView(ListView): } ListView.__init__( - self, _('Citation Tree View'), pdata, dbstate, uistate, + self, _('Citation Tree View'), pdata, dbstate, uistate, CitationTreeModel, signal_map, CitationBookmarks, nav_group, multiple=True, @@ -164,16 +164,16 @@ class CitationTreeView(ListView): # more comprehensive solution is needed in the long term. See also # add in Bookmarks.CitationBookmarks pass - + def setup_filter(self): """ Override the setup of the default Search Bar in listview, so that only the searchable source fields are shown. """ - + self.search_bar.setup_filter( [(self.COLUMNS[pair[1]][0], pair[1], pair[1] in self.exact_search()) - for pair in self.column_order() if pair[0] and + for pair in self.column_order() if pair[0] and pair[1] in self.COLUMN_FILTERABLE]) def _print_handles(self, text, handle_list): @@ -182,46 +182,46 @@ class CitationTreeView(ListView): citation = self.dbstate.db.get_citation_from_handle(handle) _LOG.debug("\n\n\n") if source: - _LOG.debug("---- %s -- source %s" % + _LOG.debug("---- %s -- source %s" % (text, source.get_title())) elif citation: - _LOG.debug("---- %s -- citation %s" % + _LOG.debug("---- %s -- citation %s" % (text, citation.get_page())) else: _LOG.debug("---- %s -- handle %s" % (text, handle)) - - def _citation_row_add(self, handle_list): + + def _citation_row_add(self, handle_list): self._print_handles("citation row add", handle_list) self.row_add(handle_list) - - def _citation_row_update(self, handle_list): + + def _citation_row_update(self, handle_list): self._print_handles("citation row update", handle_list) self.row_update(handle_list) - - def _citation_row_delete(self, handle_list): + + def _citation_row_delete(self, handle_list): self._print_handles("citation row delete", handle_list) self.row_delete(handle_list) - - def _citation_object_build(self, *args): + + def _citation_object_build(self, *args): _LOG.debug("citation object build") self.object_build(*args) - - def _source_row_add(self, handle_list): + + def _source_row_add(self, handle_list): self._print_handles("source row add", handle_list) self.row_add(handle_list) - - def _source_row_update(self, handle_list): + + def _source_row_update(self, handle_list): self._print_handles("source row update", handle_list) self.row_update(handle_list) - - def _source_row_delete(self, handle_list): + + def _source_row_delete(self, handle_list): self._print_handles("source row delete", handle_list) self.row_delete(handle_list) - - def _source_object_build(self, *args): + + def _source_object_build(self, *args): _LOG.debug("source object build") self.object_build(*args) - + def navigation_type(self): return 'Citation' @@ -236,14 +236,14 @@ class CitationTreeView(ListView): # is selected. Hence the simplistic solution implemented below, where # CITATION_LINK is always returned except when it is obviously correct # to return SOURCE_LINK. - + selection = self.selected_handles() if len(selection) == 1 and \ self.dbstate.db.get_source_from_handle(selection[0]): return DdTargets.SOURCE_LINK else: return DdTargets.CITATION_LINK - + def get_stock(self): return 'gramps-citation' @@ -252,36 +252,36 @@ class CitationTreeView(ListView): Override the default icon. Set for hierarchical view. """ return 'gramps-tree-group' - + def define_actions(self): """ This defines the possible actions for the citation views. Possible actions are: add_source: Add a new source (this is also available from the source view) - add: Add a new citation and a new source (this can also be done - by source view add a source, then citation view add a new + add: Add a new citation and a new source (this can also be done + by source view add a source, then citation view add a new citation to an existing source) share: Add a new citation to an existing source (when a source is selected) edit: Edit a source or a citation. merge: Merge the selected sources or citations. remove: Delete the selected sources or citations. - - + + """ ListView.define_actions(self) - self._add_action('Add source', 'gramps-source', _("Add source..."), - accel=None, - tip=self.ADD_SOURCE_MSG, + self._add_action('Add source', 'gramps-source', _("Add source..."), + accel=None, + tip=self.ADD_SOURCE_MSG, callback=self.add_source) - self._add_action('Add citation', 'gramps-citation', - _("Add citation..."), - accel=None, - tip=self.ADD_CITATION_MSG, + self._add_action('Add citation', 'gramps-citation', + _("Add citation..."), + accel=None, + tip=self.ADD_CITATION_MSG, callback=self.share) - + self.all_action = Gtk.ActionGroup(name=self.title + "/CitationAll") self.edit_action = Gtk.ActionGroup(name=self.title + "/CitationEdit") @@ -293,10 +293,10 @@ class CitationTreeView(ListView): self._add_action_group(self.all_action) self.all_action.add_actions([ - ('OpenAllNodes', None, _("Expand all Nodes"), None, None, - self.open_all_nodes), - ('CloseAllNodes', None, _("Collapse all Nodes"), None, None, - self.close_all_nodes), + ('OpenAllNodes', None, _("Expand all Nodes"), None, None, + self.open_all_nodes), + ('CloseAllNodes', None, _("Collapse all Nodes"), None, None, + self.close_all_nodes), ]) def additional_ui(self): @@ -336,8 +336,8 @@ class CitationTreeView(ListView): - - + + @@ -369,16 +369,16 @@ class CitationTreeView(ListView): """ add_source: Add a new source (this is also available from the source view) - + Create a new Source instance and call the EditSource editor with the - new source. - - Called when the Add_source button is clicked. - If the window already exists (WindowActiveError), we ignore it. + new source. + + Called when the Add_source button is clicked. + If the window already exists (WindowActiveError), we ignore it. This prevents the dialog from coming up twice on the same object. - + However, since the window is identified by the Source object, and - we have just created a new one, it seems to be impossible for the + we have just created a new one, it seems to be impossible for the window to already exist, so this is just an extra safety measure. """ try: @@ -388,19 +388,19 @@ class CitationTreeView(ListView): def add(self, obj): """ - add: Add a new citation and a new source (this can also be done - by source view add a source, then citation view add a new + add: Add a new citation and a new source (this can also be done + by source view add a source, then citation view add a new citation to an existing source) - - Create a new Source instance and Citation instance and call the - EditSource editor with the new source. - - Called when the Add button is clicked. - If the window already exists (WindowActiveError), we ignore it. + + Create a new Source instance and Citation instance and call the + EditSource editor with the new source. + + Called when the Add button is clicked. + If the window already exists (WindowActiveError), we ignore it. This prevents the dialog from coming up twice on the same object. - + However, since the window is identified by the Source object, and - we have just created a new one, it seems to be impossible for the + we have just created a new one, it seems to be impossible for the window to already exist, so this is just an extra safety measure. """ try: @@ -422,7 +422,7 @@ class CitationTreeView(ListView): raise ValueError("selection must be either source or citation") if source: try: - EditCitation(self.dbstate, self.uistate, [], + EditCitation(self.dbstate, self.uistate, [], Citation(), source) except WindowActiveError: from gramps.gui.dialog import WarningDialog @@ -433,7 +433,7 @@ class CitationTreeView(ListView): msg2 = _("In order to add a citation to an existing source, " " you must select a source.") ErrorDialog(msg, msg2) -# +# def remove(self, obj): self.remove_selected_objects() @@ -446,17 +446,17 @@ class CitationTreeView(ListView): if citation: the_lists = get_citation_referents(handle, self.dbstate.db) object = self.dbstate.db.get_citation_from_handle(handle) - query = DeleteCitationQuery(self.dbstate, self.uistate, object, + query = DeleteCitationQuery(self.dbstate, self.uistate, object, the_lists) is_used = any(the_lists) return (query, is_used, object) else: - the_lists = get_source_and_citation_referents(handle, + the_lists = get_source_and_citation_referents(handle, self.dbstate.db) - LOG.debug('the_lists %s' % [the_lists]) - + LOG.debug('the_lists %s' % [the_lists]) + object = self.dbstate.db.get_source_from_handle(handle) - query = DeleteSrcQuery(self.dbstate, self.uistate, object, + query = DeleteSrcQuery(self.dbstate, self.uistate, object, the_lists) is_used = any(the_lists) return (query, is_used, object) @@ -509,7 +509,7 @@ class CitationTreeView(ListView): Merge the selected citations. """ mlist = self.selected_handles() - + if len(mlist) != 2: msg = _("Cannot merge citations.") msg2 = _("Exactly two citations must be selected to perform a " @@ -522,15 +522,15 @@ class CitationTreeView(ListView): citation1 = self.dbstate.db.get_citation_from_handle(mlist[0]) if (not source1 and not citation1) or (source1 and citation1): raise ValueError("selection must be either source or citation") - + source2 = self.dbstate.db.get_source_from_handle(mlist[1]) citation2 = self.dbstate.db.get_citation_from_handle(mlist[1]) if (not source2 and not citation2) or (source2 and citation2): raise ValueError("selection must be either source or citation") - + if citation1 and citation2: if not citation1.get_reference_handle() == \ - citation2.get_reference_handle(): + citation2.get_reference_handle(): msg = _("Cannot merge citations.") msg2 = _("The two selected citations must have the same " "source to perform a merge. If you want to merge " @@ -538,7 +538,7 @@ class CitationTreeView(ListView): "sources first.") ErrorDialog(msg, msg2) else: - MergeCitation(self.dbstate, self.uistate, mlist[0], + MergeCitation(self.dbstate, self.uistate, mlist[0], mlist[1]) elif source1 and source2: MergeSource(self.dbstate, self.uistate, mlist[0], mlist[1]) diff --git a/gramps/plugins/view/dashboardview.py b/gramps/plugins/view/dashboardview.py index 27af23efd..197e5ed14 100644 --- a/gramps/plugins/view/dashboardview.py +++ b/gramps/plugins/view/dashboardview.py @@ -8,7 +8,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -39,7 +39,7 @@ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gui.widgets.grampletpane import GrampletPane -class DashboardView(PageView): +class DashboardView(PageView): """ DashboardView interface """ @@ -77,11 +77,11 @@ class DashboardView(PageView): def get_stock(self): """ - Return image associated with the view, which is used for the + Return image associated with the view, which is used for the icon for the button. """ return 'gramps-gramplet' - + def get_viewtype_stock(self): """Type of view in category """ @@ -108,16 +108,16 @@ class DashboardView(PageView): def can_configure(self): """ - See :class:`~gui.views.pageview.PageView + See :class:`~gui.views.pageview.PageView :return: bool """ return self.widget.can_configure() def _get_configure_page_funcs(self): """ - Return a list of functions that create gtk elements to use in the + Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog - + :return: list of functions """ return self.widget._get_configure_page_funcs() diff --git a/gramps/plugins/view/eventview.py b/gramps/plugins/view/eventview.py index cecfc6314..b4a0a2ad8 100644 --- a/gramps/plugins/view/eventview.py +++ b/gramps/plugins/view/eventview.py @@ -96,7 +96,7 @@ class EventView(ListView): ('columns.rank', [COL_TYPE, COL_PARTIC, COL_DATE, COL_PLACE, COL_DESCR, COL_ID, COL_PRIV, COL_TAGS, COL_CHAN]), ('columns.size', [100, 230, 150, 200, 100, 75, 40, 100, 100]) - ) + ) ADD_MSG = _("Add a new event") EDIT_MSG = _("Edit the selected event") DEL_MSG = _("Delete the selected event") @@ -122,7 +122,7 @@ class EventView(ListView): EventBookmarks, nav_group, multiple=True, filter_class=EventSidebarFilter) - + self.func_list.update({ 'J' : self.jump, 'BackSpace' : self.key_delete, @@ -183,8 +183,8 @@ class EventView(ListView): - - + + @@ -210,7 +210,7 @@ class EventView(ListView): ListView.define_actions(self) self._add_action('FilterEdit', None, _('Event Filter Editor'), callback=self.filter_editor,) - self._add_action('QuickReport', None, + self._add_action('QuickReport', None, _("Quick View"), None, None, None) def get_handle_from_gramps_id(self, gid): @@ -234,13 +234,13 @@ class EventView(ListView): item[1] for item in self.dbstate.db.find_backlink_handles(handle,['Person']) ] - family_list = [ + family_list = [ item[1] for item in self.dbstate.db.find_backlink_handles(handle,['Family']) ] - + object = self.dbstate.db.get_event_from_handle(handle) - query = DeleteEventQuery(self.dbstate, self.uistate, object, + query = DeleteEventQuery(self.dbstate, self.uistate, object, person_list, family_list) is_used = len(person_list) + len(family_list) > 0 return (query, is_used, object) @@ -287,7 +287,7 @@ class EventView(ListView): event = self.dbstate.db.get_event_from_handle(event_handle) event.add_tag(tag_handle) self.dbstate.db.commit_event(event, transaction) - + def get_default_gramplets(self): """ Define the default gramplets for the sidebar and bottombar. diff --git a/gramps/plugins/view/familyview.py b/gramps/plugins/view/familyview.py index 7cb929e10..7f5033e5f 100644 --- a/gramps/plugins/view/familyview.py +++ b/gramps/plugins/view/familyview.py @@ -87,12 +87,12 @@ class FamilyView(ListView): ] #default setting with visible columns, order of the col, and their size CONFIGSETTINGS = ( - ('columns.visible', [COL_ID, COL_FATHER, COL_MOTHER, COL_REL, + ('columns.visible', [COL_ID, COL_FATHER, COL_MOTHER, COL_REL, COL_MARDATE]), - ('columns.rank', [COL_ID, COL_FATHER, COL_MOTHER, COL_REL, + ('columns.rank', [COL_ID, COL_FATHER, COL_MOTHER, COL_REL, COL_MARDATE, COL_PRIV, COL_TAGS, COL_CHAN]), ('columns.size', [75, 200, 200, 100, 100, 40, 100, 100]) - ) + ) ADD_MSG = _("Add a new family") EDIT_MSG = _("Edit the selected family") @@ -166,8 +166,8 @@ class FamilyView(ListView): - - + + @@ -199,7 +199,7 @@ class FamilyView(ListView): self._add_action('FilterEdit', None, _('Family Filter Editor'), callback=self.filter_editor,) - + self.all_action = Gtk.ActionGroup(name=self.title + "/FamilyAll") self.all_action.add_actions([ ('MakeFatherActive', None, _("Make Father Active Person"), @@ -217,10 +217,10 @@ class FamilyView(ListView): else: from gramps.gui.dialog import WarningDialog WarningDialog( - _("Could Not Set a Bookmark"), + _("Could Not Set a Bookmark"), _("A bookmark could not be set because " "no one was selected.")) - + def add(self, obj): family = Family() try: @@ -240,13 +240,13 @@ class FamilyView(ListView): msg1 = self._message1_format(family) msg2 = self._message2_format(family) msg2 = "%s %s" % (msg2, data_recover_msg) - QuestionDialog(msg1, - msg2, - _('_Delete Family'), + QuestionDialog(msg1, + msg2, + _('_Delete Family'), lambda: self.delete_family_response(family)) else: MultiSelectDialog(self._message1_format, - self._message2_format, + self._message2_format, handles, self.dbstate.db.get_family_from_handle, yes_func=self.delete_family_response) @@ -255,7 +255,7 @@ class FamilyView(ListView): """ Header format for remove dialogs. """ - return _('Delete %s?') % (_('family') + + return _('Delete %s?') % (_('family') + (" [%s]" % family.gramps_id)) def _message2_format(self, family): @@ -278,7 +278,7 @@ class FamilyView(ListView): self.dbstate.db.remove_family_relationships(family.handle, trans) trans.set_description(_("Family [%s]") % gramps_id) self.uistate.set_busy_cursor(False) - + def edit(self, obj): for handle in self.selected_handles(): family = self.dbstate.db.get_family_from_handle(handle) @@ -286,7 +286,7 @@ class FamilyView(ListView): EditFamily(self.dbstate, self.uistate, [], family) except WindowActiveError: pass - + def merge(self, obj): """ Merge the selected families. @@ -321,7 +321,7 @@ class FamilyView(ListView): family = self.dbstate.db.get_family_from_handle(fhandle) if family: self.uistate.set_active(family.mother_handle, 'Person') - + def drag_info(self): """ Indicate that the drag type is a FAMILY_LINK diff --git a/gramps/plugins/view/fanchartdescview.py b/gramps/plugins/view/fanchartdescview.py index eb2a93673..29ee1eb3f 100644 --- a/gramps/plugins/view/fanchartdescview.py +++ b/gramps/plugins/view/fanchartdescview.py @@ -52,7 +52,7 @@ PRINT_SETTINGS = None class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): """ - The Gramplet code that realizes the FanChartWidget. + The Gramplet code that realizes the FanChartWidget. """ #settings in the config file CONFIGSETTINGS = ( @@ -70,15 +70,15 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): self.uistate = uistate NavigationView.__init__(self, _('Descendant Fan Chart'), - pdata, dbstate, uistate, + pdata, dbstate, uistate, PersonBookmarks, nav_group) fanchartdesc.FanChartDescGrampsGUI.__init__(self, self.on_childmenu_changed) #set needed values - self.maxgen = self._config.get('interface.fanview-maxgen') + self.maxgen = self._config.get('interface.fanview-maxgen') self.background = self._config.get('interface.fanview-background') self.fonttype = self._config.get('interface.fanview-font') - + self.grad_start = self._config.get('interface.color-start-grad') self.grad_end = self._config.get('interface.color-end-grad') self.form = self._config.get('interface.fanview-form') @@ -113,7 +113,7 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): The category stock icon """ return 'gramps-pedigree' - + def get_viewtype_stock(self): """Type of view in category """ @@ -145,8 +145,8 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): - - + + @@ -170,7 +170,7 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): def build_tree(self): """ Generic method called by PageView to construct the view. - Here the tree builds when active person changes or db changes or on + Here the tree builds when active person changes or db changes or on callbacks like person_rebuild, so build will be double sometimes. However, change in generic filter also triggers build_tree ! So we need to reset. @@ -196,7 +196,7 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): self._add_db_signal('family-add', self.person_rebuild) self._add_db_signal('family-delete', self.person_rebuild) self._add_db_signal('family-rebuild', self.person_rebuild) - + def change_db(self, db): self._change_db(db) if self.active: @@ -205,7 +205,7 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): def update(self): self.main() - + def goto_handle(self, handle): self.change_active(handle) self.main() @@ -235,7 +235,7 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): elif self.form == fanchart.FORM_QUADRANT: heightpx = heightpx / 2 + self.fan.CENTER + fanchart.PAD_PX widthpx = heightpx - + prt = CairoPrintSave(widthpx, heightpx, self.fan.on_draw, self.uistate.window) prt.run() @@ -247,16 +247,16 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): def can_configure(self): """ - See :class:`~gui.views.pageview.PageView + See :class:`~gui.views.pageview.PageView :return: bool """ return True def _get_configure_page_funcs(self): """ - Return a list of functions that create gtk elements to use in the + Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog - + :return: list of functions """ return [self.config_panel] @@ -272,17 +272,17 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): grid.set_row_spacing(6) configdialog.add_spinner(grid, _("Max generations"), 0, - 'interface.fanview-maxgen', (1, 11), + 'interface.fanview-maxgen', (1, 11), callback=self.cb_update_maxgen) - configdialog.add_combo(grid, - _('Text Font'), + configdialog.add_combo(grid, + _('Text Font'), 1, 'interface.fanview-font', self.allfonts, callback=self.cb_update_font, valueactive=True) backgrvals = ( (fanchart.BACKGROUND_GENDER, _('Gender colors')), (fanchart.BACKGROUND_GRAD_GEN, _('Generation based gradient')), (fanchart.BACKGROUND_GRAD_AGE, _('Age (0-100) based gradient')), - (fanchart.BACKGROUND_SINGLE_COLOR, + (fanchart.BACKGROUND_SINGLE_COLOR, _('Single main (filter) color')), (fanchart.BACKGROUND_GRAD_PERIOD, _('Time period based gradient')), (fanchart.BACKGROUND_WHITE, _('White')), @@ -295,17 +295,17 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): if curval == nr: break nrval += 1 - configdialog.add_combo(grid, - _('Background'), + configdialog.add_combo(grid, + _('Background'), 2, 'interface.fanview-background', backgrvals, callback=self.cb_update_background, valueactive=False, setactive=nrval ) #colors, stored as hex values - configdialog.add_color(grid, _('Start gradient/Main color'), 3, + configdialog.add_color(grid, _('Start gradient/Main color'), 3, 'interface.color-start-grad', col=1) - configdialog.add_color(grid, _('End gradient/2nd color'), 4, + configdialog.add_color(grid, _('End gradient/2nd color'), 4, 'interface.color-end-grad', col=1) configdialog.add_color(grid, _('Color for duplicates'), 5, 'interface.duplicate-color', col=1) @@ -313,15 +313,15 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): configdialog.add_combo(grid, _('Fan chart type'), 6, 'interface.fanview-form', ((fanchart.FORM_CIRCLE, _('Full Circle')), - (fanchart.FORM_HALFCIRCLE, _('Half Circle')), + (fanchart.FORM_HALFCIRCLE, _('Half Circle')), (fanchart.FORM_QUADRANT, _('Quadrant'))), callback=self.cb_update_form) # algo for the fan angle distribution configdialog.add_combo(grid, _('Fan chart distribution'), 7, 'interface.angle-algorithm', - ((fanchartdesc.ANGLE_CHEQUI, + ((fanchartdesc.ANGLE_CHEQUI, _('Homogeneous children distribution')), - (fanchartdesc.ANGLE_WEIGHT, + (fanchartdesc.ANGLE_WEIGHT, _('Size proportional to number of descendants')), ), callback=self.cb_update_anglealgo) @@ -369,7 +369,7 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): def cb_update_color(self, client, cnxn_id, entry, data): """ - Called when the configuration menu changes the childrenring setting. + Called when the configuration menu changes the childrenring setting. """ self.grad_start = self._config.get('interface.color-start-grad') self.grad_end = self._config.get('interface.color-end-grad') @@ -396,12 +396,12 @@ class FanChartDescView(fanchartdesc.FanChartDescGrampsGUI, NavigationView): #------------------------------------------------------------------------ class CairoPrintSave(): """Act as an abstract document that can render onto a cairo context. - + It can render the model onto cairo context pages, according to the received page style. - + """ - + def __init__(self, widthpx, heightpx, drawfunc, parent): """ This class provides the things needed so as to dump a cairo drawing on @@ -411,13 +411,13 @@ class CairoPrintSave(): self.heightpx = heightpx self.drawfunc = drawfunc self.parent = parent - + def run(self): """Create the physical output from the meta document. - + """ global PRINT_SETTINGS - + # set up a print operation operation = Gtk.PrintOperation() operation.connect("draw_page", self.on_draw_page) @@ -425,7 +425,7 @@ class CairoPrintSave(): operation.connect("paginate", self.on_paginate) operation.set_n_pages(1) #paper_size = Gtk.PaperSize.new(name="iso_a4") - ## WHY no Gtk.Unit.PIXEL ?? Is there a better way to convert + ## WHY no Gtk.Unit.PIXEL ?? Is there a better way to convert ## Pixels to MM ?? paper_size = Gtk.PaperSize.new_custom("custom", "Custom Size", @@ -437,10 +437,10 @@ class CairoPrintSave(): #page_setup.set_orientation(Gtk.PageOrientation.PORTRAIT) operation.set_default_page_setup(page_setup) #operation.set_use_full_page(True) - + if PRINT_SETTINGS is not None: operation.set_print_settings(PRINT_SETTINGS) - + # run print dialog while True: self.preview = None @@ -460,7 +460,7 @@ class CairoPrintSave(): # store print settings if printing was successful if res == Gtk.PrintOperationResult.APPLY: PRINT_SETTINGS = operation.get_print_settings() - + def on_draw_page(self, operation, context, page_nr): """Draw a page on a Cairo context. """ @@ -475,7 +475,7 @@ class CairoPrintSave(): def on_paginate(self, operation, context): """Paginate the whole document in chunks. We don't need this as there is only one page, however, - we provide a dummy holder here, because on_preview crashes if no + we provide a dummy holder here, because on_preview crashes if no default application is set with gir 3.3.2 (typically evince not installed)! It will provide the start of the preview dialog, which cannot be started in on_preview @@ -483,16 +483,16 @@ class CairoPrintSave(): finished = True # update page number operation.set_n_pages(1) - + # start preview if needed if self.preview: self.preview.run() - + return finished def on_preview(self, operation, preview, context, parent): """Implement custom print preview functionality. - We provide a dummy holder here, because on_preview crashes if no + We provide a dummy holder here, because on_preview crashes if no default application is set with gir 3.3.2 (typically evince not installed)! """ dlg = Gtk.MessageDialog(parent, @@ -505,7 +505,7 @@ class CairoPrintSave(): #dlg.format_secondary_markup(msg2) dlg.set_title("Fan Chart Preview - Gramps") dlg.connect('response', self.previewdestroy) - + # give a dummy cairo context to Gtk.PrintContext, try: width = int(round(context.get_width())) @@ -518,8 +518,8 @@ class CairoPrintSave(): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) cr = cairo.Context(surface) context.set_cairo_context(cr, 72.0, 72.0) - - return True + + return True def previewdestroy(self, dlg, res): self.preview.destroy() diff --git a/gramps/plugins/view/fanchartview.py b/gramps/plugins/view/fanchartview.py index f73182caf..6b6078e9f 100644 --- a/gramps/plugins/view/fanchartview.py +++ b/gramps/plugins/view/fanchartview.py @@ -51,7 +51,7 @@ PRINT_SETTINGS = None class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): """ - The Gramplet code that realizes the FanChartWidget. + The Gramplet code that realizes the FanChartWidget. """ #settings in the config file CONFIGSETTINGS = ( @@ -69,17 +69,17 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): self.uistate = uistate NavigationView.__init__(self, _('Fan Chart'), - pdata, dbstate, uistate, + pdata, dbstate, uistate, PersonBookmarks, nav_group) fanchart.FanChartGrampsGUI.__init__(self, self.on_childmenu_changed) #set needed values - self.maxgen = self._config.get('interface.fanview-maxgen') + self.maxgen = self._config.get('interface.fanview-maxgen') self.background = self._config.get('interface.fanview-background') self.childring = self._config.get('interface.fanview-childrenring') self.radialtext = self._config.get('interface.fanview-radialtext') self.fonttype = self._config.get('interface.fanview-font') - + self.grad_start = self._config.get('interface.color-start-grad') self.grad_end = self._config.get('interface.color-end-grad') self.form = self._config.get('interface.fanview-form') @@ -97,7 +97,7 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): def build_widget(self): self.set_fan(fanchart.FanChartWidget(self.dbstate, self.uistate, self.on_popup)) - self.scrolledwindow = Gtk.ScrolledWindow(hadjustment=None, + self.scrolledwindow = Gtk.ScrolledWindow(hadjustment=None, vadjustment=None) self.scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) @@ -111,7 +111,7 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): The category stock icon """ return 'gramps-pedigree' - + def get_viewtype_stock(self): """Type of view in category """ @@ -143,8 +143,8 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): - - + + @@ -168,7 +168,7 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): def build_tree(self): """ Generic method called by PageView to construct the view. - Here the tree builds when active person changes or db changes or on + Here the tree builds when active person changes or db changes or on callbacks like person_rebuild, so build will be double sometimes. However, change in generic filter also triggers build_tree ! So we need to reset. @@ -194,7 +194,7 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): self._add_db_signal('family-add', self.person_rebuild) self._add_db_signal('family-delete', self.person_rebuild) self._add_db_signal('family-rebuild', self.person_rebuild) - + def change_db(self, db): self._change_db(db) if self.active: @@ -203,7 +203,7 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): def update(self): self.main() - + def goto_handle(self, handle): self.change_active(handle) self.main() @@ -233,7 +233,7 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): elif self.form == fanchart.FORM_QUADRANT: heightpx = heightpx / 2 + self.fan.CENTER + fanchart.PAD_PX widthpx = heightpx - + prt = CairoPrintSave(widthpx, heightpx, self.fan.on_draw, self.uistate.window) prt.run() @@ -245,16 +245,16 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): def can_configure(self): """ - See :class:`~gui.views.pageview.PageView + See :class:`~gui.views.pageview.PageView :return: bool """ return True def _get_configure_page_funcs(self): """ - Return a list of functions that create gtk elements to use in the + Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog - + :return: list of functions """ return [self.config_panel] @@ -270,17 +270,17 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): grid.set_row_spacing(6) configdialog.add_spinner(grid, _("Max generations"), 0, - 'interface.fanview-maxgen', (1, 11), + 'interface.fanview-maxgen', (1, 11), callback=self.cb_update_maxgen) - configdialog.add_combo(grid, - _('Text Font'), + configdialog.add_combo(grid, + _('Text Font'), 1, 'interface.fanview-font', self.allfonts, callback=self.cb_update_font, valueactive=True) backgrvals = ( (fanchart.BACKGROUND_GENDER, _('Gender colors')), (fanchart.BACKGROUND_GRAD_GEN, _('Generation based gradient')), (fanchart.BACKGROUND_GRAD_AGE, _('Age (0-100) based gradient')), - (fanchart.BACKGROUND_SINGLE_COLOR, + (fanchart.BACKGROUND_SINGLE_COLOR, _('Single main (filter) color')), (fanchart.BACKGROUND_GRAD_PERIOD, _('Time period based gradient')), (fanchart.BACKGROUND_WHITE, _('White')), @@ -293,31 +293,31 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): if curval == nr: break nrval += 1 - configdialog.add_combo(grid, - _('Background'), + configdialog.add_combo(grid, + _('Background'), 2, 'interface.fanview-background', backgrvals, callback=self.cb_update_background, valueactive=False, setactive=nrval ) #colors, stored as hex values - configdialog.add_color(grid, _('Start gradient/Main color'), 3, + configdialog.add_color(grid, _('Start gradient/Main color'), 3, 'interface.color-start-grad', col=1) - configdialog.add_color(grid, _('End gradient/2nd color'), 4, + configdialog.add_color(grid, _('End gradient/2nd color'), 4, 'interface.color-end-grad', col=1) # form of the fan configdialog.add_combo(grid, _('Fan chart type'), 5, 'interface.fanview-form', - ((0, _('Full Circle')), (1,_('Half Circle')), + ((0, _('Full Circle')), (1,_('Half Circle')), (2, _('Quadrant'))), callback=self.cb_update_form) # options users should not change: - configdialog.add_checkbox(grid, - _('Show children ring'), + configdialog.add_checkbox(grid, + _('Show children ring'), nrentry-1, 'interface.fanview-childrenring') # options we don't show on the dialog - ##configdialog.add_checkbox(table, - ## _('Allow radial text'), + ##configdialog.add_checkbox(table, + ## _('Allow radial text'), ## ??, 'interface.fanview-radialtext') return _('Layout'), grid @@ -359,7 +359,7 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): def cb_update_childrenring(self, client, cnxn_id, entry, data): """ - Called when the configuration menu changes the childrenring setting. + Called when the configuration menu changes the childrenring setting. """ if entry == 'True': self.childring = True @@ -369,7 +369,7 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): def cb_update_radialtext(self, client, cnxn_id, entry, data): """ - Called when the configuration menu changes the childrenring setting. + Called when the configuration menu changes the childrenring setting. """ if entry == 'True': self.radialtext = True @@ -379,7 +379,7 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): def cb_update_color(self, client, cnxn_id, entry, data): """ - Called when the configuration menu changes the childrenring setting. + Called when the configuration menu changes the childrenring setting. """ self.grad_start = self._config.get('interface.color-start-grad') self.grad_end = self._config.get('interface.color-end-grad') @@ -405,12 +405,12 @@ class FanChartView(fanchart.FanChartGrampsGUI, NavigationView): #------------------------------------------------------------------------ class CairoPrintSave(): """Act as an abstract document that can render onto a cairo context. - + It can render the model onto cairo context pages, according to the received page style. - + """ - + def __init__(self, widthpx, heightpx, drawfunc, parent): """ This class provides the things needed so as to dump a cairo drawing on @@ -420,13 +420,13 @@ class CairoPrintSave(): self.heightpx = heightpx self.drawfunc = drawfunc self.parent = parent - + def run(self): """Create the physical output from the meta document. - + """ global PRINT_SETTINGS - + # set up a print operation operation = Gtk.PrintOperation() operation.connect("draw_page", self.on_draw_page) @@ -434,7 +434,7 @@ class CairoPrintSave(): operation.connect("paginate", self.on_paginate) operation.set_n_pages(1) #paper_size = Gtk.PaperSize.new(name="iso_a4") - ## WHY no Gtk.Unit.PIXEL ?? Is there a better way to convert + ## WHY no Gtk.Unit.PIXEL ?? Is there a better way to convert ## Pixels to MM ?? paper_size = Gtk.PaperSize.new_custom("custom", "Custom Size", @@ -446,10 +446,10 @@ class CairoPrintSave(): #page_setup.set_orientation(Gtk.PageOrientation.PORTRAIT) operation.set_default_page_setup(page_setup) #operation.set_use_full_page(True) - + if PRINT_SETTINGS is not None: operation.set_print_settings(PRINT_SETTINGS) - + # run print dialog while True: self.preview = None @@ -469,7 +469,7 @@ class CairoPrintSave(): # store print settings if printing was successful if res == Gtk.PrintOperationResult.APPLY: PRINT_SETTINGS = operation.get_print_settings() - + def on_draw_page(self, operation, context, page_nr): """Draw a page on a Cairo context. """ @@ -484,7 +484,7 @@ class CairoPrintSave(): def on_paginate(self, operation, context): """Paginate the whole document in chunks. We don't need this as there is only one page, however, - we provide a dummy holder here, because on_preview crashes if no + we provide a dummy holder here, because on_preview crashes if no default application is set with gir 3.3.2 (typically evince not installed)! It will provide the start of the preview dialog, which cannot be started in on_preview @@ -492,16 +492,16 @@ class CairoPrintSave(): finished = True # update page number operation.set_n_pages(1) - + # start preview if needed if self.preview: self.preview.run() - + return finished def on_preview(self, operation, preview, context, parent): """Implement custom print preview functionality. - We provide a dummy holder here, because on_preview crashes if no + We provide a dummy holder here, because on_preview crashes if no default application is set with gir 3.3.2 (typically evince not installed)! """ dlg = Gtk.MessageDialog(parent, @@ -514,7 +514,7 @@ class CairoPrintSave(): #dlg.format_secondary_markup(msg2) dlg.set_title("Fan Chart Preview - Gramps") dlg.connect('response', self.previewdestroy) - + # give a dummy cairo context to Gtk.PrintContext, try: width = int(round(context.get_width())) @@ -527,8 +527,8 @@ class CairoPrintSave(): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) cr = cairo.Context(surface) context.set_cairo_context(cr, 72.0, 72.0) - - return True + + return True def previewdestroy(self, dlg, res): self.preview.destroy() diff --git a/gramps/plugins/view/geoclose.py b/gramps/plugins/view/geoclose.py index 72e0349b7..b4aa37e9d 100644 --- a/gramps/plugins/view/geoclose.py +++ b/gramps/plugins/view/geoclose.py @@ -93,8 +93,8 @@ _UI_DEF = '''\ - - + + @@ -138,7 +138,7 @@ class GeoClose(GeoGraphyView): def __init__(self, pdata, dbstate, uistate, nav_group=0): GeoGraphyView.__init__(self, _("Have they been able to meet?"), - pdata, dbstate, uistate, + pdata, dbstate, uistate, PersonBookmarks, nav_group) self.dbstate = dbstate @@ -173,11 +173,11 @@ class GeoClose(GeoGraphyView): def get_stock(self): """ Returns the name of the stock icon to use for the display. - This assumes that this icon has already been registered + This assumes that this icon has already been registered as a stock icon. """ return 'gramps-relation' - + def get_viewtype_stock(self): """Type of view in category """ @@ -358,7 +358,7 @@ class GeoClose(GeoGraphyView): def _createmap(self, person, color, place_list, reference): """ - Create all markers for each people's event in the database which has + Create all markers for each people's event in the database which has a lat/lon. """ dbstate = self.dbstate @@ -489,7 +489,7 @@ class GeoClose(GeoGraphyView): continue else: events.append(plce[10]) - + if plce[0] != oldplace: message = "%s :" % plce[0] self.add_place_bubble_message(event, lat, lon, @@ -539,10 +539,10 @@ class GeoClose(GeoGraphyView): None, event.button, event.time) return 0 - def add_specific_menu(self, menu, event, lat, lon): - """ + def add_specific_menu(self, menu, event, lat, lon): + """ Add specific entry to the navigation menu. - """ + """ add_item = Gtk.MenuItem() add_item.show() menu.append(add_item) @@ -577,7 +577,7 @@ class GeoClose(GeoGraphyView): 'The value is in tenth of degree.'), 1, line_wrap=False) self.config_meeting_slider = configdialog.add_slider(grid, - "", + "", 2, 'geography.maximum_meeting_zone', (1, 9)) return _('The selection parameters'), grid diff --git a/gramps/plugins/view/geoevents.py b/gramps/plugins/view/geoevents.py index 19e731e98..241b06d15 100644 --- a/gramps/plugins/view/geoevents.py +++ b/gramps/plugins/view/geoevents.py @@ -95,8 +95,8 @@ _UI_DEF = '''\ - - + + @@ -117,7 +117,7 @@ class GeoEvents(GeoGraphyView): def __init__(self, pdata, dbstate, uistate, nav_group=0): GeoGraphyView.__init__(self, _('Events places map'), - pdata, dbstate, uistate, + pdata, dbstate, uistate, EventBookmarks, nav_group) self.dbstate = dbstate @@ -143,11 +143,11 @@ class GeoEvents(GeoGraphyView): def get_stock(self): """ Returns the name of the stock icon to use for the display. - This assumes that this icon has already been registered + This assumes that this icon has already been registered as a stock icon. """ return 'geo-show-events' - + def get_viewtype_stock(self): """Type of view in category """ @@ -194,7 +194,7 @@ class GeoEvents(GeoGraphyView): def _createmap_for_one_event(self,event): """ - Create all markers for each people's event in the database which has + Create all markers for each people's event in the database which has a lat/lon. """ dbstate = self.dbstate @@ -253,7 +253,7 @@ class GeoEvents(GeoGraphyView): self._append_to_places_list(descr1, None, None, latitude, longitude, - descr2, + descr2, eventyear, event.get_type(), None, # person.gramps_id @@ -268,7 +268,7 @@ class GeoEvents(GeoGraphyView): def _createmap(self,obj): """ - Create all markers for each people's event in the database which has + Create all markers for each people's event in the database which has a lat/lon. """ dbstate = self.dbstate @@ -373,10 +373,10 @@ class GeoEvents(GeoGraphyView): None, event.button, event.time) return 1 - def add_specific_menu(self, menu, event, lat, lon): - """ + def add_specific_menu(self, menu, event, lat, lon): + """ Add specific entry to the navigation menu. - """ + """ add_item = Gtk.MenuItem() add_item.show() menu.append(add_item) diff --git a/gramps/plugins/view/geofamclose.py b/gramps/plugins/view/geofamclose.py index a800c8ff4..442f851c8 100644 --- a/gramps/plugins/view/geofamclose.py +++ b/gramps/plugins/view/geofamclose.py @@ -91,8 +91,8 @@ _UI_DEF = '''\ - - + + @@ -136,7 +136,7 @@ class GeoFamClose(GeoGraphyView): def __init__(self, pdata, dbstate, uistate, nav_group=0): GeoGraphyView.__init__(self, _("Have these two families been able to meet?"), - pdata, dbstate, uistate, + pdata, dbstate, uistate, FamilyBookmarks, nav_group) self.dbstate = dbstate @@ -171,11 +171,11 @@ class GeoFamClose(GeoGraphyView): def get_stock(self): """ Returns the name of the stock icon to use for the display. - This assumes that this icon has already been registered + This assumes that this icon has already been registered as a stock icon. """ return 'geo-show-family' - + def get_viewtype_stock(self): """Type of view in category """ @@ -224,7 +224,7 @@ class GeoFamClose(GeoGraphyView): 'gramps_id' : family.gramps_id, } return label - + def goto_handle(self, handle=None): """ Rebuild the tree with the given family handle as reference. @@ -385,7 +385,7 @@ class GeoFamClose(GeoGraphyView): self.possible_meeting(child, ref_person) else: self.possible_meeting(person, ref_person) - + def _possible_family_meeting(self, reference, family): """ @@ -421,11 +421,11 @@ class GeoFamClose(GeoGraphyView): self._expose_persone_to_family(child, family) else: self._expose_persone_to_family(person, family) - + def _createmap_for_one_person(self, person, color, place_list, reference): """ - Create all markers for each people's event in the database which has + Create all markers for each people's event in the database which has a lat/lon. """ self.place_list = [] @@ -585,7 +585,7 @@ class GeoFamClose(GeoGraphyView): def _createmap(self, family_x, color, place_list, reference): """ - Create all markers for each family's person in the database which has + Create all markers for each family's person in the database which has a lat/lon. """ dbstate = self.dbstate @@ -633,7 +633,7 @@ class GeoFamClose(GeoGraphyView): continue else: events.append(plce[10]) - + if plce[0] != oldplace: message = "%s :" % plce[0] self.add_place_bubble_message(event, lat, lon, @@ -682,10 +682,10 @@ class GeoFamClose(GeoGraphyView): None, event.button, event.time) return 0 - def add_specific_menu(self, menu, event, lat, lon): - """ + def add_specific_menu(self, menu, event, lat, lon): + """ Add specific entry to the navigation menu. - """ + """ add_item = Gtk.MenuItem() add_item.show() menu.append(add_item) @@ -720,7 +720,7 @@ class GeoFamClose(GeoGraphyView): 'The value is in tenth of degree.'), 1, line_wrap=False) self.config_meeting_slider = configdialog.add_slider(grid, - "", + "", 2, 'geography.maximum_meeting_zone', (1, 9)) return _('The selection parameters'), grid diff --git a/gramps/plugins/view/geofamily.py b/gramps/plugins/view/geofamily.py index 788b977f2..ee2d939fc 100644 --- a/gramps/plugins/view/geofamily.py +++ b/gramps/plugins/view/geofamily.py @@ -95,8 +95,8 @@ _UI_DEF = '''\ - - + + @@ -117,7 +117,7 @@ class GeoFamily(GeoGraphyView): def __init__(self, pdata, dbstate, uistate, nav_group=0): GeoGraphyView.__init__(self, _('Family places map'), - pdata, dbstate, uistate, + pdata, dbstate, uistate, FamilyBookmarks, nav_group) self.dbstate = dbstate @@ -142,11 +142,11 @@ class GeoFamily(GeoGraphyView): def get_stock(self): """ Returns the name of the stock icon to use for the display. - This assumes that this icon has already been registered + This assumes that this icon has already been registered as a stock icon. """ return 'geo-show-family' - + def get_viewtype_stock(self): """Type of view in category """ @@ -298,7 +298,7 @@ class GeoFamily(GeoGraphyView): 'gramps_id' : family.gramps_id, } return label - + def _createmap_for_one_family(self, family): """ Create all markers for one family : all event's places with a lat/lon. @@ -357,7 +357,7 @@ class GeoFamily(GeoGraphyView): def _createmap(self, family_x): """ - Create all markers for each people's event in the database which has + Create all markers for each people's event in the database which has a lat/lon. """ self.place_list = [] @@ -450,10 +450,10 @@ class GeoFamily(GeoGraphyView): None, event.button, event.time) return 1 - def add_specific_menu(self, menu, event, lat, lon): - """ + def add_specific_menu(self, menu, event, lat, lon): + """ Add specific entry to the navigation menu. - """ + """ return def get_default_gramplets(self): diff --git a/gramps/plugins/view/geography.gpr.py b/gramps/plugins/view/geography.gpr.py index c4d33393f..17bdc9e4f 100644 --- a/gramps/plugins/view/geography.gpr.py +++ b/gramps/plugins/view/geography.gpr.py @@ -25,7 +25,7 @@ # #------------------------------------------------------------------------ -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" from gi import Repository @@ -63,7 +63,7 @@ if not OSMGPSMAP: from gramps.gui.dialog import MessageHideDialog from gramps.gen.const import URL_WIKISTRING osmgps_dict = { 'gramps_wiki_build_osmgps_url' : - URL_WIKISTRING + + URL_WIKISTRING + "GEPS_029:_GTK3-GObject_introspection" "_Conversion#OsmGpsMap_for_Geography" } title = _("OsmGpsMap module not loaded.") @@ -73,7 +73,7 @@ if not OSMGPSMAP: MessageHideDialog(title, message, 'interface.ignore-osmgpsmap') else: # Load the view only if osmgpsmap library is present. - register(VIEW, + register(VIEW, id = 'geo1', name = _("All known places for one Person"), description = _("A view showing the places visited by " @@ -89,8 +89,8 @@ else: #order = START, stock_icon = 'geo-show-person', ) - - register(VIEW, + + register(VIEW, id = 'geo2', name = _("All known places for one Family"), description = _("A view showing the places visited by " @@ -106,8 +106,8 @@ else: #order = START, stock_icon = 'geo-show-family', ) - - register(VIEW, + + register(VIEW, id = 'geo3', name = _("Every residence or move for a person and any descendants"), description = _("A view showing all the places visited by " @@ -126,7 +126,7 @@ else: stock_icon = 'geo-show-family', ) - register(VIEW, + register(VIEW, id = 'geo4', name = _("Have these two families been able to meet?"), description = _("A view showing the places visited by " @@ -143,8 +143,8 @@ else: #order = START, stock_icon = 'geo-show-family', ) - - register(VIEW, + + register(VIEW, id = 'geo5', name = _("Have they been able to meet?"), description = _("A view showing the places visited by " @@ -161,8 +161,8 @@ else: #order = START, stock_icon = 'gramps-relation', ) - - register(VIEW, + + register(VIEW, id = 'geo6', name = _("All known Places"), description = _("A view showing all places of the database."), @@ -177,8 +177,8 @@ else: #order = START, stock_icon = 'geo-show-place', ) - - register(VIEW, + + register(VIEW, id = 'geo7', name = _("All places related to Events"), description = _("A view showing all the event " @@ -194,4 +194,4 @@ else: #order = START, stock_icon = 'geo-show-event', ) - + diff --git a/gramps/plugins/view/geomoves.py b/gramps/plugins/view/geomoves.py index 7d443cd91..97603ce3f 100644 --- a/gramps/plugins/view/geomoves.py +++ b/gramps/plugins/view/geomoves.py @@ -96,8 +96,8 @@ _UI_DEF = '''\ - - + + @@ -140,7 +140,7 @@ class GeoMoves(GeoGraphyView): def __init__(self, pdata, dbstate, uistate, nav_group=0): GeoGraphyView.__init__(self, _("Descendance of the active person."), - pdata, dbstate, uistate, + pdata, dbstate, uistate, PersonBookmarks, nav_group) self.dbstate = dbstate @@ -174,11 +174,11 @@ class GeoMoves(GeoGraphyView): def get_stock(self): """ Returns the name of the stock icon to use for the display. - This assumes that this icon has already been registered + This assumes that this icon has already been registered as a stock icon. """ return 'geo-show-family' - + def get_viewtype_stock(self): """Type of view in category """ @@ -261,7 +261,7 @@ class GeoMoves(GeoGraphyView): def _createmap_for_one_person(self, person, color): """ - Create all markers for each people's event in the database which has + Create all markers for each people's event in the database which has a lat/lon. """ self.place_list = [] @@ -447,7 +447,7 @@ class GeoMoves(GeoGraphyView): def _createmap(self, person): """ - Create all markers for each family's person in the database which has + Create all markers for each family's person in the database which has a lat/lon. """ dbstate = self.dbstate @@ -491,7 +491,7 @@ class GeoMoves(GeoGraphyView): plxp = self.dbstate.db.get_person_from_gramps_id(plx) birth = "0000" death = "0000" - low_date = "9999" + low_date = "9999" high_date = "0000" for event_ref in plxp.get_event_ref_list(): if not event_ref: @@ -614,10 +614,10 @@ class GeoMoves(GeoGraphyView): None, event.button, event.time) return 1 - def add_specific_menu(self, menu, event, lat, lon): - """ + def add_specific_menu(self, menu, event, lat, lon): + """ Add specific entry to the navigation menu. - """ + """ return def get_default_gramplets(self): @@ -640,14 +640,14 @@ class GeoMoves(GeoGraphyView): _('The maximum number of generations.\n'), 1, line_wrap=False) configdialog.add_slider(grid, - "", + "", 2, 'geography.maximum_generations', (1, 20)) configdialog.add_text(grid, _('Time in milliseconds between drawing two generations.\n'), 3, line_wrap=False) configdialog.add_slider(grid, - "", + "", 4, 'geography.generation_interval', (500, 3000)) return _('The parameters for moves'), grid diff --git a/gramps/plugins/view/geoperson.py b/gramps/plugins/view/geoperson.py index f9ae36b99..be039aed6 100644 --- a/gramps/plugins/view/geoperson.py +++ b/gramps/plugins/view/geoperson.py @@ -100,8 +100,8 @@ _UI_DEF = '''\ - - + + @@ -148,7 +148,7 @@ class GeoPerson(GeoGraphyView): def __init__(self, pdata, dbstate, uistate, nav_group=0): GeoGraphyView.__init__(self, _("Person places map"), - pdata, dbstate, uistate, + pdata, dbstate, uistate, PersonBookmarks, nav_group) self.dbstate = dbstate @@ -173,11 +173,11 @@ class GeoPerson(GeoGraphyView): def get_stock(self): """ Returns the name of the stock icon to use for the display. - This assumes that this icon has already been registered + This assumes that this icon has already been registered as a stock icon. """ return 'geo-show-person' - + def get_viewtype_stock(self): """Type of view in category """ @@ -277,7 +277,7 @@ class GeoPerson(GeoGraphyView): i += 1 self.large_move = False stepyear = 1 - # if geography.speed = 100 => 100ms => 1s per 10 years. + # if geography.speed = 100 => 100ms => 1s per 10 years. # For a 100 years person, it takes 10 secondes. # if large_move, one step is the difflat or difflon / geography.steps # in this case, stepyear is >= 9000 @@ -289,7 +289,7 @@ class GeoPerson(GeoGraphyView): def _createmap(self,obj): """ - Create all markers for each people's event in the database which has + Create all markers for each people's event in the database which has a lat/lon. """ dbstate = self.dbstate @@ -494,10 +494,10 @@ class GeoPerson(GeoGraphyView): None, event.button, event.time) return 1 - def add_specific_menu(self, menu, event, lat, lon): - """ + def add_specific_menu(self, menu, event, lat, lon): + """ Add specific entry to the navigation menu. - """ + """ add_item = Gtk.MenuItem() add_item.show() menu.append(add_item) @@ -527,14 +527,14 @@ class GeoPerson(GeoGraphyView): _('Animation speed in milliseconds (big value means slower)'), 1, line_wrap=False) configdialog.add_slider(grid, - "", + "", 2, 'geography.speed', (100, 1000)) configdialog.add_text(grid, _('How many steps between two markers when we are on large move ?'), 3, line_wrap=False) configdialog.add_slider(grid, - "", + "", 4, 'geography.steps', (10, 100)) configdialog.add_text(grid, @@ -542,7 +542,7 @@ class GeoPerson(GeoGraphyView): 'The value is in tenth of degree.'), 5, line_wrap=False) configdialog.add_slider(grid, - "", + "", 6, 'geography.maximum_lon_lat', (5, 50)) return _('The animation parameters'), grid diff --git a/gramps/plugins/view/geoplaces.py b/gramps/plugins/view/geoplaces.py index 3c7f3d8a7..6cc477921 100644 --- a/gramps/plugins/view/geoplaces.py +++ b/gramps/plugins/view/geoplaces.py @@ -95,8 +95,8 @@ _UI_DEF = '''\ - - + + @@ -117,7 +117,7 @@ class GeoPlaces(GeoGraphyView): def __init__(self, pdata, dbstate, uistate, nav_group=0): GeoGraphyView.__init__(self, _('Places map'), - pdata, dbstate, uistate, + pdata, dbstate, uistate, PlaceBookmarks, nav_group) self.dbstate = dbstate @@ -143,11 +143,11 @@ class GeoPlaces(GeoGraphyView): def get_stock(self): """ Returns the name of the stock icon to use for the display. - This assumes that this icon has already been registered + This assumes that this icon has already been registered as a stock icon. """ return 'geo-show-place' - + def get_viewtype_stock(self): """Type of view in category """ @@ -222,7 +222,7 @@ class GeoPlaces(GeoGraphyView): def _createmap(self,place_x): """ - Create all markers for each people's event in the database which has + Create all markers for each people's event in the database which has a lat/lon. """ dbstate = self.dbstate @@ -363,10 +363,10 @@ class GeoPlaces(GeoGraphyView): None, event.button, event.time) return 1 - def add_specific_menu(self, menu, event, lat, lon): - """ + def add_specific_menu(self, menu, event, lat, lon): + """ Add specific entry to the navigation menu. - """ + """ add_item = Gtk.MenuItem() add_item.show() menu.append(add_item) diff --git a/gramps/plugins/view/mediaview.py b/gramps/plugins/view/mediaview.py index 21cdc465e..0acd7919b 100644 --- a/gramps/plugins/view/mediaview.py +++ b/gramps/plugins/view/mediaview.py @@ -10,7 +10,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -89,7 +89,7 @@ class MediaView(ListView): COL_PRIV = 5 COL_TAGS = 6 COL_CHAN = 7 - + # column definitions COLUMNS = [ (_('Title'), TEXT, None), @@ -108,8 +108,8 @@ class MediaView(ListView): ('columns.rank', [COL_TITLE, COL_ID, COL_TYPE, COL_PATH, COL_DATE, COL_PRIV, COL_TAGS, COL_CHAN]), ('columns.size', [200, 75, 100, 200, 150, 40, 100, 150]) - ) - + ) + ADD_MSG = _("Add a new media object") EDIT_MSG = _("Edit the selected media object") DEL_MSG = _("Delete the selected media object") @@ -120,23 +120,23 @@ class MediaView(ListView): def __init__(self, pdata, dbstate, uistate, nav_group=0): signal_map = { - 'media-add' : self.row_add, - 'media-update' : self.row_update, - 'media-delete' : self.row_delete, + 'media-add' : self.row_add, + 'media-update' : self.row_update, + 'media-delete' : self.row_delete, 'media-rebuild' : self.object_build, } ListView.__init__( - self, _('Media'), pdata, dbstate, uistate, - MediaModel, + self, _('Media'), pdata, dbstate, uistate, + MediaModel, signal_map, MediaBookmarks, nav_group, filter_class=MediaSidebarFilter, multiple=True) self.func_list.update({ - 'J' : self.jump, - 'BackSpace' : self.key_delete, + 'J' : self.jump, + 'BackSpace' : self.key_delete, }) self.additional_uis.append(self.additional_ui()) @@ -146,7 +146,7 @@ class MediaView(ListView): def drag_info(self): """ - Return the type of DND targets that this view will accept. For Media + Return the type of DND targets that this view will accept. For Media View, we will accept media objects. """ return DdTargets.MEDIAOBJ @@ -167,9 +167,9 @@ class MediaView(ListView): """ Handle the standard gtk interface for drag_data_received. - If the selection data is define, extract the value from sel_data.data, + If the selection data is define, extract the value from sel_data.data, and decide if this is a move or a reorder. - The only data we accept on mediaview is dropping a file, so URI_LIST. + The only data we accept on mediaview is dropping a file, so URI_LIST. We assume this is what we obtain """ if not sel_data: @@ -197,7 +197,7 @@ class MediaView(ListView): with DbTxn(_("Drag Media Object"), self.dbstate.db) as trans: self.dbstate.db.add_object(photo, trans) widget.emit_stop_by_name('drag_data_received') - + def define_actions(self): """ Defines the UIManager actions specific to Media View. We need to make @@ -206,18 +206,18 @@ class MediaView(ListView): """ ListView.define_actions(self) - self._add_action('FilterEdit', None, _('Media Filter Editor'), + self._add_action('FilterEdit', None, _('Media Filter Editor'), callback=self.filter_editor) - self._add_action('OpenMedia', 'gramps-viewmedia', _('View'), - tip=_("View in the default viewer"), + self._add_action('OpenMedia', 'gramps-viewmedia', _('View'), + tip=_("View in the default viewer"), callback=self.view_media) - self._add_action('OpenContainingFolder', None, - _('Open Containing _Folder'), - tip=_("Open the folder containing the media file"), + self._add_action('OpenContainingFolder', None, + _('Open Containing _Folder'), + tip=_("Open the folder containing the media file"), callback=self.open_containing_folder) self._add_action('QuickReport', None, _("Quick View"), None, None, None) - + def view_media(self, obj): """ Launch external viewers for the selected objects. @@ -280,8 +280,8 @@ class MediaView(ListView): - - + + diff --git a/gramps/plugins/view/noteview.py b/gramps/plugins/view/noteview.py index 3f5599384..2e2bf0fd1 100644 --- a/gramps/plugins/view/noteview.py +++ b/gramps/plugins/view/noteview.py @@ -73,7 +73,7 @@ class NoteView(ListView): COL_PRIV = 3 COL_TAGS = 4 COL_CHAN = 5 - + # column definitions COLUMNS = [ (_('Preview'), TEXT, None), @@ -86,7 +86,7 @@ class NoteView(ListView): # default setting with visible columns, order of the col, and their size CONFIGSETTINGS = ( ('columns.visible', [COL_PREVIEW, COL_ID, COL_TYPE]), - ('columns.rank', [COL_PREVIEW, COL_ID, COL_TYPE, COL_PRIV, COL_TAGS, + ('columns.rank', [COL_PREVIEW, COL_ID, COL_TYPE, COL_PRIV, COL_TAGS, COL_CHAN]), ('columns.size', [350, 75, 100, 40, 100, 100])) @@ -171,8 +171,8 @@ class NoteView(ListView): - - + + diff --git a/gramps/plugins/view/pedigreeview.py b/gramps/plugins/view/pedigreeview.py index c371f0958..b01b512fd 100644 --- a/gramps/plugins/view/pedigreeview.py +++ b/gramps/plugins/view/pedigreeview.py @@ -90,7 +90,7 @@ class _PersonWidgetBase(Gtk.DrawingArea): Default set up for person widgets. Set up drag options and button release events. """ - + def __init__(self, view, format_helper, person): GObject.GObject.__init__(self) self.view = view @@ -265,7 +265,7 @@ class PersonBoxWidgetCairo(_PersonWidgetBase): self.set_size_request(max(xmin, minw), max(ymin, minh)) alloc = self.get_allocation() - + alw = self.get_allocated_width() alh = self.get_allocated_height() @@ -323,7 +323,7 @@ class PersonBoxWidgetCairo(_PersonWidgetBase): context.stroke() context.restore() context.save() - + # text context.move_to(5, 4) context.set_source_rgb(0, 0, 0) @@ -344,7 +344,7 @@ class LineWidget(Gtk.DrawingArea): self.frel = frel self.mrel = mrel self.direction = direction - + self.connect("draw", self.expose) def expose(self, widget, context): @@ -397,13 +397,13 @@ class LineWidget(Gtk.DrawingArea): """ Draw a link between parent and child. """ - + cr.set_line_width(3) if rela: cr.set_dash([], 0) #SOLID else: cr.set_dash([9.], 1) #DASH - + self.draw_line(cr, parent_side, side, centre, side) self.draw_line(cr, centre, side, centre, middle, True) self.draw_line(cr, centre, middle, child_side, middle, True) @@ -474,7 +474,7 @@ class LineWidget2(Gtk.DrawingArea): self.draw_line(context, child_x, child_y, mid_x, mid_y) self.draw_line(context, mid_x, mid_y, parent_x, parent_y, True) - + def draw_line(self, cr, x_from, y_from, x_to, y_to, join=False): """ Draw a single line in a link. @@ -510,7 +510,7 @@ class PedigreeView(NavigationView): ) def __init__(self, pdata, dbstate, uistate, nav_group=0): - NavigationView.__init__(self, _('Pedigree'), pdata, dbstate, uistate, + NavigationView.__init__(self, _('Pedigree'), pdata, dbstate, uistate, PersonBookmarks, nav_group) self.func_list.update({ @@ -521,9 +521,9 @@ class PedigreeView(NavigationView): self.dbstate = dbstate self.dbstate.connect('database-changed', self.change_db) uistate.connect('nameformat-changed', self.person_rebuild) - + self.format_helper = FormattingHelper(self.dbstate) - + # Depth of tree. self._depth = 1 # Variables for drag and scroll @@ -538,7 +538,7 @@ class PedigreeView(NavigationView): self.additional_uis.append(self.additional_ui()) # Automatic resize - self.force_size = self._config.get('interface.pedview-tree-size') + self.force_size = self._config.get('interface.pedview-tree-size') # Nice tree self.tree_style = self._config.get('interface.pedview-layout') # Show photos of persons @@ -566,7 +566,7 @@ class PedigreeView(NavigationView): The category stock icon """ return 'gramps-pedigree' - + def get_viewtype_stock(self): """Type of view in category """ @@ -578,8 +578,8 @@ class PedigreeView(NavigationView): contains the interface. This containter will be inserted into a Gtk.ScrolledWindow page. """ - self.scrolledwindow = Gtk.ScrolledWindow(hadjustment=None, - vadjustment=None) + self.scrolledwindow = Gtk.ScrolledWindow(hadjustment=None, + vadjustment=None) self.scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.scrolledwindow.add_events(Gdk.EventMask.SCROLL_MASK) @@ -659,8 +659,8 @@ class PedigreeView(NavigationView): at the beginning of the history. """ NavigationView.define_actions(self) - - self._add_action('FilterEdit', None, _('Person Filter Editor'), + + self._add_action('FilterEdit', None, _('Person Filter Editor'), callback=self.cb_filter_editor) def cb_filter_editor(self, obj): @@ -668,7 +668,7 @@ class PedigreeView(NavigationView): Display the person filter editor. """ try: - FilterEditor('Person', CUSTOM_FILTERS, + FilterEditor('Person', CUSTOM_FILTERS, self.dbstate, self.uistate) except WindowActiveError: return @@ -700,7 +700,7 @@ class PedigreeView(NavigationView): self._add_db_signal('family-add', self.person_rebuild) self._add_db_signal('family-delete', self.person_rebuild) self._add_db_signal('family-rebuild', self.person_rebuild) - + def change_db(self, db): """ Callback associated with DbState. Whenever the database @@ -723,7 +723,7 @@ class PedigreeView(NavigationView): def can_configure(self): """ - See :class:`~gui.views.pageview.PageView + See :class:`~gui.views.pageview.PageView :return: bool """ return True @@ -871,7 +871,7 @@ class PedigreeView(NavigationView): ymax = 0 if self.tree_style == 0: xmax = 2 * size - ymax = 2 ** size + ymax = 2 ** size elif self.tree_style == 1: xmax = 2 * size + 2 ymax = [0, 10, 14, 16, 32][size - 1] @@ -964,7 +964,7 @@ class PedigreeView(NavigationView): if pbw: self.attach_widget(table_widget, pbw, xmax, x_pos, x_pos+width, y_pos, y_pos+height) - + #################################################################### # Connection lines #################################################################### @@ -987,7 +987,7 @@ class PedigreeView(NavigationView): line.connect("button-press-event", self.cb_relation_button_press, lst[i][2].get_handle()) - + self.attach_widget(table_widget, line, xmax, x_pos, x_pos+width, y_pos, y_pos+height) @@ -1045,7 +1045,7 @@ class PedigreeView(NavigationView): line.set_tooltip_text( self.format_helper.format_relation( lst[((i+1) // 2) - 1][2], 11)) - + self.attach_widget(table_widget, line, xmax, x_pos, x_pos+width, y_pos, y_pos+height) @@ -1081,7 +1081,7 @@ class PedigreeView(NavigationView): self.attach_widget(table_widget, label, xmax, x_pos, x_pos+width, y_pos, y_pos+height) - + ######################################################################## # Add navigation arrows ######################################################################## @@ -1115,7 +1115,7 @@ class PedigreeView(NavigationView): ymid = ymax // 2 self.attach_widget(table_widget, button, xmax, 0, 1, ymid, ymid +1) - + button = Gtk.Button() button.add(Gtk.Arrow.new(parent_arrow, Gtk.ShadowType.IN)) if lst[1]: @@ -1124,7 +1124,7 @@ class PedigreeView(NavigationView): button.set_tooltip_text(_("Jump to father")) else: button.set_sensitive(False) - + ymid = ymax // 4 self.attach_widget(table_widget, button, xmax, xmax, xmax+1, ymid-1, ymid+2) @@ -1137,7 +1137,7 @@ class PedigreeView(NavigationView): button.set_tooltip_text(_("Jump to mother")) else: button.set_sensitive(False) - + ymid = ymax // 4 * 3 self.attach_widget(table_widget, button, xmax, xmax, xmax+1, ymid-1, ymid+2) @@ -1187,7 +1187,7 @@ class PedigreeView(NavigationView): except KeyError: # fill unused cells label = Gtk.Label(label="%d,%d"%(x_pos, y_pos)) - frame = Gtk.ScrolledWindow(hadjustment=None, + frame = Gtk.ScrolledWindow(hadjustment=None, vadjustment=None) frame.set_shadow_type(Gtk.ShadowType.NONE) frame.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.NEVER) @@ -1293,7 +1293,7 @@ class PedigreeView(NavigationView): """ person = self.dbstate.db.get_person_from_handle(person_handle) if person: - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_CLIPBOARD) clipboard.set_text(self.format_helper.format_person(person, 11), -1) return True @@ -1306,7 +1306,7 @@ class PedigreeView(NavigationView): """ family = self.dbstate.db.get_family_from_handle(family_handle) if family: - clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), + clipboard = Gtk.Clipboard.get_for_display(Gdk.Display.get_default(), Gdk.SELECTION_CLIPBOARD) clipboard.set_text(self.format_helper.format_relation(family, 11), -1) return True @@ -1559,12 +1559,12 @@ class PedigreeView(NavigationView): Add frequently used settings to the menu. Most settings will be set from the configuration dialog. """ - # Separator. + # Separator. item = Gtk.SeparatorMenuItem() item.show() menu.append(item) - # Mouse scroll direction setting. + # Mouse scroll direction setting. item = Gtk.MenuItem(label=_("Mouse scroll direction")) item.set_submenu(Gtk.Menu()) scroll_direction_menu = item.get_submenu() @@ -1907,10 +1907,10 @@ class PedigreeView(NavigationView): self.add_settings_to_menu(self.menu) self.menu.popup(None, None, None, None, 0, event.time) return 1 - + def cb_update_show_images(self, client, cnxn_id, entry, data): """ - Called when the configuration menu changes the images setting. + Called when the configuration menu changes the images setting. """ if entry == 'True': self.show_images = True @@ -1920,7 +1920,7 @@ class PedigreeView(NavigationView): def cb_update_show_marriage(self, client, cnxn_id, entry, data): """ - Called when the configuration menu changes the marriage data setting. + Called when the configuration menu changes the marriage data setting. """ if entry == 'True': self.show_marriage_data = True @@ -1930,7 +1930,7 @@ class PedigreeView(NavigationView): def cb_update_show_unknown_people(self, client, cnxn_id, entry, data): """ - Called when the configuration menu changes the unknown people setting. + Called when the configuration menu changes the unknown people setting. """ if entry == 'True': self.show_unknown_people = True @@ -1940,7 +1940,7 @@ class PedigreeView(NavigationView): def cb_update_layout(self, obj, constant): """ - Called when the configuration menu changes the layout. + Called when the configuration menu changes the layout. """ entry = obj.get_active() self._config.set(constant, entry) @@ -1958,14 +1958,14 @@ class PedigreeView(NavigationView): def cb_update_tree_direction(self, client, cnxn_id, entry, data): """ - Called when the configuration menu changes the tree direction. + Called when the configuration menu changes the tree direction. """ self.tree_direction = int(entry) self.rebuild_trees(self.get_active()) def cb_update_tree_size(self, client, cnxn_id, entry, data): """ - Called when the configuration menu changes the tree size. + Called when the configuration menu changes the tree size. """ self.force_size = int(entry) self.rebuild_trees(self.get_active()) @@ -1989,9 +1989,9 @@ class PedigreeView(NavigationView): def _get_configure_page_funcs(self): """ - Return a list of functions that create gtk elements to use in the + Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog - + :return: list of functions """ return [self.config_panel] @@ -2005,31 +2005,31 @@ class PedigreeView(NavigationView): grid.set_column_spacing(6) grid.set_row_spacing(6) - configdialog.add_checkbox(grid, - _('Show images'), + configdialog.add_checkbox(grid, + _('Show images'), 0, 'interface.pedview-show-images') - configdialog.add_checkbox(grid, - _('Show marriage data'), + configdialog.add_checkbox(grid, + _('Show marriage data'), 1, 'interface.pedview-show-marriage') - configdialog.add_checkbox(grid, - _('Show unknown people'), + configdialog.add_checkbox(grid, + _('Show unknown people'), 2, 'interface.pedview-show-unknown-people') - configdialog.add_combo(grid, - _('Tree style'), + configdialog.add_combo(grid, + _('Tree style'), 4, 'interface.pedview-layout', ((0, _('Standard')), (1, _('Compact')), (2, _('Expanded'))), callback=self.cb_update_layout) - configdialog.add_combo(grid, - _('Tree direction'), + configdialog.add_combo(grid, + _('Tree direction'), 5, 'interface.pedview-tree-direction', ((0, _('Vertical (↓)')), (1, _('Vertical (↑)')), (2, _('Horizontal (→)')), (3, _('Horizontal (←)')))) - self.config_size_slider = configdialog.add_slider(grid, - _('Tree size'), + self.config_size_slider = configdialog.add_slider(grid, + _('Tree size'), 6, 'interface.pedview-tree-size', (2, 9)) diff --git a/gramps/plugins/view/persontreeview.py b/gramps/plugins/view/persontreeview.py index ac05aca0d..f13c39a17 100644 --- a/gramps/plugins/view/persontreeview.py +++ b/gramps/plugins/view/persontreeview.py @@ -71,7 +71,7 @@ class PersonTreeView(BasePersonView): Override the default icon. Set for hierarchical view. """ return 'gramps-tree-group' - + def define_actions(self): """ Define actions for the popup menu specific to the tree view. @@ -79,10 +79,10 @@ class PersonTreeView(BasePersonView): BasePersonView.define_actions(self) self.all_action.add_actions([ - ('OpenAllNodes', None, _("Expand all Nodes"), None, None, - self.open_all_nodes), - ('CloseAllNodes', None, _("Collapse all Nodes"), None, None, - self.close_all_nodes), + ('OpenAllNodes', None, _("Expand all Nodes"), None, None, + self.open_all_nodes), + ('CloseAllNodes', None, _("Collapse all Nodes"), None, None, + self.close_all_nodes), ]) def additional_ui(self): @@ -124,8 +124,8 @@ class PersonTreeView(BasePersonView): - - + + @@ -155,7 +155,7 @@ class PersonTreeView(BasePersonView): def add(self, obj): person = Person() - + # attempt to get the current surname (model, pathlist) = self.selection.get_selected_rows() name = Name() diff --git a/gramps/plugins/view/placetreeview.py b/gramps/plugins/view/placetreeview.py index 8169e2e70..556b90cf5 100644 --- a/gramps/plugins/view/placetreeview.py +++ b/gramps/plugins/view/placetreeview.py @@ -60,13 +60,13 @@ class PlaceTreeView(PlaceBaseView): Override the default icon. Set for hierarchical view. """ return 'gramps-tree-group' - + def define_actions(self): """ Define actions for the popup menu specific to the tree view. """ PlaceBaseView.define_actions(self) - + self._add_action('OpenBranch', None, _("Expand this Entire Group"), callback=self.open_branch) self._add_action('CloseBranch', None, _("Collapse this Entire Group"), @@ -112,8 +112,8 @@ class PlaceTreeView(PlaceBaseView): - - + + @@ -153,7 +153,7 @@ class PlaceTreeView(PlaceBaseView): place = Place() if len(parent_list) > 0: place.placeref_list = parent_list - + try: EditPlace(self.dbstate, self.uistate, [], place) except WindowActiveError: diff --git a/gramps/plugins/view/relview.py b/gramps/plugins/view/relview.py index a0605bbba..54721d535 100644 --- a/gramps/plugins/view/relview.py +++ b/gramps/plugins/view/relview.py @@ -55,7 +55,7 @@ from gi.repository import Pango # Gramps Modules # #------------------------------------------------------------------------- -from gramps.gen.lib import (ChildRef, EventRoleType, EventType, Family, +from gramps.gen.lib import (ChildRef, EventRoleType, EventType, Family, FamilyRelType, Name, Person, Surname) from gramps.gen.lib.date import Today from gramps.gen.db import DbTxn @@ -77,14 +77,14 @@ from gramps.gui.selectors import SelectorFactory from gramps.gen.errors import WindowActiveError from gramps.gui.views.bookmarks import PersonBookmarks from gramps.gen.const import CUSTOM_FILTERS -from gramps.gen.utils.db import (get_birth_or_fallback, get_death_or_fallback, +from gramps.gen.utils.db import (get_birth_or_fallback, get_death_or_fallback, preset_name) from gramps.gui.ddtargets import DdTargets _GenderCode = { - Person.MALE : '\u2642', - Person.FEMALE : '\u2640', - Person.UNKNOWN : '\u2650', + Person.MALE : '\u2642', + Person.FEMALE : '\u2640', + Person.UNKNOWN : '\u2650', } _NAME_START = 0 @@ -94,7 +94,7 @@ _DATA_START = _LABEL_STOP _DATA_STOP = _DATA_START+1 _BTN_START = _DATA_STOP _BTN_STOP = _BTN_START+2 -_PLABEL_START = 1 +_PLABEL_START = 1 _PLABEL_STOP = _PLABEL_START+1 _PDATA_START = _PLABEL_STOP _PDATA_STOP = _PDATA_START+2 @@ -120,7 +120,7 @@ _RIGHT_BUTTON = 3 class RelationshipView(NavigationView): """ - View showing a textual representation of the relationships of the + View showing a textual representation of the relationships of the active person """ #settings in the config file @@ -134,9 +134,9 @@ class RelationshipView(NavigationView): def __init__(self, pdata, dbstate, uistate, nav_group=0): NavigationView.__init__(self, _('Relationships'), - pdata, dbstate, uistate, + pdata, dbstate, uistate, PersonBookmarks, - nav_group) + nav_group) self.func_list.update({ 'J' : self.jump, @@ -182,7 +182,7 @@ class RelationshipView(NavigationView): def can_configure(self): """ - See :class:`~gui.views.pageview.PageView + See :class:`~gui.views.pageview.PageView :return: bool """ return True @@ -275,7 +275,7 @@ class RelationshipView(NavigationView): def change_page(self): NavigationView.change_page(self) self.uistate.clear_filter_results() - + def get_stock(self): """ Return the name of the stock icon to use for the display. @@ -283,7 +283,7 @@ class RelationshipView(NavigationView): GNOME as a stock icon. """ return 'gramps-relation' - + def get_viewtype_stock(self): """Type of view in category """ @@ -291,8 +291,8 @@ class RelationshipView(NavigationView): def build_widget(self): """ - Build the widget that contains the view, see - :class:`~gui.views.pageview.PageView + Build the widget that contains the view, see + :class:`~gui.views.pageview.PageView """ container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) container.set_border_width(12) @@ -318,7 +318,7 @@ class RelationshipView(NavigationView): self.scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.scroll.show() - + vp = Gtk.Viewport() vp.set_shadow_type(Gtk.ShadowType.NONE) vp.add(self.vbox) @@ -368,8 +368,8 @@ class RelationshipView(NavigationView): - - + + @@ -407,20 +407,20 @@ class RelationshipView(NavigationView): _("Add a new family with person as parent"), self.add_spouse), ('AddParents', 'gramps-parents-add', _('Add'), None , _("Add a new set of parents"), self.add_parents), - ('AddParentsMenu', 'gramps-parents-add', _('Add New Parents...'), + ('AddParentsMenu', 'gramps-parents-add', _('Add New Parents...'), None, _("Add a new set of parents"), self.add_parents), - ('ShareFamily', 'gramps-parents-open', _('Share'), - None , _("Add person as child to an existing family"), + ('ShareFamily', 'gramps-parents-open', _('Share'), + None , _("Add person as child to an existing family"), self.select_parents), - ('ShareFamilyMenu', 'gramps-parents-open', - _('Add Existing Parents...'), None , - _("Add person as child to an existing family"), + ('ShareFamilyMenu', 'gramps-parents-open', + _('Add Existing Parents...'), None , + _("Add person as child to an existing family"), self.select_parents), ]) - - self._add_action('FilterEdit', None, _('Person Filter Editor'), + + self._add_action('FilterEdit', None, _('Person Filter Editor'), callback=self.filter_editor) - + self._add_action_group(self.order_action) self._add_action_group(self.family_action) @@ -429,7 +429,7 @@ class RelationshipView(NavigationView): def filter_editor(self, obj): try: - FilterEditor('Person', CUSTOM_FILTERS, + FilterEditor('Person', CUSTOM_FILTERS, self.dbstate, self.uistate) except WindowActiveError: return @@ -463,7 +463,7 @@ class RelationshipView(NavigationView): self.change_person(active_person) else: self.change_person(None) - + def change_person(self, obj): self.change_active(obj) try: @@ -524,9 +524,9 @@ class RelationshipView(NavigationView): else: self.write_label("%s:" % _('Parents'), None, True, person) self.row += 1 - + family_handle_list = person.get_family_handle_list() - + if not self.reorder_sensitive: self.reorder_sensitive = len(family_handle_list)> 1 @@ -562,7 +562,7 @@ class RelationshipView(NavigationView): label = widgets.DualMarkupLabel(text, _GenderCode[person.gender], halign=Gtk.Align.END) if self._config.get('preferences.releditbtn'): - button = widgets.IconButton(self.edit_button_press, + button = widgets.IconButton(self.edit_button_press, person.handle) button.set_tooltip_text(_('Edit %s') % name) else: @@ -617,7 +617,7 @@ class RelationshipView(NavigationView): age = death_date - birth_date subgrid.attach(widgets.BasicLabel("%s:" % death_title), 1, 2, 1, 1) - subgrid.attach(widgets.BasicLabel("%s (%s)" % + subgrid.attach(widgets.BasicLabel("%s (%s)" % (self.format_event(death), age), Pango.EllipsizeMode.END), 2, 2, 1, 1) @@ -632,7 +632,7 @@ class RelationshipView(NavigationView): else: subgrid.attach(widgets.BasicLabel("%s:" % _("Death")), 1, 2, 1, 1) - subgrid.attach(widgets.BasicLabel("%s (%s)" % (_("unknown"), age), + subgrid.attach(widgets.BasicLabel("%s (%s)" % (_("unknown"), age), Pango.EllipsizeMode.END), 2, 2, 1, 1) showed_death = True @@ -652,7 +652,7 @@ class RelationshipView(NavigationView): mobj = self.dbstate.db.get_object_from_handle(image_list[0].ref) if mobj and mobj.get_mime_type()[0:5] == "image": pixbuf = get_thumbnail_image( - media_path_full(self.dbstate.db, + media_path_full(self.dbstate.db, mobj.get_path()), rectangle=image_list[0].get_rectangle()) image = Gtk.Image() @@ -682,8 +682,8 @@ class RelationshipView(NavigationView): pname = None value = { - 'date' : displayer.display(dobj), - 'place' : pname, + 'date' : displayer.display(dobj), + 'place' : pname, } else: pname = None @@ -691,7 +691,7 @@ class RelationshipView(NavigationView): if dobj: if pname: - self.write_person_data(ename, + self.write_person_data(ename, _('%(date)s in %(place)s') % value) else: self.write_person_data(ename, '%(date)s' % value) @@ -710,8 +710,8 @@ class RelationshipView(NavigationView): pname = None value = { - 'date' : displayer.display(dobj), - 'place' : pname, + 'date' : displayer.display(dobj), + 'place' : pname, } else: pname = None @@ -754,7 +754,7 @@ class RelationshipView(NavigationView): self.expand_collapse_press, (person, family.handle)) else : - arrow = Gtk.Arrow(arrow_type=Gtk.ArrowType.RIGHT, + arrow = Gtk.Arrow(arrow_type=Gtk.ArrowType.RIGHT, shadow_type=Gtk.ShadowType.OUT) hbox.pack_start(arrow, False, True, 0) hbox.pack_start(label, True, True, 0) @@ -804,7 +804,7 @@ class RelationshipView(NavigationView): if not self.toolbar_visible and not self.dbstate.db.readonly: # Show edit-Buttons if toolbar is not visible if self.reorder_sensitive: - add = widgets.IconButton(self.reorder_button_press, None, + add = widgets.IconButton(self.reorder_button_press, None, 'view-sort-ascending') add.set_tooltip_text(ord_msg) hbox.pack_start(add, False, True, 0) @@ -820,12 +820,12 @@ class RelationshipView(NavigationView): hbox.pack_start(add, False, True, 0) if family: - edit = widgets.IconButton(self.edit_family, family.handle, + edit = widgets.IconButton(self.edit_family, family.handle, 'gtk-edit') edit.set_tooltip_text(edit_msg) hbox.pack_start(edit, False, True, 0) if not self.dbstate.db.readonly: - delete = widgets.IconButton(del_fcn, family.handle, + delete = widgets.IconButton(del_fcn, family.handle, 'list-remove') delete.set_tooltip_text(del_msg) hbox.pack_start(delete, False, True, 0) @@ -837,7 +837,7 @@ class RelationshipView(NavigationView): self.child.attach(eventbox, _BTN_START, self.row, _BTN_STOP-_BTN_START, 1) self.row += 1 - + ###################################################################### def write_parents(self, family_handle, person = None): @@ -937,12 +937,12 @@ class RelationshipView(NavigationView): self.row += 1 # now advance it else: hbox = Gtk.Box() - addchild = widgets.IconButton(self.add_child_to_fam, - family.handle, + addchild = widgets.IconButton(self.add_child_to_fam, + family.handle, 'list-add') addchild.set_tooltip_text(_('Add new child to family')) - selchild = widgets.IconButton(self.sel_child_to_fam, - family.handle, + selchild = widgets.IconButton(self.sel_child_to_fam, + family.handle, 'gtk-index') selchild.set_tooltip_text(_('Add existing child to family')) hbox.pack_start(addchild, False, True, 0) @@ -978,13 +978,13 @@ class RelationshipView(NavigationView): initial_name = False if handle: name = self.get_name(handle, True) - link_label = widgets.LinkLabel(name, self._button_press, + link_label = widgets.LinkLabel(name, self._button_press, handle, theme=self.theme) if self.use_shade: link_label.override_background_color(Gtk.StateType.NORMAL, self.color) if self._config.get('preferences.releditbtn'): - button = widgets.IconButton(self.edit_button_press, + button = widgets.IconButton(self.edit_button_press, handle) button.set_tooltip_text(_('Edit %s') % name[0]) else: @@ -1037,7 +1037,7 @@ class RelationshipView(NavigationView): emph = True else: emph = False - link_label = widgets.LinkLabel(name, self._button_press, + link_label = widgets.LinkLabel(name, self._button_press, handle, emph, theme=self.theme) if self.use_shade: link_label.override_background_color(Gtk.StateType.NORMAL, self.color) @@ -1053,7 +1053,7 @@ class RelationshipView(NavigationView): link_label.set_halign(Gtk.Align.START) link_label.show() vbox.pack_start(link_label, True, True, 0) - + if self.show_details: value = self.info_string(handle) if value: @@ -1062,7 +1062,7 @@ class RelationshipView(NavigationView): if self.use_shade: eventbox.override_background_color(Gtk.StateType.NORMAL, self.color) eventbox.add(vbox) - + self.child.attach(eventbox, _PDATA_START, self.row, _PDATA_STOP-_PDATA_START, 1) self.row += 1 @@ -1137,7 +1137,7 @@ class RelationshipView(NavigationView): original_vbox.pack_start(frame, True, True, 0) else: original_vbox.pack_start(ev, True, True, 0) - + parent = has_children(self.dbstate.db, self.dbstate.db.get_person_from_handle(handle)) @@ -1225,7 +1225,7 @@ class RelationshipView(NavigationView): value = _("%(birthabbrev)s %(birthdate)s, %(deathabbrev)s %(deathdate)s") % { 'birthabbrev': birth.type.get_abbreviation(), 'deathabbrev': death.type.get_abbreviation(), - 'birthdate' : bdate, + 'birthdate' : bdate, 'deathdate' : ddate } elif bdate: @@ -1301,13 +1301,13 @@ class RelationshipView(NavigationView): handle = event_ref.ref event = self.dbstate.db.get_event_from_handle(handle) if (event and event.get_type().is_relationship_event() and - (event_ref.get_role() == EventRoleType.FAMILY or + (event_ref.get_role() == EventRoleType.FAMILY or event_ref.get_role() == EventRoleType.PRIMARY)): self.write_event_ref(vbox, event.get_type().string, event) value = True return value - def write_event_ref(self, vbox, ename, event, start_col=_SDATA_START, + def write_event_ref(self, vbox, ename, event, start_col=_SDATA_START, stop_col=_SDATA_STOP): if event: dobj = event.get_date_object() @@ -1318,9 +1318,9 @@ class RelationshipView(NavigationView): pname = None value = { - 'date' : displayer.display(dobj), - 'place' : pname, - 'event_type' : ename, + 'date' : displayer.display(dobj), + 'place' : pname, + 'event_type' : ename, } else: pname = None @@ -1334,7 +1334,7 @@ class RelationshipView(NavigationView): value, start_col, stop_col) else: self.write_data( - vbox, _('%(event_type)s: %(date)s') % value, + vbox, _('%(event_type)s: %(date)s') % value, start_col, stop_col) elif pname: self.write_data( @@ -1352,7 +1352,7 @@ class RelationshipView(NavigationView): _('Broken family detected'), _('Please run the Check and Repair Database tool')) return - + father_handle = family.get_father_handle() mother_handle = family.get_mother_handle() if self.get_active() == father_handle: @@ -1434,14 +1434,14 @@ class RelationshipView(NavigationView): self.row += 1 # now advance it else: hbox = Gtk.Box() - addchild = widgets.IconButton(self.add_child_to_fam, - family.handle, + addchild = widgets.IconButton(self.add_child_to_fam, + family.handle, 'list-add') addchild.set_tooltip_text(_('Add new child to family')) - selchild = widgets.IconButton(self.sel_child_to_fam, - family.handle, + selchild = widgets.IconButton(self.sel_child_to_fam, + family.handle, 'gtk-index') - selchild.set_tooltip_text(_('Add existing child to family')) + selchild.set_tooltip_text(_('Add existing child to family')) hbox.pack_start(addchild, False, True, 0) hbox.pack_start(selchild, False, True, 0) self.child.attach(hbox, _CLABEL_START, self.row, @@ -1466,7 +1466,7 @@ class RelationshipView(NavigationView): def edit_button_press(self, obj, event, handle): if button_activated(event, _LEFT_BUTTON): self.edit_person(obj, handle) - + def edit_person(self, obj, handle): person = self.dbstate.db.get_person_from_handle(handle) try: @@ -1488,12 +1488,12 @@ class RelationshipView(NavigationView): person = self.dbstate.db.get_person_from_handle(self.get_active()) if not person: return - + if person.gender == Person.MALE: family.set_father_handle(person.handle) else: family.set_mother_handle(person.handle) - + try: EditFamily(self.dbstate, self.uistate, [], family) except WindowActiveError: @@ -1505,12 +1505,12 @@ class RelationshipView(NavigationView): if not person: return - + if person.gender == Person.MALE: family.set_father_handle(person.handle) else: family.set_mother_handle(person.handle) - + try: EditFamily(self.dbstate, self.uistate, [], family) except WindowActiveError: @@ -1535,7 +1535,7 @@ class RelationshipView(NavigationView): preset_name(father, name) person.set_primary_name(name) try: - EditPerson(self.dbstate, self.uistate, [], person, + EditPerson(self.dbstate, self.uistate, [], person, callback=callback) except WindowActiveError: pass @@ -1545,7 +1545,7 @@ class RelationshipView(NavigationView): ref.ref = person.get_handle() family = self.dbstate.db.get_family_from_handle(family_handle) family.add_child_ref(ref) - + with DbTxn(_("Add Child to Family"), self.dbstate.db) as trans: #add parentref to child person.add_parent_family_handle(family_handle) @@ -1566,7 +1566,7 @@ class RelationshipView(NavigationView): sel = SelectPerson(self.dbstate, self.uistate, [], _("Select Child"), skip=skip_list) person = sel.run() - + if person: self.callback_add_child(person, handle) @@ -1577,7 +1577,7 @@ class RelationshipView(NavigationView): phandle = self.get_active() person = self.dbstate.db.get_person_from_handle(phandle) skip = set(person.get_family_handle_list()) - + dialog = SelectFamily(self.dbstate, self.uistate, skip=skip) family = dialog.run() @@ -1593,13 +1593,13 @@ class RelationshipView(NavigationView): person = self.dbstate.db.get_person_from_handle(phandle) skip = set(person.get_family_handle_list()+ person.get_parent_family_handle_list()) - + dialog = SelectFamily(self.dbstate, self.uistate, skip=skip) family = dialog.run() if family: child = self.dbstate.db.get_person_from_handle(self.get_active()) - + self.dbstate.db.add_child_to_family(family, child) def add_parents(self, obj): @@ -1612,12 +1612,12 @@ class RelationshipView(NavigationView): ref = ChildRef() ref.ref = person.handle family.add_child_ref(ref) - + try: EditFamily(self.dbstate, self.uistate, [], family) except WindowActiveError: pass - + def add_parent_family(self, obj, event, handle): if button_activated(event, _LEFT_BUTTON): family = Family() @@ -1626,7 +1626,7 @@ class RelationshipView(NavigationView): ref = ChildRef() ref.ref = person.handle family.add_child_ref(ref) - + try: EditFamily(self.dbstate, self.uistate, [], family) except WindowActiveError: @@ -1646,7 +1646,7 @@ class RelationshipView(NavigationView): def reorder_button_press(self, obj, event, handle): if button_activated(event, _LEFT_BUTTON): self.reorder(obj) - + def reorder(self, obj, dumm1=None, dummy2=None): if self.get_active(): try: @@ -1682,11 +1682,11 @@ class RelationshipView(NavigationView): grid.set_column_spacing(6) grid.set_row_spacing(6) - configdialog.add_checkbox(grid, - _('Use shading'), + configdialog.add_checkbox(grid, + _('Use shading'), 0, 'preferences.relation-shade') - configdialog.add_checkbox(grid, - _('Display edit buttons'), + configdialog.add_checkbox(grid, + _('Display edit buttons'), 1, 'preferences.releditbtn') checkbox = Gtk.CheckButton(label=_('View links as website links')) theme = self._config.get('preferences.relation-display-theme') @@ -1704,11 +1704,11 @@ class RelationshipView(NavigationView): grid.set_border_width(12) grid.set_column_spacing(6) grid.set_row_spacing(6) - configdialog.add_checkbox(grid, - _('Show Details'), + configdialog.add_checkbox(grid, + _('Show Details'), 0, 'preferences.family-details') - configdialog.add_checkbox(grid, - _('Show Siblings'), + configdialog.add_checkbox(grid, + _('Show Siblings'), 1, 'preferences.family-siblings') return _('Content'), grid @@ -1719,18 +1719,18 @@ class RelationshipView(NavigationView): """ if obj.get_active(): self.theme = 'WEBPAGE' - self._config.set('preferences.relation-display-theme', + self._config.set('preferences.relation-display-theme', 'WEBPAGE') else: self.theme = 'CLASSIC' - self._config.set('preferences.relation-display-theme', + self._config.set('preferences.relation-display-theme', 'CLASSIC') def _get_configure_page_funcs(self): """ - Return a list of functions that create gtk elements to use in the + Return a list of functions that create gtk elements to use in the notebook pages of the Configure dialog - + :return: list of functions """ return [self.content_panel, self.config_panel] diff --git a/gramps/plugins/view/repoview.py b/gramps/plugins/view/repoview.py index 614102a5f..9b11b832e 100644 --- a/gramps/plugins/view/repoview.py +++ b/gramps/plugins/view/repoview.py @@ -62,7 +62,7 @@ _ = glocale.translation.gettext # #------------------------------------------------------------------------- class RepositoryView(ListView): - """ repository listview class + """ repository listview class """ COL_NAME = 0 COL_ID = 1 @@ -104,11 +104,11 @@ class RepositoryView(ListView): ]), ('columns.rank', [COL_NAME, COL_ID, COL_TYPE, COL_URL, COL_STREET, COL_LOCALITY, COL_CITY, COL_STATE, COL_COUNTRY, - COL_ZIP, COL_EMAIL, COL_SURL, COL_PRIV, COL_TAGS, + COL_ZIP, COL_EMAIL, COL_SURL, COL_PRIV, COL_TAGS, COL_CHAN]), ('columns.size', [200, 75, 100, 250, 100, 100, 100, 100, 100, 100, 100, 100, 40, 100, 100]) - ) + ) ADD_MSG = _("Add a new repository") EDIT_MSG = _("Edit the selected repository") DEL_MSG = _("Delete the selected repository") @@ -124,7 +124,7 @@ class RepositoryView(ListView): 'repository-delete' : self.row_delete, 'repository-rebuild' : self.object_build, } - + ListView.__init__( self, _('Repositories'), pdata, dbstate, uistate, RepositoryModel, signal_map, @@ -149,7 +149,7 @@ class RepositoryView(ListView): ListView.define_actions(self) self._add_action('FilterEdit', None, _('Repository Filter Editor'), callback=self.filter_editor,) - self._add_action('QuickReport', None, + self._add_action('QuickReport', None, _("Quick View"), None, None, None) def get_stock(self): @@ -188,8 +188,8 @@ class RepositoryView(ListView): - - + + @@ -277,7 +277,7 @@ class RepositoryView(ListView): repo = self.dbstate.db.get_repository_from_handle(repo_handle) repo.add_tag(tag_handle) self.dbstate.db.commit_repository(repo, transaction) - + def get_default_gramplets(self): """ Define the default gramplets for the sidebar and bottombar. diff --git a/gramps/plugins/view/sourceview.py b/gramps/plugins/view/sourceview.py index e5a1cef72..20248724d 100644 --- a/gramps/plugins/view/sourceview.py +++ b/gramps/plugins/view/sourceview.py @@ -66,7 +66,7 @@ _ = glocale.translation.gettext # #------------------------------------------------------------------------- class SourceView(ListView): - """ sources listview class + """ sources listview class """ COL_TITLE = 0 COL_ID = 1 @@ -76,7 +76,7 @@ class SourceView(ListView): COL_PRIV = 5 COL_TAGS = 6 COL_CHAN = 7 - + # column definitions COLUMNS = [ (_('Title'), TEXT, None), @@ -94,7 +94,7 @@ class SourceView(ListView): ('columns.rank', [COL_TITLE, COL_ID, COL_AUTH, COL_ABBR, COL_PINFO, COL_PRIV, COL_TAGS, COL_CHAN]), ('columns.size', [200, 75, 150, 100, 150, 40, 100, 100]) - ) + ) ADD_MSG = _("Add a new source") EDIT_MSG = _("Edit the selected source") DEL_MSG = _("Delete the selected source") @@ -112,7 +112,7 @@ class SourceView(ListView): } ListView.__init__( - self, _('Sources'), pdata, dbstate, uistate, + self, _('Sources'), pdata, dbstate, uistate, SourceModel, signal_map, SourceBookmarks, nav_group, multiple=True, @@ -130,7 +130,7 @@ class SourceView(ListView): def drag_info(self): return DdTargets.SOURCE_LINK - + def define_actions(self): ListView.define_actions(self) self._add_action('FilterEdit', None, _('Source Filter Editor'), @@ -173,8 +173,8 @@ class SourceView(ListView): - - + + @@ -204,7 +204,7 @@ class SourceView(ListView): def remove_object_from_handle(self, handle): the_lists = get_source_and_citation_referents(handle, self.dbstate.db) - LOG.debug('the_lists %s' % [the_lists]) + LOG.debug('the_lists %s' % [the_lists]) object = self.dbstate.db.get_source_from_handle(handle) query = DeleteSrcQuery(self.dbstate, self.uistate, object, the_lists) @@ -224,7 +224,7 @@ class SourceView(ListView): Merge the selected sources. """ mlist = self.selected_handles() - + if len(mlist) != 2: msg = _("Cannot merge sources.") msg2 = _("Exactly two sources must be selected to perform a merge. " @@ -260,7 +260,7 @@ class SourceView(ListView): source = self.dbstate.db.get_source_from_handle(source_handle) source.add_tag(tag_handle) self.dbstate.db.commit_source(source, transaction) - + def get_default_gramplets(self): """ Define the default gramplets for the sidebar and bottombar. diff --git a/gramps/plugins/view/view.gpr.py b/gramps/plugins/view/view.gpr.py index dbc384dc1..639742e14 100644 --- a/gramps/plugins/view/view.gpr.py +++ b/gramps/plugins/view/view.gpr.py @@ -22,7 +22,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # @@ -30,7 +30,7 @@ MODULE_VERSION="5.0" # #------------------------------------------------------------------------ -register(VIEW, +register(VIEW, id = 'eventview', name = _("Events"), description = _("The view showing all the events"), @@ -45,7 +45,7 @@ viewclass = 'EventView', order = START, ) -register(VIEW, +register(VIEW, id = 'familyview', name = _("Families"), description = _("The view showing all families"), @@ -60,7 +60,7 @@ viewclass = 'FamilyView', order = START, ) -register(VIEW, +register(VIEW, id = 'dashboardview', name = _("Dashboard"), description = _("The view showing Gramplets"), @@ -75,7 +75,7 @@ viewclass = 'DashboardView', order = START, ) -register(VIEW, +register(VIEW, id = 'mediaview', name = _("Media"), description = _("The view showing all the media objects"), @@ -90,7 +90,7 @@ viewclass = 'MediaView', order = START, ) -register(VIEW, +register(VIEW, id = 'noteview', name = _("Notes"), description = _("The view showing all the notes"), @@ -105,7 +105,7 @@ viewclass = 'NoteView', order = START, ) -register(VIEW, +register(VIEW, id = 'relview', name = _("Relationships"), description = _("The view showing all relationships of the selected person"), @@ -120,7 +120,7 @@ viewclass = 'RelationshipView', order = START, ) -register(VIEW, +register(VIEW, id = 'pedigreeview', name = _("Pedigree"), description = _("The view showing an ancestor pedigree of the selected person"), @@ -136,7 +136,7 @@ order = START, stock_icon = 'gramps-pedigree', ) -register(VIEW, +register(VIEW, id = 'fanchartview', name = _("Fan Chart"), category = ("Ancestry", _("Charts")), @@ -151,7 +151,7 @@ viewclass = 'FanChartView', stock_icon = 'gramps-fanchart', ) -register(VIEW, +register(VIEW, id = 'fanchartdescview', name = _("Descendant Fan"), category = ("Ancestry", _("Charts")), @@ -166,7 +166,7 @@ viewclass = 'FanChartDescView', stock_icon = 'gramps-fanchartdesc', ) -register(VIEW, +register(VIEW, id = 'personview', name = _("Grouped People"), description = _("The view showing all people in the Family Tree grouped per" @@ -183,7 +183,7 @@ order = START, stock_icon = 'gramps-tree-group', ) -register(VIEW, +register(VIEW, id = 'personlistview', name = _("People"), description = _("The view showing all people in the Family Tree" @@ -198,8 +198,8 @@ category = ("People", _("People")), viewclass = 'PersonListView', stock_icon = 'gramps-tree-list', ) - -register(VIEW, + +register(VIEW, id = 'placelistview', name = _("Places"), description = _("The view showing all the places of the Family Tree"), @@ -214,7 +214,7 @@ viewclass = 'PlaceListView', stock_icon = 'gramps-tree-list', ) -register(VIEW, +register(VIEW, id = 'placetreeview', name = _("Place Tree"), description = _("A view displaying places in a tree format."), @@ -230,7 +230,7 @@ stock_icon = 'gramps-tree-group', order = START, ) -register(VIEW, +register(VIEW, id = 'repoview', name = _("Repositories"), description = _("The view showing all the repositories"), @@ -245,7 +245,7 @@ viewclass = 'RepositoryView', order = START, ) -register(VIEW, +register(VIEW, id = 'sourceview', name = _("Sources"), description = _("The view showing all the sources"), @@ -261,7 +261,7 @@ order = START, stock_icon = 'gramps-tree-list', ) -register(VIEW, +register(VIEW, id = 'citationlistview', name = _("Citations"), description = _("The view showing all the citations"), @@ -276,7 +276,7 @@ viewclass = 'CitationListView', order = START, ) -register(VIEW, +register(VIEW, id = 'citationtreeview', name = _("Citation Tree"), description = _("A view displaying citations and sources in a tree format."), diff --git a/gramps/plugins/webreport/narrativeweb.py b/gramps/plugins/webreport/narrativeweb.py index 62c6b97ab..fff1e28c9 100644 --- a/gramps/plugins/webreport/narrativeweb.py +++ b/gramps/plugins/webreport/narrativeweb.py @@ -21,7 +21,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -39,10 +39,10 @@ Classes: the report is write_report NavWebOptions - class that defines the options and provides the handling interface - + BasePage - super class for producing a web page. This class is instantiated once for each page. Provdes various common functions. - + Classes for producing the web pages: SurnamePage - creates list of individuals with same surname FamilyPage - Family index page and individual Family pages @@ -60,7 +60,7 @@ Classes for producing the web pages: PersonPage - Person index page and individual `Person pages RepositoryPage - Repository index page and individual Repository pages AddressBookListPage - AddressBookPage + AddressBookPage """ #------------------------------------------------ # python modules @@ -214,7 +214,7 @@ dropmarkers = """ function initialize() { var mapOptions = { scaleControl: true, - zoomControl: true, + zoomControl: true, zoom: %d, mapTypeId: google.maps.MapTypeId.ROADMAP, center: new google.maps.LatLng(0, 0) @@ -274,7 +274,7 @@ markers = """ draggable: true, title: location[0], map: map, - zIndex: location[3] + zIndex: location[3] }); bounds.extend(myLatLng); map.fitBounds(bounds); @@ -302,14 +302,14 @@ openstreetmap_jsc = """ var osm = new OpenLayers.Layer.OSM() map.addLayer(osm); - + var lonLat = new OpenLayers.LonLat(%s, %s) .transform( new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984 map.getProjectionObject() // to Spherical Mercator Projection ); var zoom =16; - + map.setCenter(lonLat, zoom); var markers = new OpenLayers.Layer.Markers("Markers"); @@ -352,7 +352,7 @@ osm_markers = """ var location = tracelife[i]; marker = new OpenLayers.Marker(new OpenLayers.LonLat(location[0], location[1])); - markers.addMarker(marker); + markers.addMarker(marker); map.addControl(new OpenLayers.Control.LayerSwitcher()); } }""" @@ -396,14 +396,14 @@ _ABSENT = _("") # Events that are usually a family event _EVENTMAP = set( - [EventType.MARRIAGE, EventType.MARR_ALT, + [EventType.MARRIAGE, EventType.MARR_ALT, EventType.MARR_SETTL, EventType.MARR_LIC, EventType.MARR_CONTR, EventType.MARR_BANNS, EventType.ENGAGEMENT, EventType.DIVORCE, EventType.DIV_FILING ] ) - + # define clear blank line for proper styling fullclear = Html("div", class_ = "fullclear", inline = True) @@ -518,12 +518,12 @@ def format_date(date): if mod == Date.MOD_SPAN: val = "%sFROM %s TO %s" % ( qual_text, - make_gedcom_date(start, cal, mod, None), + make_gedcom_date(start, cal, mod, None), make_gedcom_date(date.get_stop_date(), cal, mod, None)) elif mod == Date.MOD_RANGE: val = "%sBET %s AND %s" % ( qual_text, - make_gedcom_date(start, cal, mod, None), + make_gedcom_date(start, cal, mod, None), make_gedcom_date(date.get_stop_date(), cal, mod, None)) else: val = make_gedcom_date(start, cal, mod, quality) @@ -541,7 +541,7 @@ def copy_thumbnail(report, handle, photo, region=None): to_path = os.path.join(to_dir, handle) + ( ('%d,%d-%d,%d.png' % region) if region else '.png' ) - + if photo.get_mime_type(): from_path = get_thumbnail_path(media_path_full( report.database, @@ -556,7 +556,7 @@ def copy_thumbnail(report, handle, photo, region=None): return to_path ''' -# Manages all the functions, variables, and everything needed +# Manages all the functions, variables, and everything needed # for all of the classes contained within this plugin ''' class BasePage(object): @@ -591,7 +591,7 @@ class BasePage(object): # Functions used when no Web Page plugin is provided def add_instance(self, *param): pass - + def display_pages(self, *param): pass @@ -717,14 +717,14 @@ class BasePage(object): birthorder = self.report.options["birthorder"] # display family events; such as marriage and divorce... family_events = family.get_event_ref_list() - if family_events: + if family_events: trow = Html("tr") + ( Html("td", " ", class_ = "ColumnType", inline = True), Html("td", " ", class_ = "ColumnAttribute", inline = True), Html("td", self.format_family_events(family_events, place_lat_long), class_ = "ColumnValue") ) table = trow - + # If the families pages are not output, display family notes if not self.inc_families: notelist = family.get_note_list() @@ -745,31 +745,31 @@ class BasePage(object): Html("td", _("Children"), class_ = "ColumnAttribute", inline = True) ) table = table + trow if table is not None else trow - + tcell = Html("td", class_ = "ColumnValue") trow += tcell - + ordered = Html("ol") - tcell += ordered + tcell += ordered childlist = [child_ref.ref for child_ref in childlist] - + # add individual's children event places to family map... if self.familymappages: for handle in childlist: child = self.dbase_.get_person_from_handle(handle) if child: self._get_event_place(child, place_lat_long) - + children = add_birthdate(self.dbase_, childlist) if birthorder: - children = sorted(children) - + children = sorted(children) + ordered.extend( (Html("li") + self.display_child_link(chandle)) for birth_date, chandle in children ) - + # family LDS ordinance list family_lds_ordinance_list = family.get_lds_ord_list() if family_lds_ordinance_list: @@ -779,7 +779,7 @@ class BasePage(object): Html("td", self.dump_ordinance(family, "Family"), class_ = "ColumnValue") ) table = table + trow if table is not None else trow - + # Family Attribute list family_attribute_list = family.get_attribute_list() if family_attribute_list: @@ -788,10 +788,10 @@ class BasePage(object): Html("td", _("Attributes"), class_ ="ColumnAttribute", inline =True) ) table = table + trow if table is not None else trow - + tcell = Html("td", class_ = "ColumnValue") trow += tcell - + # we do not need the section variable for this instance of Attributes... dummy, attrtable = self.display_attribute_header() tcell += attrtable @@ -872,8 +872,8 @@ class BasePage(object): def get_note_format(self, note, link_prefix_up): """ - will get the note from the database, and will return either the - styled text or plain note + will get the note from the database, and will return either the + styled text or plain note """ self.report.link_prefix_up = link_prefix_up @@ -881,10 +881,10 @@ class BasePage(object): if note is not None: # retrieve the body of the note note_text = note.get() - + # styled notes htmlnotetext = self.styled_note(note.get_styledtext(), - note.get_format(), contains_html = + note.get_format(), contains_html = note.get_type() == NoteType.HTML_CODE) text = htmlnotetext or Html("p", note_text) @@ -905,14 +905,14 @@ class BasePage(object): s_tags = styledtext.get_tags() htmllist = Html("div", class_="grampsstylednote") if contains_html: - markuptext = self._backend.add_markup_from_styled(text, - s_tags, + markuptext = self._backend.add_markup_from_styled(text, + s_tags, split='\n', escape=False) htmllist += markuptext else: - markuptext = self._backend.add_markup_from_styled(text, - s_tags, + markuptext = self._backend.add_markup_from_styled(text, + s_tags, split='\n') linelist = [] linenb = 1 @@ -1001,7 +1001,7 @@ class BasePage(object): # get event type and hyperlink to it or not? etype = str(event.get_type()) - + event_role = event_ref.get_role() if not event_role == omit: etype += " (%s)" % event_role @@ -1021,7 +1021,7 @@ class BasePage(object): notelist = event.get_note_list() notelist.extend(event_ref.get_note_list()) htmllist = self.dump_notes(notelist) - + # if the event or event reference has an attribute attached to it, # get the text and format it correctly? attrlist = event.get_attribute_list() @@ -1050,7 +1050,7 @@ class BasePage(object): def append_to_place_lat_long(self, place, event, place_lat_long): """ Create a list of places with coordinates. - + @param: place_lat_long -- for use in Family Map Pages. This will be None if called from Family pages, which do not create a Family Map """ @@ -1116,7 +1116,7 @@ class BasePage(object): if result is None: # the family is not included in the webreport return name + str(gid_html) - + url = self.report.build_url_fname(result[0], up = uplink) hyper = Html("a", name, href = url, title = name) hyper += gid_html @@ -1181,13 +1181,13 @@ class BasePage(object): # begin table body tbody = Html("tbody") - table += tbody - + table += tbody + for evt_ref in event_ref_list: event = self.dbase_.get_event_from_handle(evt_ref.ref) # add event body row - tbody += self.display_event_row(event, evt_ref, place_lat_long, + tbody += self.display_event_row(event, evt_ref, place_lat_long, up =True, hyperlink =True, omit =EventRoleType.FAMILY) return table @@ -1206,7 +1206,7 @@ class BasePage(object): place = self.dbase_.get_place_from_handle(place_handle) place_hyper = None - if place: + if place: place_name = ReportUtils.place_name(self.dbase_, place_handle) place_hyper = self.place_link(place_handle, place_name, uplink = up) @@ -1331,8 +1331,8 @@ class BasePage(object): """ url = self.report.build_url_fname_html(source_handle, "src", uplink) - hyper = Html("a", source_title, - href = url, + hyper = Html("a", source_title, + href = url, title = source_title) # if not None, add name reference to hyperlink element @@ -1369,7 +1369,7 @@ class BasePage(object): def dump_addresses(self, addrlist, showsrc): """ - will display an object's addresses, url list, note list, + will display an object's addresses, url list, note list, and source references. @param: addrlist = either person or repository address list @@ -1381,7 +1381,7 @@ class BasePage(object): return None # begin summaryarea division - with Html("div", id = "AddressTable") as summaryarea: + with Html("div", id = "AddressTable") as summaryarea: # begin address table with Html("table") as table: @@ -1390,10 +1390,10 @@ class BasePage(object): # get table class based on showsrc if showsrc == True: table.attr = 'class = "infolist addrlist"' - elif showsrc == False: + elif showsrc == False: table.attr = 'class = "infolist repolist"' else: - table.attr = 'class = "infolist addressbook"' + table.attr = 'class = "infolist addressbook"' # begin table head thead = Html("thead") @@ -1404,8 +1404,8 @@ class BasePage(object): addr_header = [ [DHEAD, "Date"], - [STREET, "StreetAddress"], - [_("Locality"), "Locality"], + [STREET, "StreetAddress"], + [_("Locality"), "Locality"], [CITY, "City"], [STATE, "State"], [COUNTY, "County"], @@ -1452,7 +1452,7 @@ class BasePage(object): Html("td", value or " ", class_= colclass, inline = True) for (value, colclass) in addr_data_row ) - + # address: notelist if showsrc is not None: notelist = self.display_note_list(address.get_note_list()) @@ -1499,8 +1499,8 @@ class BasePage(object): def get_name(self, person, maiden_name = None): """ I5118 - Return person's name, unless maiden_name given, unless married_name - listed. + Return person's name, unless maiden_name given, unless married_name + listed. @param: person -- person object from database @param: maiden_name -- Female's family surname @@ -1572,7 +1572,7 @@ class BasePage(object): tbody.extend( self.dump_attribute(attr) for attr in attrlist ) - + def write_footer(self): """ Will create and display the footer section of each page... @@ -1591,7 +1591,7 @@ class BasePage(object): ) user_footer = Html("div", id = 'user_footer') footer += user_footer - + # attach note user_footer += note @@ -1648,8 +1648,8 @@ class BasePage(object): # begin each html page... xmllang = xml_lang() - page, head, body = Html.page('%s - %s' % - (html_escape(self.title_str.strip()), + page, head, body = Html.page('%s - %s' % + (html_escape(self.title_str.strip()), html_escape(title)), self.report.encoding, xmllang) @@ -1690,7 +1690,7 @@ class BasePage(object): ) # Link to Navigation Menus stylesheet - if CSS[self.report.css]["navigation"]: + if CSS[self.report.css]["navigation"]: fname = "/".join(["css", "narrative-menus.css"]) url = self.report.build_url_fname(fname, None, self.up) links += Html("link", type = "text/css", href = url, media = "screen", rel = "stylesheet", indent = False) @@ -1711,19 +1711,19 @@ class BasePage(object): self.report.database.get_note_from_gramps_id(header_note), False) user_header = Html("div", id = 'user_header') - headerdiv += user_header - + headerdiv += user_header + # attach note user_header += note # Begin Navigation Menu-- # is the style sheet either Basic-Blue or Visually Impaired, # and menu layout is Drop Down? - if (self.report.css == _("Basic-Blue") or + if (self.report.css == _("Basic-Blue") or self.report.css == _("Visually Impaired")) and \ self.report.navigation == "dropdown": body += self.display_drop_menu() - else: + else: body += self.display_nav_links(title) # return page, head, and body to its classes... @@ -1736,7 +1736,7 @@ class BasePage(object): @param: currentsection = which menu item are you on """ # include repositories or not? - inc_repos = True + inc_repos = True if (not self.report.inc_repository or not len(self.report.database.get_repository_handles()) ): inc_repos = False @@ -1746,7 +1746,7 @@ class BasePage(object): if self.create_media: _create_media_link = True if self.create_thumbs_only: - _create_media_link = False + _create_media_link = False # determine which menu items will be available? # menu items have been adjusted to concide with Gramps Navigation Sidebar order... @@ -1756,7 +1756,7 @@ class BasePage(object): ('individuals', _("Individuals"), True), (self.report.surname_fname, _("Surnames"), True), ('families', _("Families"), self.report.inc_families), - ('events', _("Events"), self.report.inc_events), + ('events', _("Events"), self.report.inc_events), ('places', _("Places"), True), ('sources', _("Sources"), True), ('repositories', _("Repositories"), inc_repos), @@ -1817,19 +1817,19 @@ class BasePage(object): check_cs = True elif nav_text == _("Events"): if "evt" in self.report.cur_fname: - check_cs = True + check_cs = True elif nav_text == _("Media"): if "img" in self.report.cur_fname: check_cs = True elif nav_text == _("Address Book"): if "addr" in self.report.cur_fname: - check_cs = True + check_cs = True check_cs = 'class = "CurrentSection"' if check_cs else False if check_cs: unordered.extend( Html("li", hyper, attr = check_cs, inline = True) ) - else: + else: unordered.extend( Html("li", hyper, inline = True) ) @@ -1845,7 +1845,7 @@ class BasePage(object): creates the Drop Down Navigation Menu """ # include repositories or not? - inc_repos = True + inc_repos = True if (not self.report.inc_repository or not len(self.report.database.get_repository_handles()) ): inc_repos = False @@ -1855,7 +1855,7 @@ class BasePage(object): if self.create_media: _create_media_link = True if self.create_thumbs_only: - _create_media_link = False + _create_media_link = False personal = [ (self.report.intro_fname, _("Introduction"), self.report.use_intro), @@ -1921,7 +1921,7 @@ class BasePage(object): # add contact column self.get_column_data(unordered, contact, _("Contact")) - + container += unordered navigation += container return navigation @@ -1955,10 +1955,10 @@ class BasePage(object): image.attr += ' src = "%s" alt = "%s"' % (newpath, descr ) # return an image - return image + return image except (IOError, OSError) as msg: - self.report.user.warn(_("Could not add photo to page"), + self.report.user.warn(_("Could not add photo to page"), str(msg)) # no image to return @@ -1978,7 +1978,7 @@ class BasePage(object): # get all of the backlinks to this media object; meaning all of # the people, events, places, etc..., that use this image _region_items = set() - for (classname, newhandle) in self.dbase_.find_backlink_handles(handle, + for (classname, newhandle) in self.dbase_.find_backlink_handles(handle, include_classes = ["Person", "Family", "Event", "Place"]): # for each of the backlinks, get the relevant object from the db @@ -2011,10 +2011,10 @@ class BasePage(object): partner2 = self.dbase_.get_person_from_handle(partner2_handle) if partner2 and partner1: _name = partner1.get_primary_name().get_first_name() - _linkurl = self.report.build_url_fname_html(partner1_handle, "ppl", True) + _linkurl = self.report.build_url_fname_html(partner1_handle, "ppl", True) elif partner1: _name = partner1.get_primary_name().get_first_name() - _linkurl = self.report.build_url_fname_html(partner1_handle, "ppl", True) + _linkurl = self.report.build_url_fname_html(partner1_handle, "ppl", True) elif partner2: _name = partner2.get_primary_name().get_first_name() _linkurl = self.report.build_url_fname_html(partner2_handle, "ppl", True) @@ -2025,13 +2025,13 @@ class BasePage(object): _name = _obj.get_description() if not _name: _name = _UNKNOWN - _linkurl = self.report.build_url_fname_html(_obj.handle, "evt", True) + _linkurl = self.report.build_url_fname_html(_obj.handle, "evt", True) elif classname == "Place": _obj = self.dbase_.get_place_from_handle(newhandle) _name = ReportUtils.place_name(self.dbase_, newhandle) if not _name: _name = _UNKNOWN - _linkurl = self.report.build_url_fname_html(newhandle, "plc", True) + _linkurl = self.report.build_url_fname_html(newhandle, "plc", True) # continue looking through the loop for an object... if _obj is None: @@ -2072,7 +2072,7 @@ class BasePage(object): # get a list of all media refs for this object for mediaref in obj.get_media_list(): # is this mediaref for this image? do we have a rect? - if (mediaref.ref == media_handle and + if (mediaref.ref == media_handle and mediaref.rect is not None): return mediaref.rect # (x1, y1, x2, y2) return None @@ -2110,7 +2110,7 @@ class BasePage(object): real_path, newpath = self.report.prepare_copy_media(photo) newpath = self.report.build_url_fname(newpath, up = True) - + # FIXME: There doesn't seem to be any point in highlighting # a sub-region in the thumbnail and linking back to the # person or whatever. First it is confusing when the link @@ -2128,7 +2128,7 @@ class BasePage(object): mediadisplay += ordered while len(_region_items): (name, x, y, w, h, linkurl) = _region_items.pop() - ordered += Html("li", + ordered += Html("li", style="left:%d%%; top:%d%%; width:%d%%; height:%d%%;" % (x, y, w, h)) + Html("a", name, href = linkurl) # Need to add link to mediadisplay to get the links: @@ -2173,7 +2173,7 @@ class BasePage(object): photolist_ordered += photolist # begin individualgallery division and section title - with Html("div", class_ = "subsection", id = "indivgallery") as section: + with Html("div", class_ = "subsection", id = "indivgallery") as section: section += Html("h4", _("Media"), inline = True) displayed = [] @@ -2242,9 +2242,9 @@ class BasePage(object): # begin web links division with Html("div", class_ = "subsection", id = "WebLinks") as section: - section += Html("h4", _("Web Links"), inline = True) + section += Html("h4", _("Web Links"), inline = True) - with Html("table", class_ = "infolist weblinks") as table: + with Html("table", class_ = "infolist weblinks") as table: section += table thead = Html("thead") @@ -2268,7 +2268,7 @@ class BasePage(object): trow = Html("tr") tbody += trow - + _type = url.get_type() uri = url.get_path() descr = url.get_description() @@ -2281,12 +2281,12 @@ class BasePage(object): # Web Site address elif _type == UrlType.WEB_HOME: if not (uri.startswith("http://") or uri.startswith("https://")): - uri = "http://%(website)s" % { "website" : uri } + uri = "http://%(website)s" % { "website" : uri } # FTP server address elif _type == UrlType.WEB_FTP: if not (uri.startswith("ftp://") or uri.startswith("ftps://")): - uri = "ftp://%(ftpsite)s" % { "ftpsite" : uri } + uri = "ftp://%(ftpsite)s" % { "ftpsite" : uri } descr = Html("p", html_escape(descr)) + ( Html("a", _(" [Click to Go]"), href = uri, title = uri) @@ -2298,7 +2298,7 @@ class BasePage(object): (str(_type), "ColumnType"), (descr, "ColumnDescription") ] - ) + ) return section def display_lds_ordinance(self, db_obj_): @@ -2326,7 +2326,7 @@ class BasePage(object): """ list(map(lambda i: self.bibli.add_reference( - self.report.database.get_citation_from_handle(i)), + self.report.database.get_citation_from_handle(i)), srcobj.get_citation_list())) sourcerefs = self.display_source_refs(self.bibli) @@ -2381,11 +2381,11 @@ class BasePage(object): if mime_type.startswith("image/"): real_path, newpath = self.report.prepare_copy_media(media) newpath = self.report.build_url_fname(newpath, up = self.up) - + tmp += Html("li", self.media_link(media_handle, newpath, media.get_description(), self.up, usedescr = False), inline = True) - + else: tmp += Html("li", self.doc_link(media_handle, media.get_description(), self.up, usedescr = False), inline = True) @@ -2417,9 +2417,9 @@ class BasePage(object): section += Html("h4", _("References"), inline = True) ordered = Html("ol") - section += ordered + section += ordered sortlist = sorted(handlelist, key=lambda x:SORT_KEY(x[1])) - + for (path, name, gid) in sortlist: list = Html("li") ordered += list @@ -2470,15 +2470,15 @@ class BasePage(object): # display family relationship status, and add spouse to FamilyMapPages if self.familymappages: self._get_event_place(partner, place_lat_long) - + trow = Html("tr", class_ ="BeginFamily") + ( Html("td", rtype, class_ ="ColumnType", inline =True), Html("td", relstr, class_ ="ColumnAttribute", inline =True) ) - + tcell = Html("td", class_ ="ColumnValue") trow += tcell - + tcell += self.new_person_link(partner.get_handle(), uplink=True, person=partner) return trow @@ -2522,7 +2522,7 @@ class BasePage(object): # The person has been encountered in the web report, but this does # not necessarily mean that a page has been generated (link, name, gid) = result - + if name_style == _NAME_STYLE_FIRST and person: name = _get_short_name(person.get_gender(), person.get_primary_name()) name = html_escape(name) @@ -2573,7 +2573,7 @@ class BasePage(object): def doc_link(self, handle, name, uplink = False, usedescr = True): """ create a hyperlink for the media object and returns it - + @param: handle - document handle @param: name - document name @param: uplink - whether to add "../../.." or not @@ -2648,13 +2648,13 @@ class BasePage(object): ml = get_main_location(self.dbase_, place) for (label, data) in [ (STREET, ml.get(PlaceType.STREET, '')), - (LOCALITY, ml.get(PlaceType.LOCALITY, '')), + (LOCALITY, ml.get(PlaceType.LOCALITY, '')), (CITY, ml.get(PlaceType.CITY, '')), (PARISH, ml.get(PlaceType.PARISH, '')), (COUNTY, ml.get(PlaceType.COUNTY, '')), (STATE, ml.get(PlaceType.STATE, '')), (POSTAL, place.get_code()), - (COUNTRY, ml.get(PlaceType.COUNTRY, ''))]: + (COUNTRY, ml.get(PlaceType.COUNTRY, ''))]: if data: trow = Html("tr") + ( Html("td", label, class_ = "ColumnAttribute", inline = True), @@ -2672,7 +2672,7 @@ class BasePage(object): for loc in (nonempt for nonempt in altloc if not nonempt.is_empty()): for (label, data) in [ (STREET, loc.street), - (LOCALITY, loc.locality), + (LOCALITY, loc.locality), (CITY, loc.city), (PARISH, loc.parish), (COUNTY, loc.county), @@ -2739,7 +2739,7 @@ class BasePage(object): for repo_ref in repo_ref_list: repository = self.dbase_.get_repository_from_handle(repo_ref.ref) if repository: - + trow = Html("tr") + ( Html("td", index, class_ ="ColumnRowLabel", inline =True), Html("td", self.repository_link(repo_ref.ref, repository.get_name(), @@ -2772,7 +2772,7 @@ class BasePage(object): descr = has_res.get_description() if descr: - + trow = Html("tr") if len(table) == 3: # append description row to tbody element of dump_place @@ -2780,7 +2780,7 @@ class BasePage(object): else: # append description row to table element table += trow - + trow.extend(Html("td", DESCRHEAD, class_ = "ColumnAttribute", inline = True)) trow.extend(Html("td", descr, class_ = "ColumnValue", inline=True)) @@ -2815,7 +2815,7 @@ class BasePage(object): gid_html = "" list += Html("a", href=url) + name + gid_html return ordered - + def display_bkref_list(self, obj_class, obj_handle): bkref_list = self.report.bkref_dict[obj_class][obj_handle] if not bkref_list: @@ -2827,9 +2827,9 @@ class BasePage(object): ordered = self.display_bkref(bkref_list, depth) section += ordered return section - + # --------------------------------------------------------------------------------------- - # # Web Page Fortmatter and writer + # # Web Page Fortmatter and writer # --------------------------------------------------------------------------------------- def XHTMLWriter(self, htmlinstance, of, sio): """ @@ -2840,7 +2840,7 @@ class BasePage(object): src/plugins/lib/libhtml.py """ - htmlinstance.write(partial(print, file=of)) + htmlinstance.write(partial(print, file=of)) # closes the file self.report.close_file(of, sio) @@ -2867,7 +2867,7 @@ class SurnamePage(BasePage): if surname == '': surname = _ABSENT - + of, sio = self.report.create_file(name_to_md5(surname), "srn") self.up = True surnamepage, head, body = self.write_header("%s - %s" % (_("Surname"), surname)) @@ -2897,7 +2897,7 @@ class SurnamePage(BasePage): thead += trow # Name Column - trow += Html("th", _("Given Name"), class_ = "ColumnName", inline = True) + trow += Html("th", _("Given Name"), class_ = "ColumnName", inline = True) if showbirth: trow += Html("th", _("Birth"), class_ = "ColumnDate", inline = True) @@ -2911,12 +2911,12 @@ class SurnamePage(BasePage): if showparents: trow += Html("th", _("Parents"), class_ = "ColumnParents", inline = True) - # begin table body + # begin table body tbody = Html("tbody") table += tbody for person_handle in ppl_handle_list: - + person = self.dbase_.get_person_from_handle(person_handle) trow = Html("tr") tbody += trow @@ -2925,7 +2925,7 @@ class SurnamePage(BasePage): link = self.new_person_link(person_handle, uplink=True, person=person, name_style=_NAME_STYLE_FIRST) - trow += Html("td", link, class_ = "ColumnName") + trow += Html("td", link, class_ = "ColumnName") # birth column if showbirth: @@ -3022,19 +3022,19 @@ class FamilyPages(BasePage): # and remembers the list of Family. A single call to 'display_pages' # displays both the Family List (Index) page and all the Family # pages. - + # The base class 'BasePage' is initialised once for each page that is # displayed. def __init__(self, report): self.family_dict = defaultdict(set) self.report = report self.db = report.database - + def display_pages(self, title): """ Generate and output the pages under the Family tab, namely the family index and the individual family pages. - + @param: title -- the web site title """ log.debug("obj_dict[Family]") @@ -3042,7 +3042,7 @@ class FamilyPages(BasePage): log.debug(" %s" % str(item)) with self.report.user.progress(_("Narrated Web Site Report"), - _("Creating family pages..."), + _("Creating family pages..."), len(self.report.obj_dict[Family]) + 1) as step: self.FamilyListPage(self.report, title, self.report.obj_dict[Family].keys()) @@ -3050,7 +3050,7 @@ class FamilyPages(BasePage): for family_handle in self.report.obj_dict[Family]: step() self.FamilyPage(self.report, title, family_handle) - + def FamilyListPage(self, report, title, fam_list): self.dbase_ = report.database BasePage.__init__(self, report, title) @@ -3085,10 +3085,10 @@ class FamilyPages(BasePage): pers_fam_dict[husband_handle].append(family) if spouse_handle: pers_fam_dict[spouse_handle].append(family) - + # add alphabet navigation index_list = get_first_letters(self.dbase_, pers_fam_dict.keys(), - _KEYPERSON) + _KEYPERSON) alpha_nav = alphabet_navigation(index_list) if alpha_nav: relationlist += alpha_nav @@ -3105,9 +3105,9 @@ class FamilyPages(BasePage): # set up page columns trow.extend( - Html("th", trans, class_ =colclass, inline =True) + Html("th", trans, class_ =colclass, inline =True) for trans, colclass in [ - (_("Letter"), "ColumnRowLabel"), + (_("Letter"), "ColumnRowLabel"), (_("Person"), "ColumnPartner"), (_("Family"), "ColumnPartner"), (_("Marriage"), "ColumnDate"), @@ -3123,7 +3123,7 @@ class FamilyPages(BasePage): first = True for (surname, handle_list) in ppl_handle_list: - if surname and not surname.isspace(): + if surname and not surname.isspace(): letter = get_index_letter(first_letter(surname), index_list) else: letter =' ' @@ -3137,10 +3137,10 @@ class FamilyPages(BasePage): for family in family_list: trow = Html("tr") tbody += trow - + tcell = Html("td", class_="ColumnRowLabel") trow += tcell - + if first or primary_difference(letter, prev_letter): first = False prev_letter = letter @@ -3149,7 +3149,7 @@ class FamilyPages(BasePage): title =_("Families beginning with letter ") + letter, inline =True) else: tcell += ' ' - + tcell = Html("td", class_="ColumnPartner") trow += tcell @@ -3245,7 +3245,7 @@ class FamilyPages(BasePage): relationshipdetail += Html("h2", self.page_title, inline = True) +\ (Html('sup') +\ - (Html('small') + + (Html('small') + self.get_citation_links(family.get_citation_list()))) # display relationships @@ -3261,7 +3261,7 @@ class FamilyPages(BasePage): # Narrative subsection notelist = family.get_note_list() - if notelist: + if notelist: relationshipdetail += self.display_note_list(notelist) # display family LDS ordinance... @@ -3279,7 +3279,7 @@ class FamilyPages(BasePage): # source references srcrefs = self.display_ind_sources(family) if srcrefs: - relationshipdetail += srcrefs + relationshipdetail += srcrefs # add clearline for proper styling # add footer section @@ -3302,19 +3302,19 @@ class PlacePages(BasePage): # and remembers the list of persons. A single call to 'display_pages' # displays both the Event List (Index) page and all the Event # pages. - + # The base class 'BasePage' is initialised once for each page that is # displayed. def __init__(self, report): self.report = report self.db = report.database self.place_dict = defaultdict(set) - + def display_pages(self, title): """ Generate and output the pages under the Place tab, namely the place index and the individual place pages. - + @param: title -- the web site title """ log.debug("obj_dict[Place]") @@ -3351,7 +3351,7 @@ class PlacePages(BasePage): placelist += Html("p", msg, id = "description") # begin alphabet navigation - index_list = get_first_letters(self.dbase_, place_handles, _KEYPLACE) + index_list = get_first_letters(self.dbase_, place_handles, _KEYPLACE) alpha_nav = alphabet_navigation(index_list) if alpha_nav is not None: placelist += alpha_nav @@ -3388,15 +3388,15 @@ class PlacePages(BasePage): for place_handle in handle_list: place = self.dbase_.get_place_from_handle(place_handle) - if place: + if place: place_title = _pd.display(self.dbase_, place) ml = get_main_location(self.dbase_, place) - if place_title and not place_title.isspace(): + if place_title and not place_title.isspace(): letter = get_index_letter(first_letter(place_title), index_list) else: - letter = ' ' + letter = ' ' trow = Html("tr") tbody += trow @@ -3409,7 +3409,7 @@ class PlacePages(BasePage): trow.attr = 'class = "BeginLetter"' tcell += Html( - "a", letter, name =letter, + "a", letter, name =letter, title = _("Places beginning with letter %s") % letter) else: tcell += " " @@ -3437,7 +3437,7 @@ class PlacePages(BasePage): else: tcell1 += ' ' tcell2 += ' ' - + # add clearline for proper styling # add footer section footer = self.write_footer() @@ -3495,7 +3495,7 @@ class PlacePages(BasePage): # place notes notelist = self.display_note_list(place.get_note_list()) if notelist is not None: - placedetail += notelist + placedetail += notelist # place urls urllinks = self.display_url_list(place.get_url_list()) @@ -3550,7 +3550,7 @@ class PlacePages(BasePage): body.attr +=' onload = "initialize();" ' # source references - srcrefs = self.display_ind_sources(place) + srcrefs = self.display_ind_sources(place) if srcrefs is not None: placedetail += srcrefs @@ -3580,7 +3580,7 @@ class EventPages(BasePage): # and remembers the list of persons. A single call to 'display_pages' # displays both the Event List (Index) page and all the Event # pages. - + # The base class 'BasePage' is initialised once for each page that is # displayed. def __init__(self, report): @@ -3589,12 +3589,12 @@ class EventPages(BasePage): self.event_dict = defaultdict(set) self.report = report self.db = report.database - + def display_pages(self, title): """ Generate and output the pages under the Event tab, namely the event index and the individual event pages. - + @param: title -- the web site title """ log.debug("obj_dict[Event]") @@ -3606,7 +3606,7 @@ class EventPages(BasePage): event = self.report.database.get_event_from_handle(event_handle) event_types.append(str(event.get_type())) with self.report.user.progress(_("Narrated Web Site Report"), - _("Creating event pages"), + _("Creating event pages"), len(event_handle_list) + 1) as step: self.EventListPage(self.report, title, event_types, event_handle_list) @@ -3614,7 +3614,7 @@ class EventPages(BasePage): step() self.EventPage(self.report, title, event_handle) - + def EventListPage(self, report, title, event_types, event_handle_list): """ Will create the event list page @@ -3685,12 +3685,12 @@ class EventPages(BasePage): # check to see if we have listed this gramps_id yet? if gid not in _EVENT_DISPLAYED: - # family event + # family event if int(_type) in _EVENTMAP: - handle_list = set(self.dbase_.find_backlink_handles(event_handle, + handle_list = set(self.dbase_.find_backlink_handles(event_handle, include_classes = ['Family', 'Person'])) else: - handle_list = set(self.dbase_.find_backlink_handles(event_handle, + handle_list = set(self.dbase_.find_backlink_handles(event_handle, include_classes = ['Person'])) if handle_list: @@ -3716,8 +3716,8 @@ class EventPages(BasePage): "a", letter, name = letter, id_ = letter, title = _("Event types beginning with letter %s") % letter, inline = True) else: - tcell += " " - + tcell += " " + # display Event type if first in the list tcell = Html("td", class_="ColumnType", title=evt_type, inline=True) @@ -3727,7 +3727,7 @@ class EventPages(BasePage): if trow.attr == "": trow.attr = 'class = "BeginType"' else: - tcell += " " + tcell += " " # event date tcell = Html("td", class_ = "ColumnDate", inline = True) @@ -3738,7 +3738,7 @@ class EventPages(BasePage): if date and date is not Date.EMPTY: tcell += _dd.display(date) else: - tcell += " " + tcell += " " # GRAMPS ID trow += Html("td", class_ = "ColumnGRAMPSID") + ( @@ -3830,7 +3830,7 @@ class EventPages(BasePage): # begin eventdetail table with Html("table", class_ = "infolist eventlist") as table: eventdetail += table - + tbody = Html("tbody") table += tbody @@ -3841,11 +3841,11 @@ class EventPages(BasePage): 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: @@ -3872,7 +3872,7 @@ class EventPages(BasePage): # event source references srcrefs = self.display_ind_sources(event) if srcrefs is not None: - eventdetail += srcrefs + eventdetail += srcrefs # display additional images as gallery if self.create_media: @@ -3888,7 +3888,7 @@ class EventPages(BasePage): # add clearline for proper styling # add footer section footer = self.write_footer() - body += (fullclear, footer) + body += (fullclear, footer) # send page out for processing # and close the page @@ -3939,7 +3939,7 @@ class SurnameListPage(BasePage): else: table_id = 'SortByName' - # begin surnamelist table and table head + # begin surnamelist table and table head with Html("table", class_ = "infolist primobjlist surnamelist", id = table_id) as table: surnamelist += table @@ -3951,7 +3951,7 @@ class SurnameListPage(BasePage): trow += Html("th", _("Letter"), class_ = "ColumnLetter", inline = True) - # create table header surname hyperlink + # create table header surname hyperlink fname = self.report.surname_fname + self.ext tcell = Html("th", class_ = "ColumnSurname", inline = True) trow += tcell @@ -3984,7 +3984,7 @@ class SurnameListPage(BasePage): first_surname = True for (surname, data_list) in ppl_handle_list: - + if surname and not surname.isspace(): letter = first_letter(surname) if order_by == self.ORDER_BY_NAME: @@ -4006,7 +4006,7 @@ class SurnameListPage(BasePage): prev_letter = letter trow.attr = 'class = "BeginLetter"' hyper = Html( - "a", letter, name = letter, + "a", letter, name = letter, title = _("Surnames beginning with letter %s") % letter, inline = True) tcell += hyper elif first_surname or surname != prev_surname: @@ -4014,7 +4014,7 @@ class SurnameListPage(BasePage): tcell += " " prev_surname = surname - trow += Html("td", self.surname_link(name_to_md5(surname), html_escape(surname)), + trow += Html("td", self.surname_link(name_to_md5(surname), html_escape(surname)), class_ = "ColumnSurname", inline = True) trow += Html("td", len(data_list), class_ = "ColumnQuantity", inline = True) @@ -4055,9 +4055,9 @@ class IntroductionPage(BasePage): note_id = report.options['intronote'] if note_id: - note = self.dbase_.get_note_from_gramps_id(note_id) + note = self.dbase_.get_note_from_gramps_id(note_id) note_text = self.get_note_format(note, False) - + # attach note section += note_text @@ -4115,7 +4115,7 @@ class CitationPages(BasePage): def __init__(self, report): self.report = report self.db = report.database - + def display_pages(self): pass @@ -4131,19 +4131,19 @@ class SourcePages(BasePage): # 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): self.source_dict = defaultdict(set) self.report = report self.db = report.database - + def display_pages(self, title): """ Generate and output the pages under the Sources tab, namely the sources index and the individual sources pages. - + @param: title -- the web site title """ log.debug("obj_dict[Source]") @@ -4159,11 +4159,11 @@ class SourcePages(BasePage): step() self.SourcePage(self.report, title, source_handle) - + def SourceListPage(self, report, title, source_handles): """ Generate and output the Sources index page. - + @param: report -- the instance of the main report class for this report @param: title -- the web site title @param: source_handles -- a list of the handles of the sources to be @@ -4187,7 +4187,7 @@ class SourcePages(BasePage): if source is not None: key = source.get_title() + str(source.get_gramps_id()) source_dict[key] = (source, handle) - + keys = sorted(source_dict, key=SORT_KEY) msg = _("This page contains an index of all the sources in the " @@ -4198,7 +4198,7 @@ class SourcePages(BasePage): # begin sourcelist table and table head with Html("table", class_ = "infolist primobjlist sourcelist") as table: - sourceslist += table + sourceslist += table thead = Html("thead") table += thead @@ -4212,7 +4212,7 @@ class SourcePages(BasePage): trow.extend( Html("th", label or " ", class_ =colclass, inline =True) for (label, colclass) in header_row) - + # begin table body tbody = Html("tbody") table += tbody @@ -4241,7 +4241,7 @@ class SourcePages(BasePage): def SourcePage(self, report, title, source_handle): """ Generate and output an individual Source page. - + @param: report -- the instance of the main report class for this report @param: title -- the web site title @param: source_handle -- the handle of the source to be output @@ -4259,7 +4259,7 @@ class SourcePages(BasePage): of, sio = self.report.create_file(source_handle, "src") self.up = True - sourcepage, head, body = self.write_header("%s - %s" % (_('Sources'), + sourcepage, head, body = self.write_header("%s - %s" % (_('Sources'), self.page_title)) # begin source detail division @@ -4282,7 +4282,7 @@ class SourcePages(BasePage): tbody = Html("tbody") table += tbody - source_gid = False + source_gid = False if not self.noid and self.gid: source_gid = source.get_gramps_id() @@ -4324,7 +4324,7 @@ class SourcePages(BasePage): ref_list = self.display_bkref_list(Source, source_handle) if ref_list is not None: sourcedetail += ref_list - + # add clearline for proper styling # add footer section footer = self.write_footer() @@ -4346,28 +4346,28 @@ class MediaPages(BasePage): # 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): self.media_dict = defaultdict(set) self.report = report self.db = report.database - + 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 -- the web site title """ log.debug("obj_dict[Media]") for item in self.report.obj_dict[MediaObject].items(): log.debug(" %s" % str(item)) with self.report.user.progress(_("Narrated Web Site Report"), - _("Creating media pages"), + _("Creating media pages"), len(self.report.obj_dict[MediaObject]) + 1) as step: - + sorted_media_handles = sorted(self.report.obj_dict[MediaObject].keys(), key=lambda x: SORT_KEY(self.report.database.get_object_from_handle(x).desc)) self.MediaListPage(self.report, title, sorted_media_handles) @@ -4386,7 +4386,7 @@ class MediaPages(BasePage): 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 -- the web site title @param: sorted_media_handles -- a list of the handles of the media to be @@ -4431,7 +4431,7 @@ class MediaPages(BasePage): (_("Mime Type"), "ColumnMime") ] ) - + # begin table body tbody = Html("tbody") table += tbody @@ -4483,13 +4483,13 @@ class MediaPages(BasePage): 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 -- the web site title @param: item -- a tuple containing the source handle and a list of back-references @param: info -- a tuple containing the media handle for the next and - previous media, the current page number, and the total number of + previous media, the current page number, and the total number of media pages """ (prev, next, page_number, total_pages) = info @@ -4534,12 +4534,12 @@ class MediaPages(BasePage): body += mediadetail # media navigation - with Html("div", id = "GalleryNav", role = "navigation") as medianav: + with Html("div", id = "GalleryNav", role = "navigation") as medianav: mediadetail += medianav if prev: medianav += self.media_nav_link(prev, _("Previous"), True) data = _('%(strong1_start)s%(page_number)d%(strong_end)s of ' - '%(strong2_start)s%(total_pages)d%(strong_end)s' + '%(strong2_start)s%(total_pages)d%(strong_end)s' ) % { 'strong1_start' : '' , 'strong2_start' : @@ -4562,8 +4562,8 @@ class MediaPages(BasePage): if not target_exists: with Html("div", id = "MediaDisplay") as mediadisplay: summaryarea += mediadisplay - mediadisplay += Html("span", errormsg, class_ = "MissingImage") - + 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 @@ -4608,7 +4608,7 @@ class MediaPages(BasePage): # TODO. Convert disk path to URL. url = self.report.build_url_fname(initial_image_path, None, self.up) - with Html("div", id="GalleryDisplay", style = 'width: %dpx; height: %dpx' % (new_width, + with Html("div", id="GalleryDisplay", style = 'width: %dpx; height: %dpx' % (new_width, new_height)) as mediadisplay: summaryarea += mediadisplay @@ -4623,14 +4623,14 @@ class MediaPages(BasePage): ordered += Html("li", style = "left:%d%%; top:%d%%; width:%d%%; height:%d%%;" % (x, y, w, h)) + ( Html("a", name, href = linkurl) - ) + ) # display the image if initial_image_path != newpath: - url = self.report.build_url_fname(newpath, + url = self.report.build_url_fname(newpath, None, self.up) mediadisplay += Html("a", href = url) + ( - Html("img", width = new_width, + Html("img", width = new_width, height = new_height, src = url, alt = html_escape(self.page_title)) ) @@ -4664,7 +4664,7 @@ class MediaPages(BasePage): ) mediadisplay += hyper else: - mediadisplay += Html("span", errormsg, class_ = "MissingImage") + mediadisplay += Html("span", errormsg, class_ = "MissingImage") else: with Html("div", id = "GalleryDisplay") as mediadisplay: summaryarea += mediadisplay @@ -4677,7 +4677,7 @@ class MediaPages(BasePage): summaryarea += title # begin media table - with Html("table", class_ = "infolist gallery") as table: + with Html("table", class_ = "infolist gallery") as table: summaryarea += table # GRAMPS ID @@ -4690,7 +4690,7 @@ class MediaPages(BasePage): table += trow # mime type - if mime_type: + if mime_type: trow = Html("tr") + ( Html("td", _("File Type"), class_ = "ColumnAttribute", inline = True), Html("td", mime_type, class_ = "ColumnValue", inline = True) @@ -4723,7 +4723,7 @@ class MediaPages(BasePage): if srclist is not None: mediadetail += srclist - # get media references + # get media references reflist = self.display_bkref_list(MediaObject, media_handle) if reflist is not None: mediadetail += reflist @@ -4748,7 +4748,7 @@ class MediaPages(BasePage): def display_media_sources(self, photo): list(map(lambda i: self.bibli.add_reference( - self.report.database.get_citation_from_handle(i)), + self.report.database.get_citation_from_handle(i)), photo.get_citation_list())) sourcerefs = self.display_source_refs(self.bibli) @@ -4832,14 +4832,14 @@ class ThumbnailPreviewPage(BasePage): thead += trow trow += Html("th", _("Thumbnail Preview"), class_ ="monthName", colspan=7, inline =True) - + # table header cells... trow = Html("tr") thead += trow ltrs = [" ", " ", " ", " ", " ", " ", " "] for ltr in ltrs: - trow += Html("th", ltr, class_ ="weekend", inline =True) + trow += Html("th", ltr, class_ ="weekend", inline =True) tbody = Html("tbody") table += tbody @@ -4862,7 +4862,7 @@ class ThumbnailPreviewPage(BasePage): # begin table cell and attach to table row(trow)... tcell = Html("td", class_ ="highlight weekend") trow += tcell - + # attach index number... numberdiv = Html("div", class_ ="date") tcell += numberdiv @@ -4872,9 +4872,9 @@ class ThumbnailPreviewPage(BasePage): # begin unordered list and attach to table cell(tcell)... unordered = Html("ul") - tcell += unordered + tcell += unordered - # create thumbnail + # create thumbnail real_path, newpath = self.report.prepare_copy_media(photo) newpath = self.report.build_url_fname(newpath) @@ -4893,7 +4893,7 @@ class ThumbnailPreviewPage(BasePage): if (grid_row == num_of_rows and cols < num_of_cols): for emptyCols in range(cols, num_of_cols): trow += Html("td", class_ ="emptyDays", inline =True) - + # begin Thumbnail Reference section... with Html("div", class_ ="subsection", id ="references") as section: body += section @@ -4903,7 +4903,7 @@ class ThumbnailPreviewPage(BasePage): section += table tbody = Html("tbody") - table += tbody + table += tbody index = 1 for ptitle, person_handle, photo in media_list: @@ -4914,7 +4914,7 @@ class ThumbnailPreviewPage(BasePage): tcell2 = Html("td", ptitle, class_ ="ColumnName") trow += (tcell1, tcell2) - # increase index for row number... + # increase index for row number... index += 1 # increase progress meter... @@ -5018,7 +5018,7 @@ class DownloadPage(BasePage): (_("File Name"), "Filename"), (DESCRHEAD, "Description"), (_("Last Modified"), "Modified") ] - ) + ) # table body tbody = Html("tbody") table += tbody @@ -5030,7 +5030,7 @@ class DownloadPage(BasePage): tbody += trow fname = os.path.basename(dlfname1) - # TODO dlfname1 is filename, convert disk path to URL + # TODO dlfname1 is filename, convert disk path to URL tcell = Html("td", class_ = "ColumnFilename") + ( Html("a", fname, href = dlfname1, title = html_escape(dldescr1)) ) @@ -5040,7 +5040,7 @@ class DownloadPage(BasePage): trow += Html("td", dldescr1, class_ = "ColumnDescription", inline = True) tcell = Html("td", class_ = "ColumnModified", inline = True) - trow += tcell + trow += tcell if os.path.exists(dlfname1): modified = os.stat(dlfname1).st_mtime last_mod = datetime.datetime.fromtimestamp(modified) @@ -5058,7 +5058,7 @@ class DownloadPage(BasePage): fname = os.path.basename(dlfname2) tcell = Html("td", class_ = "ColumnFilename") + ( Html("a", fname, href = dlfname2, title = html_escape(dldescr2)) - ) + ) trow += tcell dldescr2 = dldescr2 or " " @@ -5092,7 +5092,7 @@ class ContactPage(BasePage): # begin contact division with Html("div", class_ = "content", id = "Contact") as section: - body += section + body += section # begin summaryarea division with Html("div", id = 'summaryarea') as summaryarea: @@ -5135,7 +5135,7 @@ class ContactPage(BasePage): if note_id: note = self.dbase_.get_note_from_gramps_id(note_id) note_text = self.get_note_format(note, False) - + # attach note summaryarea += note_text @@ -5160,26 +5160,26 @@ class PersonPages(BasePage): # 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): self.ind_dict = defaultdict(set) self.report = report self.db = report.database - + def display_pages(self, title): """ Generate and output the pages under the Individuals tab, namely the individual index and the individual pages. - + @param: title -- the web site title """ log.debug("obj_dict[Person]") for item in self.report.obj_dict[Person].items(): log.debug(" %s" % str(item)) with self.report.user.progress(_("Narrated Web Site Report"), - _('Creating individual pages'), + _('Creating individual pages'), len(self.report.obj_dict[Person]) + 1) as step: self.IndividualListPage(self.report, title, self.report.obj_dict[Person].keys()) @@ -5187,7 +5187,7 @@ class PersonPages(BasePage): step() person = self.report.database.get_person_from_handle(person_handle) self.IndividualPage(self.report, title, person) - + ################################################# # # creates the Individual List Page @@ -5219,7 +5219,7 @@ class PersonPages(BasePage): individuallist += Html("p", msg, id = "description") # add alphabet navigation - index_list = get_first_letters(self.dbase_, ppl_handle_list, _KEYPERSON) + index_list = get_first_letters(self.dbase_, ppl_handle_list, _KEYPERSON) alpha_nav = alphabet_navigation(index_list) if alpha_nav is not None: individuallist += alpha_nav @@ -5231,7 +5231,7 @@ class PersonPages(BasePage): table += thead trow = Html("tr") - thead += trow + thead += trow # show surname and first name trow += Html("th", _("Surname"), class_ = "ColumnSurname", inline = True) @@ -5255,13 +5255,13 @@ class PersonPages(BasePage): ppl_handle_list = sort_people(self.dbase_, ppl_handle_list) first = True for (surname, handle_list) in ppl_handle_list: - + if surname and not surname.isspace(): letter = get_index_letter(first_letter(surname), index_list) else: letter = ' ' surname = _ABSENT - + first_surname = True for person_handle in handle_list: person = self.dbase_.get_person_from_handle(person_handle) @@ -5271,7 +5271,7 @@ class PersonPages(BasePage): tbody += trow tcell = Html("td", class_ = "ColumnSurname", inline = True) trow += tcell - + if first or primary_difference(letter, prev_letter): first = False first_surname = False @@ -5285,12 +5285,12 @@ class PersonPages(BasePage): {'surname' : surname, 'letter' : letter}) elif first_surname: - first_surname = False + first_surname = False tcell += Html("a", html_escape(surname), title = "Surnames " + surname) else: tcell += " " - + # firstname column link = self.new_person_link(person_handle, person=person, name_style=_NAME_STYLE_FIRST) @@ -5370,7 +5370,7 @@ class PersonPages(BasePage): father_name = self.get_name(father) if mother: mother_name = self.get_name(mother) - samerow = False + samerow = False if mother and father: tcell = (Html("span", father_name, class_ = "father fatherNmother", inline=True), Html("span", mother_name, class_ = "mother", inline=True)) @@ -5509,7 +5509,7 @@ class PersonPages(BasePage): # display attributes attrlist = person.get_attribute_list() - if attrlist: + if attrlist: attrsection, attrtable = self.display_attribute_header() self.display_attr_list(attrlist, attrtable) individualdetail += attrsection @@ -5542,7 +5542,7 @@ class PersonPages(BasePage): if sect13 is not None: individualdetail += sect13 - # display ancestor tree + # display ancestor tree if report.options['ancestortree']: sect14 = self.display_tree() if sect14 is not None: @@ -5618,7 +5618,7 @@ class PersonPages(BasePage): elif spany in largeset: zoomlevel = 4 else: - zoomlevel = 3 + zoomlevel = 3 # 0 = latitude, 1 = longitude, 2 = place title, 3 = handle, and 4 = date, 5 = event type... # being sorted by date, latitude, and longitude... @@ -5711,7 +5711,7 @@ class PersonPages(BasePage): "list are sorted in date order (if any?). " "Clicking on a place’s " "name in the Reference section will take you " - "to that place’s page.") + "to that place’s page.") mapdetail += Html("p", msg, id = "description") # this is the style element where the Map is held in the CSS... @@ -5800,7 +5800,7 @@ class PersonPages(BasePage): tbody = Html("tbody") table += tbody - + for (latitude, longitude, placetitle, handle, date, etype) in place_lat_long: trow = Html("tr") tbody += trow @@ -5813,7 +5813,7 @@ class PersonPages(BasePage): (str(etype), "ColumnType") ] ) - + # add body id for this page... body.attr = 'id ="FamilyMap" onload ="initialize()"' @@ -5858,11 +5858,11 @@ class PersonPages(BasePage): divclass = "female" else: divclass = "unknown" - + boxbg = Html("div", class_ = "boxbg %s AncCol%s" % (divclass, col), style="top: %dpx; left: %dpx;" % (top, xoff+1) ) - + person_name = self.get_name(person) # This does not use [new_]person_link because the requirements are # unique @@ -5916,7 +5916,7 @@ class PersonPages(BasePage): ) gv = Html("div", class_ = "gvline", inline = True, style = style % (y0+_SHADOW, x0, _HGAP/2+_SHADOW) - ) + ) return [bv, gv] def connect_line(self, y0, y1, col): @@ -5925,7 +5925,7 @@ class PersonPages(BasePage): styleh = "top: %dpx; left: %dpx; height: %dpx;" x0 = _XOFFSET + col * _WIDTH + (col-1)*_HGAP + _HGAP/2 bv = Html("div", class_ = "bvline", inline = True, style=stylew % (y1, x0, _HGAP/2)) - gv = Html("div", class_ = "gvline", inline = True, style=stylew % + gv = Html("div", class_ = "gvline", inline = True, style=stylew % (y1+_SHADOW, x0+_SHADOW, _HGAP/2+_SHADOW)) bh = Html("div", class_ = "bhline", inline = True, style=styleh % (y, x0, abs(y0-y1))) gh = Html("div", class_ = "gvline", inline = True, style=styleh % @@ -5958,11 +5958,11 @@ class PersonPages(BasePage): tree += Html("h4", _('Ancestors'), inline = True) with Html("div", id = "treeContainer", style="width:%dpx; height:%dpx;" % - (_XOFFSET+(generations)*_WIDTH+(generations-1)*_HGAP, + (_XOFFSET+(generations)*_WIDTH+(generations-1)*_HGAP, max_size) ) as container: tree += container - container += self.draw_tree(1, generations, max_size, + container += self.draw_tree(1, generations, max_size, 0, center, self.person.handle) return tree @@ -5995,12 +5995,12 @@ class PersonPages(BasePage): f_center = new_center-gen_offset f_handle = family.get_father_handle() - tree += self.draw_tree(gen_nr+1, maxgen, max_size, + tree += self.draw_tree(gen_nr+1, maxgen, max_size, new_center, f_center, f_handle) m_center = new_center+gen_offset m_handle = family.get_mother_handle() - tree += self.draw_tree(gen_nr+1, maxgen, max_size, + tree += self.draw_tree(gen_nr+1, maxgen, max_size, new_center, m_center, m_handle) return tree @@ -6009,7 +6009,7 @@ class PersonPages(BasePage): display an individual's associations """ - # begin Associations division + # begin Associations division with Html("div", class_ = "subsection", id = "Associations") as section: section += Html("h4", _('Associations'), inline = True) @@ -6049,13 +6049,13 @@ class PersonPages(BasePage): person_ref.get_relation(), self.dump_notes(person_ref.get_note_list()), self.get_citation_links(person_ref.get_citation_list()), - ]: + ]: # get colclass from assoc_row colclass = assoc_row[index][1] - trow += Html("td", data, class_ = "Column" + colclass, - inline = True) + trow += Html("td", data, class_ = "Column" + colclass, + inline = True) index += 1 # return section to its callers @@ -6077,7 +6077,7 @@ class PersonPages(BasePage): if birthorder: children = sorted(children) - + for birthdate, handle in children: if handle == self.person.get_handle(): child_ped(ol) @@ -6087,7 +6087,7 @@ class PersonPages(BasePage): else: child_ped(ol) return ol - + def child_ped(ol): with Html("li", self.name, class_="thisperson") as pedfam: family = self.pedigree_family() @@ -6133,7 +6133,7 @@ class PersonPages(BasePage): else: pedol += (Html("li") + children_ped(Html("ol"))) return ped - + def display_ind_general(self): """ display an individual's general information... @@ -6142,7 +6142,7 @@ class PersonPages(BasePage): thumbnail = self.display_first_image_as_thumbnail(self.person.get_media_list(), self.person) section_title = Html("h3", html_escape(self.page_title), inline =True) + \ (Html('sup') +\ - (Html('small') + + (Html('small') + self.get_citation_links(self.person.get_citation_list()))) # begin summaryarea division @@ -6162,7 +6162,7 @@ class PersonPages(BasePage): for name in all_names: pname = html_escape(_nd.display_name(name)) # if name == primary_name: -# pname += self.get_citation_links(self.person.get_citation_list() ) +# pname += self.get_citation_links(self.person.get_citation_list() ) pname += self.get_citation_links( name.get_citation_list() ) # if we have just a firstname, then the name is preceeded by ", " @@ -6190,12 +6190,12 @@ class PersonPages(BasePage): note = self.dbase_.get_note_from_handle(notehandle) if note: note_text = self.get_note_format(note, True) - + # attach note unordered += note_text tcell += unordered trow += tcell - table += trow + table += trow # display the callname associated with this name. call_name = name.get_call_name() @@ -6220,8 +6220,8 @@ class PersonPages(BasePage): Html("td", _("Nick Name"), class_ = "ColumnAttribute", inline = True), Html("td", nick_name, class_ = "ColumnValue", inline = True) ) - table += trow - + table += trow + # GRAMPS ID person_gid = self.person.get_gramps_id() if not self.noid and person_gid: @@ -6244,7 +6244,7 @@ class PersonPages(BasePage): birth_ref = self.person.get_birth_ref() if birth_ref: birth = self.dbase_.get_event_from_handle(birth_ref.ref) - if birth: + if birth: birth_date = birth.get_date_object() if birth_date and birth_date is not Date.EMPTY: @@ -6261,7 +6261,7 @@ class PersonPages(BasePage): table += trow # return all three pieces to its caller - # do NOT combine before returning + # do NOT combine before returning return thumbnail, section_title, summaryarea def display_ind_events(self, place_lat_long): @@ -6274,7 +6274,7 @@ class PersonPages(BasePage): event_ref_list = self.person.get_event_ref_list() if not event_ref_list: return None - + # begin events division and section title with Html("div", id = "events", class_ = "subsection") as section: section += Html("h4", _("Events"), inline = True) @@ -6325,14 +6325,14 @@ class PersonPages(BasePage): return (child_ref.get_father_relation(), child_ref.get_mother_relation()) return (None, None) - + def display_ind_parent_family(self, birthmother, birthfather, family, table, first = False): if not first: trow = Html("tr") + (Html("td", " ", colspan =3, inline = True)) table += trow - + # get the father father_handle = family.get_father_handle() if father_handle: @@ -6349,7 +6349,7 @@ class PersonPages(BasePage): reln = _("Stepfather") trow = Html("tr") + (self.display_parent(father_handle, reln, None)) table += trow - + # get the mother mother_handle = family.get_mother_handle() if mother_handle: @@ -6374,7 +6374,7 @@ class PersonPages(BasePage): # sibling, we cannot necessarily guarantee that. sibling_type = self.rel_class.get_sibling_type( self.dbase_, self.person, child) - + reln = self.rel_class.get_sibling_relationship_string( sibling_type, self.person.gender, child.gender) @@ -6393,7 +6393,7 @@ class PersonPages(BasePage): frelmrel = "" trow = Html("tr") + ( Html("td", reln, class_ = "ColumnAttribute", inline = True)) - + tcell = Html("td", class_ = "ColumnValue", inline = True) tcell += "    " tcell += self.display_child_link(child_handle) @@ -6414,7 +6414,7 @@ class PersonPages(BasePage): self.display_ind_parent_family(birthmother, birthfather, parent_family, table) all_family_handles.append(parent_family_handle) - + def display_ind_parents(self): """ Display a person's parents @@ -6450,11 +6450,11 @@ class PersonPages(BasePage): tbody = Html("tbody") table += tbody - + all_family_handles = list(parent_list) (birthmother, birthfather) = self.rel_class.get_birth_parents( self.dbase_, self.person) - + first = True for family_handle in parent_list: family = self.dbase_.get_family_from_handle(family_handle) @@ -6464,7 +6464,7 @@ class PersonPages(BasePage): birthmother, birthfather, family, table, first) first = False - + if self.report.options['showhalfsiblings']: # Display all families in which the parents are # involved. This displays half siblings and step @@ -6477,7 +6477,7 @@ class PersonPages(BasePage): family.get_mother_handle(), family, all_family_handles, birthmother, birthfather, table) - return section + return section def pedigree_person(self, person): """ @@ -6518,7 +6518,7 @@ class PersonPages(BasePage): """ will print the event header row for display_event_row() and format_family_events() - """ + """ trow = Html("tr") trow.extend( @@ -6545,20 +6545,20 @@ class RepositoryPages(BasePage): # 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): self.repos_dict = defaultdict(set) self.report = report pass - + def display_pages(self, title): """ Generate and output the pages under the Repository tab, namely the repository index and the individual repository pages. - + @param: title -- the web site title """ log.debug("obj_dict[Person]") @@ -6567,7 +6567,7 @@ class RepositoryPages(BasePage): # set progress bar pass for Repositories with self.report.user.progress(_("Narrated Web Site Report"), - _('Creating repository pages'), + _('Creating repository pages'), len(self.report.obj_dict[Repository]) + 1) as step: # Sort the repositories repos_dict = {} @@ -6575,7 +6575,7 @@ class RepositoryPages(BasePage): repository = self.report.database.get_repository_from_handle(repository_handle) key = repository.get_name() + str(repository.get_gramps_id()) repos_dict[key] = (repository, repository_handle) - + keys = sorted(repos_dict, key = SORT_KEY) # RepositoryListPage Class @@ -6608,7 +6608,7 @@ class RepositoryPages(BasePage): # begin repositories table and table head with Html("table", class_ = "infolist primobjlist repolist") as table: - repositorylist += table + repositorylist += table thead = Html("thead") table += thead @@ -6622,7 +6622,7 @@ class RepositoryPages(BasePage): # begin table body tbody = Html("tbody") - table += tbody + table += tbody for index, key in enumerate(keys): (repo, handle) = repos_dict[key] @@ -6700,7 +6700,7 @@ class RepositoryPages(BasePage): repositorydetail += urllist # reposity: notelist - notelist = self.display_note_list(repo.get_note_list()) + notelist = self.display_note_list(repo.get_note_list()) if notelist is not None: repositorydetail += notelist @@ -6777,12 +6777,12 @@ class AddressBookListPage(BasePage): # has residence, but no addresses elif has_res and not has_add: - residence = "X" + residence = "X" # has residence and addresses too elif has_add and has_res: address = "X" - residence = "X" + residence = "X" # has Web Links if has_url: @@ -6855,7 +6855,7 @@ class AddressBookPage(BasePage): self.XHTMLWriter(addressbookpage, of, sio) class NavWebReport(Report): - + def __init__(self, database, options, user): """ Create WebReport object that produces the report. @@ -6967,7 +6967,7 @@ class NavWebReport(Report): self.intro_fname = None self.archive = None - self.cur_fname = None # Internal use. The name of the output file, + self.cur_fname = None # Internal use. The name of the output file, # to be used for the tar archive. self.string_io = None if self.use_archive: @@ -7039,19 +7039,19 @@ class NavWebReport(Report): # for use with discovering biological, half, and step siblings for use # in display_ind_parents()... self.rel_class = get_relationship_calculator() - + ################################################# - # + # # Pass 0 Initialise the plug-ins # ################################################# - + # FIXME: The whole of this section of code should be implemented by the # registration process for the Web Page plugins. - + # Note that by use of a dictionary we ensure that at most one Web Page # plugin is provided for any object class - + self.tab = {} # FIXME: Initialising self.tab in this way means that this code has to # run before the Web Page registration - I am not sure whether this is @@ -7078,7 +7078,7 @@ class NavWebReport(Report): self.tab["Source"] = SourcePages(self) self.tab["Repository"] = RepositoryPages(self) self.tab["Citation"] = CitationPages(self) - + # FIXME: The following routines that are not run in two passes have not # yet been converted to a form suitable for separation into Web Page # plugins: SurnamePage, SurnameListPage, IntroductionPage, HomePage, @@ -7086,24 +7086,24 @@ class NavWebReport(Report): # AddressBookPage ################################################# - # + # # Pass 1 Build the lists of objects to be output # ################################################# - + self._build_obj_dict() - + ################################################# - # + # # Pass 2 Generate the web pages # ################################################# - + self.base_pages() # build classes IndividualListPage and IndividualPage self.tab["Person"].display_pages(self.title) - + self.build_gendex(self.obj_dict[Person]) # build classes SurnameListPage and SurnamePage @@ -7145,7 +7145,7 @@ class NavWebReport(Report): # if an archive is being used, close it? if self.archive: self.archive.close() - + if len(_WRONGMEDIAPATH) > 0: error = '\n'.join([_('ID=%(grampsid)s, path=%(dir)s') % { 'grampsid': x[0], @@ -7155,7 +7155,7 @@ class NavWebReport(Report): self.user.warn(_("Missing media objects:"), error) ########################################################################### - # + # # Construct the dictionaries of objects to be included in the reports. There # are two dictionaries, which have the same structure: they are two level # dictionaries,the first key is the class of object (e.g. gen.lib.Person). @@ -7171,26 +7171,26 @@ class NavWebReport(Report): def _build_obj_dict(self): _obj_class_list = (Person, Family, Event, Place, Source, Citation, MediaObject, Repository, Note, Tag) - + # setup a dictionary of the required structure self.obj_dict = defaultdict(lambda: defaultdict(set)) self.bkref_dict = defaultdict(lambda: defaultdict(set)) - - + + # initialise the dictionary to empty in case no objects of any # particular class are incuded in the web report for obj_class in _obj_class_list: self.obj_dict[obj_class] = defaultdict(set) - + ind_list = self.database.iter_person_handles() with self.user.progress(_("Narrated Web Site Report"), - _('Applying Person Filter...'), + _('Applying Person Filter...'), self.database.get_number_of_people()) as step: ind_list = self.filter.apply(self.database, ind_list, step) - + with self.user.progress(_("Narrated Web Site Report"), - _('Constructing list of other objects...'), + _('Constructing list of other objects...'), sum(1 for _ in ind_list)) as step: for handle in ind_list: # FIXME work around bug that self.database.iter under python 3 @@ -7199,13 +7199,13 @@ class NavWebReport(Report): handle = handle.decode('utf-8') step() self._add_person(handle, "", "") - - log.debug("final object dictionary \n" + + + log.debug("final object dictionary \n" + "".join(("%s: %s\n" % item) for item in self.obj_dict.items())) - - log.debug("final backref dictionary \n" + + + log.debug("final backref dictionary \n" + "".join(("%s: %s\n" % item) for item in self.bkref_dict.items())) - + def _add_person(self, person_handle, bkref_class, bkref_handle): """ Add person_handle to the obj_dict, and recursively all referenced @@ -7223,15 +7223,15 @@ class NavWebReport(Report): ############### Header section ############## for citation_handle in person.get_citation_list(): self._add_citation(citation_handle, Person, person_handle) - + ############### Name section ############## for name in [person.get_primary_name()] + \ person.get_alternate_names(): for citation_handle in name.get_citation_list(): self._add_citation(citation_handle, Person, person_handle) - + ############### Events section ############## - # Now tell the events tab to display the individual events + # Now tell the events tab to display the individual events evt_ref_list = person.get_event_ref_list() if evt_ref_list: for evt_ref in evt_ref_list: @@ -7249,17 +7249,17 @@ class NavWebReport(Report): for media_ref in event.get_media_list(): media_handle = media_ref.get_reference_handle() self._add_media(media_handle, Person, person_handle) - + for citation_handle in event.get_citation_list(): self._add_citation(citation_handle, Person, person_handle) - + ############### Families section ############## # Tell the families tab to display this individuals families family_handle_list = person.get_family_handle_list() if family_handle_list: for family_handle in person.get_family_handle_list(): self._add_family(family_handle, Person, person_handle) - + # Tell the events tab to display the family events which are # referenced from the individual page. family = self.database.get_family_from_handle(family_handle) @@ -7268,7 +7268,7 @@ class NavWebReport(Report): if family_evt_ref_list: for evt_ref in family_evt_ref_list: event = self.database.get_event_from_handle(evt_ref.ref) - if event: + if event: self._add_event(evt_ref.ref, Person, person_handle) place_handle = event.get_place_handle() if place_handle: @@ -7284,20 +7284,20 @@ class NavWebReport(Report): media_handle = media_ref.get_reference_handle() self._add_media( media_handle, Person, person_handle) - + for lds_ord in family.get_lds_ord_list(): for citation_handle in lds_ord.get_citation_list(): self._add_citation(citation_handle, Person, person_handle) - + for attr in family.get_attribute_list(): for citation_handle in attr.get_citation_list(): self._add_citation(citation_handle, Person, person_handle) - + if not self.inc_families: for media_ref in family.get_media_list(): media_handle = media_ref.get_reference_handle() self._add_media(media_handle, Person, person_handle) - + ############### LDS Ordinance section ############## for lds_ord in person.get_lds_ord_list(): for citation_handle in lds_ord.get_citation_list(): @@ -7314,8 +7314,8 @@ class NavWebReport(Report): for media_ref in person.get_media_list(): media_handle = media_ref.get_reference_handle() self._add_media(media_handle, Person, person_handle) - - + + def get_person_name(self, person): """ Return a string containing the person's primary name in the name @@ -7330,7 +7330,7 @@ class NavWebReport(Report): return _nd.display_name(name) def _add_family(self, family_handle, bkref_class, bkref_handle): - + family = self.database.get_family_from_handle(family_handle) family_name = self.get_family_name(family) if self.inc_families: @@ -7346,14 +7346,14 @@ class NavWebReport(Report): for media_ref in family.get_media_list(): media_handle = media_ref.get_reference_handle() self._add_media(media_handle, Family, family_handle) - + ############### Events section ############## for evt_ref in family.get_event_ref_list(): event = self.database.get_event_from_handle(evt_ref.ref) place_handle = event.get_place_handle() if place_handle: self._add_place(place_handle, Family, family_handle) - + if self.inc_events: # detail for family events are displayed on the events pages as # well as on this family page @@ -7366,21 +7366,21 @@ class NavWebReport(Report): for media_ref in event.get_media_list(): media_handle = media_ref.get_reference_handle() self._add_media(media_handle, Family, family_handle) - + ############### LDS Ordinance section ############## for lds_ord in family.get_lds_ord_list(): for citation_handle in lds_ord.get_citation_list(): self._add_citation(citation_handle, Family, family_handle) - + ############### Attributes section ############## for attr in family.get_attribute_list(): for citation_handle in attr.get_citation_list(): self._add_citation(citation_handle, Family, family_handle) - + ############### Sources section ############## for citation_handle in family.get_citation_list(): self._add_citation(citation_handle, Family, family_handle) - + def get_family_name(self, family): """ Return a string containing the name of the family (e.g. 'Family of John @@ -7401,7 +7401,7 @@ class NavWebReport(Report): 'husband' : husband_name, 'spouse' : spouse_name} elif husband: husband_name = self.get_person_name(husband) - # Only the name of the husband is known + # Only the name of the husband is known title_str = _("Family of %s") % husband_name elif spouse: spouse_name = self.get_person_name(spouse) @@ -7431,16 +7431,16 @@ class NavWebReport(Report): self.obj_dict[Event][event_handle] = (event_fname, event_name, event.gramps_id) self.bkref_dict[Event][event_handle].add((bkref_class, bkref_handle)) - + ############### Attribute section ############## for attr in event.get_attribute_list(): for citation_handle in attr.get_citation_list(): self._add_citation(citation_handle, Event, event_handle) - + ############### Source section ############## for citation_handle in event.get_citation_list(): self._add_citation(citation_handle, Event, event_handle) - + ############### Media section ############## if self.inc_gallery: for media_ref in event.get_media_list(): @@ -7457,13 +7457,13 @@ class NavWebReport(Report): self.obj_dict[Place][place_handle] = (place_fname, place_name, place.gramps_id) self.bkref_dict[Place][place_handle].add((bkref_class, bkref_handle)) - + ############### Media section ############## if self.inc_gallery: for media_ref in place.get_media_list(): media_handle = media_ref.get_reference_handle() self._add_media(media_handle, Place, place_handle) - + ############### Sources section ############## for citation_handle in place.get_citation_list(): self._add_citation(citation_handle, Place, place_handle) @@ -7491,7 +7491,7 @@ class NavWebReport(Report): def _add_citation(self, citation_handle, bkref_class, bkref_handle): citation = self.database.get_citation_from_handle(citation_handle) - # If Page is none, we want to make sure that a tuple is generated for + # If Page is none, we want to make sure that a tuple is generated for # the source backreference citation_name = citation.get_page() or "" source_handle = citation.get_reference_handle() @@ -7501,7 +7501,7 @@ class NavWebReport(Report): ############### Source section ############## self._add_source(source_handle, Citation, citation_handle) - + ############### Media section ############## if self.inc_gallery: for media_ref in citation.get_media_list(): @@ -7527,11 +7527,11 @@ class NavWebReport(Report): for attr in media.get_attribute_list(): for citation_handle in attr.get_citation_list(): self._add_citation(citation_handle, MediaObject, media_handle) - + ############### Sources section ############## for citation_handle in media.get_citation_list(): self._add_citation(citation_handle, MediaObject, media_handle) - + def _add_repository(self, repos_handle, bkref_class, bkref_handle): repos = self.database.get_repository_from_handle(repos_handle) repos_name = repos.name @@ -7556,7 +7556,7 @@ class NavWebReport(Report): self.copy_file(fname, _NARRATIVESCREEN, "css") # copy printer style sheet - fname = CSS["Print-Default"]["filename"] + fname = CSS["Print-Default"]["filename"] self.copy_file(fname, _NARRATIVEPRINT, "css") # copy ancestor tree style sheet if tree is being created? @@ -7565,11 +7565,11 @@ class NavWebReport(Report): self.copy_file(fname, "ancestortree.css", "css") # copy behaviour style sheet - fname = CSS["behaviour"]["filename"] + fname = CSS["behaviour"]["filename"] self.copy_file(fname, "behaviour.css", "css") # copy Menu Layout Style Sheet if Blue or Visually is being used as the stylesheet? - if CSS[self.css]["navigation"]: + if CSS[self.css]["navigation"]: if self.navigation == "Horizontal": fname = CSS["Horizontal-Menus"]["filename"] elif self.navigation == "Vertical": @@ -7582,7 +7582,7 @@ class NavWebReport(Report): # copy narrative-maps Style Sheet if Place or Family Map pages are being created? if (self.placemappages or self.familymappages): - fname = CSS["NarrativeMaps"]["filename"] + fname = CSS["NarrativeMaps"]["filename"] self.copy_file(fname, "narrative-maps.css", "css") # Copy the Creative Commons icon if the Creative Commons @@ -7633,7 +7633,7 @@ class NavWebReport(Report): * field 4: date of birth or christening (optional) * field 5: place of birth or christening (optional) * field 6: date of death or burial (optional) - * field 7: place of death or burial (optional) + * field 7: place of death or burial (optional) """ url = self.build_url_fname_html(person.handle, "ppl") surname = person.get_primary_name().get_surname() @@ -7672,7 +7672,7 @@ class NavWebReport(Report): creates the thumbnail preview page """ with self.user.progress(_("Narrated Web Site Report"), - _("Creating thumbnail preview page..."), + _("Creating thumbnail preview page..."), len(self.obj_dict[MediaObject])) as step: ThumbnailPreviewPage(self, self.title, step) @@ -7702,18 +7702,18 @@ class NavWebReport(Report): if add or res or url: primary_name = person.get_primary_name() - sort_name = ''.join([primary_name.get_surname(), ", ", + sort_name = ''.join([primary_name.get_surname(), ", ", primary_name.get_first_name()]) url_addr_res.append( (sort_name, person_handle, add, res, url) ) url_addr_res.sort() AddressBookListPage(self, self.title, url_addr_res) - # begin Address Book pages + # begin Address Book pages addr_size = len(url_addr_res) - + with self.user.progress(_("Narrated Web Site Report"), - _("Creating address book pages ..."), + _("Creating address book pages ..."), addr_size) as step: for (sort_name, person_handle, add, res, url) in url_addr_res: AddressBookPage(self, self.title, person_handle, add, res, url) @@ -7801,12 +7801,12 @@ class NavWebReport(Report): if obj: handle = obj.handle else: - raise AttributeError("gramps_id '%s' not found in '%s'" % + raise AttributeError("gramps_id '%s' not found in '%s'" % handle, obj_class) else: - raise AttributeError("invalid gramps_id lookup " + raise AttributeError("invalid gramps_id lookup " "in table name '%s'" % obj_class) - up = self.link_prefix_up + up = self.link_prefix_up # handle, ppl if obj_class == "Person": if self.person_in_webreport(handle): @@ -7823,7 +7823,7 @@ class NavWebReport(Report): subdir = "img" elif obj_class == "Repository": subdir = "repo" - elif obj_class == "Family": + elif obj_class == "Family": subdir = "fam" else: print ("NarrativeWeb ignoring link type '%s'" % obj_class) @@ -7836,7 +7836,7 @@ class NavWebReport(Report): If the subdirectory is given, then two extra levels of subdirectory are inserted between 'subdir' and the filename. The reason is to prevent directories with too many entries. - If 'up' is True, then "../../../" is inserted in front of the result. + If 'up' is True, then "../../../" is inserted in front of the result. The extension is added to the filename as well. @@ -7981,7 +7981,7 @@ class NavWebOptions(MenuReportOptions): self.__add_report_options(menu) self.__add_page_generation_options(menu) self.__add_privacy_options(menu) - self.__add_download_options(menu) + self.__add_download_options(menu) self.__add_advanced_options(menu) self.__add_place_map_options(menu) @@ -8037,7 +8037,7 @@ class NavWebOptions(MenuReportOptions): if val[0] == defaultnum: default = ind break - name_format = EnumeratedListOption(_("Name format"), + name_format = EnumeratedListOption(_("Name format"), fmt_list[default][0]) for num, name, fmt_str, act in fmt_list: name_format.add_item(num, name) @@ -8057,7 +8057,7 @@ class NavWebOptions(MenuReportOptions): addopt( "cright", cright ) self.__css = EnumeratedListOption(_('StyleSheet'), CSS["default"]["id"]) - for (fname, id) in sorted([(CSS[key]["translation"], CSS[key]["id"]) + for (fname, id) in sorted([(CSS[key]["translation"], CSS[key]["id"]) for key in list(CSS.keys())]): if CSS[id]["user"]: self.__css.add_item(CSS[id]["id"], CSS[id]["translation"]) @@ -8168,13 +8168,13 @@ class NavWebOptions(MenuReportOptions): addopt("create_thumbs_only", self.__create_thumbs_only) self.__create_thumbs_only.connect("value-changed", self.__gallery_changed) - self.__maxinitialimagewidth = NumberOption(_("Max width of initial image"), + self.__maxinitialimagewidth = NumberOption(_("Max width of initial image"), _DEFAULT_MAX_IMG_WIDTH, 0, 2000) self.__maxinitialimagewidth.set_help(_("This allows you to set the maximum width " "of the image shown on the media page. Set to 0 for no limit.")) addopt( "maxinitialimagewidth", self.__maxinitialimagewidth ) - self.__maxinitialimageheight = NumberOption(_("Max height of initial image"), + self.__maxinitialimageheight = NumberOption(_("Max height of initial image"), _DEFAULT_MAX_IMG_HEIGHT, 0, 2000) self.__maxinitialimageheight.set_help(_("This allows you to set the maximum height " "of the image shown on the media page. Set to 0 for no limit.")) @@ -8197,13 +8197,13 @@ class NavWebOptions(MenuReportOptions): self.__living = EnumeratedListOption(_("Living People"), LivingProxyDb.MODE_EXCLUDE_ALL) - self.__living.add_item(LivingProxyDb.MODE_EXCLUDE_ALL, + self.__living.add_item(LivingProxyDb.MODE_EXCLUDE_ALL, _("Exclude")) - self.__living.add_item(LivingProxyDb.MODE_INCLUDE_LAST_NAME_ONLY, + self.__living.add_item(LivingProxyDb.MODE_INCLUDE_LAST_NAME_ONLY, _("Include Last Name Only")) - self.__living.add_item(LivingProxyDb.MODE_INCLUDE_FULL_NAME_ONLY, + self.__living.add_item(LivingProxyDb.MODE_INCLUDE_FULL_NAME_ONLY, _("Include Full Name Only")) - self.__living.add_item(_INCLUDE_LIVING_VALUE, + self.__living.add_item(_INCLUDE_LIVING_VALUE, _("Include")) self.__living.set_help(_("How to handle living people")) addopt( "living", self.__living ) @@ -8407,7 +8407,7 @@ class NavWebOptions(MenuReportOptions): """ css_opts = self.__css.get_value() - if CSS[css_opts]["navigation"]: + if CSS[css_opts]["navigation"]: self.__navigation.set_available(True) else: self.__navigation.set_available(False) @@ -8437,7 +8437,7 @@ class NavWebOptions(MenuReportOptions): self.__maxinitialimagewidth.set_available(False) self.__maxinitialimageheight.set_available(False) - # full- sized images and Media Pages will be created... + # full- sized images and Media Pages will be created... else: self.__maxinitialimagewidth.set_available(True) self.__maxinitialimageheight.set_available(True) @@ -8520,9 +8520,9 @@ def sort_people(dbase, handle_list): sorted_lists = [] temp_list = sorted(sname_sub, key=SORT_KEY) - + for name in temp_list: - slist = sorted(((sortnames[x], x) for x in sname_sub[name]), + slist = sorted(((sortnames[x], x) for x in sname_sub[name]), key=lambda x:SORT_KEY(x[0])) entries = [x[1] for x in slist] sorted_lists.append((name, entries)) @@ -8576,7 +8576,7 @@ def __get_person_keyname(dbase, handle): def __get_place_keyname(dbase, handle): """ ... """ - return ReportUtils.place_name(dbase, handle) + return ReportUtils.place_name(dbase, handle) # See : http://www.gramps-project.org/bugs/view.php?id = 4423 @@ -8686,12 +8686,12 @@ def first_letter(string): """ if string is None or len(string) < 1: return ' ' - + norm_unicode = normalize('NFKC', str(string)) contractions = contractions_dict.get(COLLATE_LANG) if contractions == None: contractions = contractions_dict.get(COLLATE_LANG.split("_")[0]) - + if contractions is not None: for contraction in contractions: count = len(contraction[0][0]) @@ -8706,19 +8706,19 @@ try: import PyICU PRIM_COLL = PyICU.Collator.createInstance(PyICU.Locale(COLLATE_LANG)) PRIM_COLL.setStrength(PRIM_COLL.PRIMARY) - + def primary_difference(prev_key, new_key): return PRIM_COLL.compare(prev_key, new_key) != 0 - + except: def primary_difference(prev_key, new_key): # Returns true if there is a primary difference between the two parameters. # See http://www.gramps-project.org/bugs/view.php?id=2933#c9317 if # letter[i]+'a' < letter[i+1]+'b' and letter[i+1]+'a' < letter[i]+'b' is # true then the letters should be grouped together - + # The test characters here must not be any that are used in contractions. - + return SORT_KEY(prev_key + "e") >= SORT_KEY(new_key + "f") or\ SORT_KEY(new_key + "e") >= SORT_KEY(prev_key + "f") @@ -8726,10 +8726,10 @@ def get_first_letters(dbase, handle_list, key): """ get the first letters of the handle_list - @param: handle_list = one of a handle list for either person or place handles + @param: handle_list = one of a handle list for either person or place handles or an evt types list @param: key = either a person, place, or event type - + The first letter (or letters if there is a contraction) are extracted from all the objects in the handle list. There may be duplicates, and there may be letters where there is only a secondary or tertiary difference, not a @@ -8742,7 +8742,7 @@ def get_first_letters(dbase, handle_list, key): letters are extracted (Å and A). These are sorted, which gives A and Å. Then the first of these is used for the index entry. """ - + index_list = [] for handle in handle_list: @@ -8767,7 +8767,7 @@ def get_first_letters(dbase, handle_list, key): prev_index = key else: index_list.remove(key) - + # return menu set letters for alphabet_navigation return index_list @@ -8781,7 +8781,7 @@ def get_index_letter(letter, index_list): for index in index_list: if not primary_difference(letter, index): return index - + log.warning("Initial letter '%s' not found in alphabetic navigation list" % letter) log.debug("filtered sorted index list %s" % index_list) @@ -8815,7 +8815,7 @@ def alphabet_navigation(index_list): index = 0 for row in range(num_of_rows): - unordered = Html("ul") + unordered = Html("ul") cols = 0 while (cols <= num_of_cols and index < num_ltrs): @@ -8832,7 +8832,7 @@ def alphabet_navigation(index_list): num_of_rows -= 1 alphabetnavigation += unordered - + return alphabetnavigation def _has_webpage_extension(url): @@ -8841,7 +8841,7 @@ def _has_webpage_extension(url): url = filename to be checked """ - return any(url.endswith(ext) for ext in _WEB_EXT) + return any(url.endswith(ext) for ext in _WEB_EXT) def add_birthdate(dbase, ppl_handle_list): """ @@ -8899,7 +8899,7 @@ def _find_death_date(dbase, individual): date_out.fallback = False else: person_evt_ref_list = individual.get_primary_event_ref_list() - if person_evt_ref_list: + if person_evt_ref_list: for evt_ref in person_evt_ref_list: event = dbase.get_event_from_handle(evt_ref.ref) if event: @@ -8940,9 +8940,9 @@ def build_event_data_by_individuals(dbase, ppl_handle_list): if family_evt_ref_list: for evt_ref in family_evt_ref_list: event = dbase.get_event_from_handle(evt_ref.ref) - if event: + if event: event_types.append(str(event.type)) event_handle_list.append(evt_ref.ref) - + # return event_handle_list and event types to its caller return event_handle_list, event_types diff --git a/gramps/plugins/webreport/webcal.py b/gramps/plugins/webreport/webcal.py index c1ee55938..974417d80 100644 --- a/gramps/plugins/webreport/webcal.py +++ b/gramps/plugins/webreport/webcal.py @@ -14,7 +14,7 @@ # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # -# This program is distributed in the hope that it will be useful, +# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. @@ -139,7 +139,7 @@ class WebCalReport(Report): self.home_link = mgobn('home_link') self.month_notes = [mgobn('note_' + month) - for month in ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', + for month in ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']] self.encoding = mgobn('encoding') @@ -172,13 +172,13 @@ class WebCalReport(Report): def get_note_format(self, note): """ - will get the note from the database, and will return either the - styled text or plain note + will get the note from the database, and will return either the + styled text or plain note """ # retrieve the body of the note note_text = note.get() - + # styled notes htmlnotetext = self.styled_note(note.get_styledtext(), note.get_format()) @@ -264,7 +264,7 @@ class WebCalReport(Report): adds birthdays, anniversaries, and holidays to their perspective lists text -- line to be added - year, month, day -- date to add the text to + year, month, day -- date to add the text to event -- one of 'BirthDay', 'Anniversary', or 'Holiday' """ @@ -311,7 +311,7 @@ class WebCalReport(Report): holiday_table.load_holidays(year, country) for month in range(1, 13): for day in range(1, 32): - holiday_names = holiday_table.get_holidays(month, day) + holiday_names = holiday_table.get_holidays(month, day) for holiday_name in holiday_names: self.add_day_item(holiday_name, year, month, day, 'Holiday') step() @@ -432,7 +432,7 @@ class WebCalReport(Report): # add horizontal menu if css == Blue or Visually because there is no menus? if CSS[self.css]["navigation"]: fname = "/".join(subdirs + ["css", "calendar-menus.css"]) - links.extend( + links.extend( Html("link", href = fname, type = "text/css", media = "screen", rel = "stylesheet", indent = False) ) @@ -452,7 +452,7 @@ class WebCalReport(Report): # Created for ? msg = None - if self.author and self.email: + if self.author and self.email: msg = _('the "WebCal" will be the potential-email Subject|' 'Created for %(html_email_author_start)s' 'WebCal%(html_email_author_end)s') % { @@ -466,7 +466,7 @@ class WebCalReport(Report): if msg: header += Html("p", msg, id = "CreatorInfo") - body += header + body += header return page, body def year_navigation(self, nr_up, currentsection): @@ -496,7 +496,7 @@ class WebCalReport(Report): # this will always need an extension added full_month_name = date_displayer.long_months[self.today.get_month() ] - # Note. We use '/' here because it is a URL, not a OS dependent + # Note. We use '/' here because it is a URL, not a OS dependent # pathname. url = '/'.join(subdirs + [full_month_name]) + self.ext hyper = Html("a", str(cal_year), href = url, title = str(cal_year)) @@ -522,7 +522,7 @@ class WebCalReport(Report): nr_up = number of directories up to reach root directory year = year being created currentsection = month name being created for proper CSS styling - use_home = if creating a link to home + use_home = if creating a link to home -- a link to root directory of website """ navs = [] @@ -555,11 +555,11 @@ class WebCalReport(Report): if not (url.startswith('http:') or url.startswith('/')): add_subdirs = not any(url.endswith(ext) for ext in _WEB_EXT) - + # whether to add subdirs or not??? - if add_subdirs: + if add_subdirs: subdirs = ['..'] * nr_up - subdirs.append(str(year)) + subdirs.append(str(year)) url = '/'.join(subdirs + [url_fname]) if not _has_webpage_extension(url): @@ -637,7 +637,7 @@ class WebCalReport(Report): # day_col is based on range(0 - 6) return previous_month_day - def __get_next_month_day(year, month, day_col): + def __get_next_month_day(year, month, day_col): if month == 12: nextmonth = calendar.monthcalendar((year + 1), 1) @@ -650,7 +650,7 @@ class WebCalReport(Report): # day_col is based on range(0 - 6) return next_month_day - # Begin calendar head. We'll use the capitalized name, because here it + # Begin calendar head. We'll use the capitalized name, because here it # seems appropriate for most countries. month_name = full_month_name.capitalize() th_txt = month_name @@ -661,17 +661,17 @@ class WebCalReport(Report): # begin calendar table and table head with Html("table", class_ = "calendar", id = month_name, role = "Calendar-Grid") as table: thead = Html("thead") - table += thead + table += thead trow = Html("tr") + ( Html("th", th_txt, class_ ='monthName', colspan=7, inline = True) ) - thead += trow + thead += trow # Calendar weekday names header trow = Html("tr") thead += trow - + for day_col in range(7): dayclass = get_class_for_daycol(day_col) dayname = get_name_for_daycol(day_col) @@ -682,10 +682,10 @@ class WebCalReport(Report): tbody = Html("tbody") table += tbody - # get first of the month and month information + # get first of the month and month information current_date, current_ord, monthinfo = get_first_day_of_month(year, month) - # begin calendar table rows, starting week0 + # begin calendar table rows, starting week0 nweeks = len(monthinfo) for week_row in range(0, nweeks): week = monthinfo[week_row] @@ -698,7 +698,7 @@ class WebCalReport(Report): for day_col in range(0, 7): dayclass = get_class_for_daycol(day_col) - # day number, can also be a zero -- a day before or after month + # day number, can also be a zero -- a day before or after month day = week[day_col] # start the beginning variable for , table cell @@ -712,7 +712,7 @@ class WebCalReport(Report): # day in previous/ next month specday = __get_previous_month_day(year, month, day_col) if week_row == 0 \ - else __get_next_month_day(year, month, day_col) + else __get_next_month_day(year, month, day_col) specclass = "previous " if week_row == 0 else "next " specclass += dayclass @@ -722,7 +722,7 @@ class WebCalReport(Report): Html("div", specday, class_ = "date", inline = True) ) # normal day number in current month - else: + else: thisday = datetime.date.fromordinal(current_ord) # Something this month @@ -734,10 +734,10 @@ class WebCalReport(Report): event_date = Date(thisday.year, thisday.month, thisday.day) # get events for this day - day_list = get_day_list(event_date, holiday_list, bday_anniv_list) + day_list = get_day_list(event_date, holiday_list, bday_anniv_list) # is there something this day? - if day_list: + if day_list: hilightday = 'highlight ' + dayclass tcell = Html("td", id = tcell_id, class_ = hilightday) @@ -745,17 +745,17 @@ class WebCalReport(Report): # Year at a Glance if cal == "yg": - # make one day pages and hyperlink - if self.makeoneday: + # make one day pages and hyperlink + if self.makeoneday: - # create yyyymmdd date string for + # create yyyymmdd date string for # "One Day" calendar page filename fname_date = '%04d%02d%02d' % (year,month,day) + self.ext # create hyperlink to one_day() tcell += Html("a", datediv, href = fname_date, inline = True) - # only year_glance() needs this to create the one_day() pages + # only year_glance() needs this to create the one_day() pages self.one_day(event_date, fname_date, day_list) # just year_glance(), but no one_day() pages @@ -766,31 +766,31 @@ class WebCalReport(Report): # adds date division Html("div", day, class_ = "date", inline = True) - ) + ) # WebCal else: # add date to table cell - tcell += datediv + tcell += datediv # list the events unordered = Html("ul") tcell += unordered for nyears, date, text, event in day_list: - unordered += Html("li", text, inline = False + unordered += Html("li", text, inline = False if event == 'Anniversary' else True) # no events for this day - else: + else: - # create empty day with date + # create empty day with date tcell = Html("td", class_ = dayclass, inline = True) + ( # adds date division Html("div", day, class_ = "date", inline = True) - ) + ) # nothing for this month else: @@ -798,7 +798,7 @@ class WebCalReport(Report): # adds date division Html("div", day, class_ = "date", inline = True) - ) + ) # attach table cell to table row # close the day column @@ -867,13 +867,13 @@ class WebCalReport(Report): note = self.database.get_note_from_gramps_id(note) note = self.get_note_format(note) - # table foot section + # table foot section cal_foot = Html("tfoot") monthly_calendar += cal_foot trow = Html("tr") + ( Html("td", note, colspan=7, inline = True) - ) + ) cal_foot += trow # create blank line for stylesheets @@ -921,7 +921,7 @@ class WebCalReport(Report): 'on a date will take you to a page that shows all the events for ' 'that date, if there are any.\n')) - # page description + # page description content = Html("div", class_ = "content", id = "YearGlance") body += content @@ -931,7 +931,7 @@ class WebCalReport(Report): # build the calendar monthly_calendar = self.calendar_build("yg", year, month) - content += monthly_calendar + content += monthly_calendar # increase progress bar step() @@ -981,14 +981,14 @@ class WebCalReport(Report): currentsection = date_displayer.long_months[month] body += self.month_navigation(nr_up, year, currentsection, True) - # set date display as in user prevferences + # set date display as in user prevferences content = Html("div", class_="content", id = "OneDay") body += content content += Html("h3", date_displayer.display(event_date), inline = True) # list the events ordered = Html("ol") - content += ordered + content += ordered for nyears, date, text, event in day_list: ordered += Html("li", text, inline = False if event == 'Anniversary' else True) @@ -998,7 +998,7 @@ class WebCalReport(Report): body += (fullclear, footer) # send calendar page to web output - # and close the file + # and close the file self.XHTMLWriter(oneday, od) def build_url_fname_html(self, fname, subdir=None, prefix=None): @@ -1010,7 +1010,7 @@ class WebCalReport(Report): If the subdirectory is given, then two extra levels of subdirectory are inserted between 'subdir' and the filename. The reason is to prevent directories with too many entries. - If 'prefix' is set, then is inserted in front of the result. + If 'prefix' is set, then is inserted in front of the result. The extension is added to the filename as well. @@ -1039,9 +1039,9 @@ class WebCalReport(Report): return subdirs def get_name(self, person, maiden_name = None): - """ - Return person's name, unless maiden_name given, unless married_name - listed. + """ + Return person's name, unless maiden_name given, unless married_name + listed. person -- person to get short name from maiden_name -- either a woman's maiden name or man's surname @@ -1077,7 +1077,7 @@ class WebCalReport(Report): people = db.iter_person_handles() with self._user.progress(_("Web Calendar Report"), - _('Applying Filter...'), + _('Applying Filter...'), db.get_number_of_people()) as step: people = self.filter.apply(db, people, step) @@ -1102,7 +1102,7 @@ class WebCalReport(Report): day = birth_date.get_day() # date to figure if someone is still alive - # current year of calendar, month nd day is their birth month and birth day + # current year of calendar, month nd day is their birth month and birth day prob_alive_date = Date(this_year, month, day) # add some things to handle maiden name: @@ -1110,7 +1110,7 @@ class WebCalReport(Report): if person.gender == Person.FEMALE: # get husband's last name: - if self.maiden_name in ['spouse_first', 'spouse_last']: + if self.maiden_name in ['spouse_first', 'spouse_last']: if family_list: if self.maiden_name == 'spouse_first': fhandle = family_list[0] @@ -1123,7 +1123,7 @@ class WebCalReport(Report): if father_handle: father = db.get_person_from_handle(father_handle) if father is not None: - father_surname = _get_regular_surname(person.gender, + father_surname = _get_regular_surname(person.gender, father.get_primary_name()) short_name = self.get_name(person, father_surname) alive = probably_alive(person, db, prob_alive_date) @@ -1131,8 +1131,8 @@ class WebCalReport(Report): # add link to NarrativeWeb if self.link_to_narweb: - text = str(Html("a", short_name, - href = self.build_url_fname_html(person.handle, "ppl", + text = str(Html("a", short_name, + href = self.build_url_fname_html(person.handle, "ppl", prefix = self.narweb_prefix))) else: text = short_name @@ -1154,7 +1154,7 @@ class WebCalReport(Report): spouse_name = self.get_name(spouse) short_name = self.get_name(person) - # will return a marriage event or False if not married any longer + # will return a marriage event or False if not married any longer marriage_event = get_marriage_event(db, fam) if marriage_event: event_date = marriage_event.get_date_object() @@ -1169,12 +1169,12 @@ class WebCalReport(Report): if self.link_to_narweb: spouse_name = str(Html("a", spouse_name, - href = self.build_url_fname_html(spouse_handle, 'ppl', + href = self.build_url_fname_html(spouse_handle, 'ppl', prefix = self.narweb_prefix))) short_name = str(Html("a", short_name, - href = self.build_url_fname_html(person.handle, 'ppl', + href = self.build_url_fname_html(person.handle, 'ppl', prefix = self.narweb_prefix))) - + alive1 = probably_alive(person, db, prob_alive_date) alive2 = probably_alive(spouse, db, prob_alive_date) if ((self.alive and alive1 and alive2) or not self.alive): @@ -1184,7 +1184,7 @@ class WebCalReport(Report): 'person' : short_name} self.add_day_item(text, year, month, day, 'Anniversary') - + def write_footer(self, nr_up): """ Writes the footer section of the pages @@ -1217,7 +1217,7 @@ class WebCalReport(Report): else: text = "© %s %s" % (self.today.get_year(), self.author) - footer += Html("p", text, id = 'copyright') + footer += Html("p", text, id = 'copyright') # return footer to its callers return footer @@ -1237,7 +1237,7 @@ class WebCalReport(Report): def write_report(self): """ - The short method that runs through each month and creates a page. + The short method that runs through each month and creates a page. """ # get data from database for birthdays/ anniversaries self.collect_data(self.start_year) @@ -1263,7 +1263,7 @@ class WebCalReport(Report): # create webcalendar() calendar pages self.webcalendar(cal_year) - # create "Year At A Glance" and + # create "Year At A Glance" and # "One Day" calendar pages if self.fullyear: self.year_glance(cal_year) @@ -1273,7 +1273,7 @@ class WebCalReport(Report): cal_year = self.start_year self.holidays = {} - + # get the information, first from holidays: if self.country != 0: self.__get_holidays(cal_year) @@ -1281,7 +1281,7 @@ class WebCalReport(Report): # create webcalendar() calendar pages self.webcalendar(cal_year) - # create "Year At A Glance" and + # create "Year At A Glance" and # "One Day" calendar pages if self.fullyear: self.year_glance(cal_year) @@ -1352,7 +1352,7 @@ class WebCalOptions(MenuReportOptions): if val[0] == defaultnum: default = ind break - name_format = EnumeratedListOption(_("Name format"), + name_format = EnumeratedListOption(_("Name format"), fmt_list[default][0]) for num, name, fmt_str, act in fmt_list: name_format.add_item(num, name) @@ -1377,11 +1377,11 @@ class WebCalOptions(MenuReportOptions): cright.set_help( _("The copyright to be used for the web files")) menu.add_option(category_name, "cright", cright) - css_list = sorted([(CSS[key]["translation"], CSS[key]["id"]) + css_list = sorted([(CSS[key]["translation"], CSS[key]["id"]) for key in list(CSS.keys()) if CSS[key]["user"]]) css = EnumeratedListOption(_('StyleSheet'), css_list[0][1]) - for css_item in css_list: + for css_item in css_list: css.add_item(css_item[1], css_item[0]) css.set_help( _('The stylesheet to be used for the web pages')) menu.add_option(category_name, "css", css) @@ -1398,7 +1398,7 @@ class WebCalOptions(MenuReportOptions): self.__multiyear = BooleanOption(_('Create multiple year calendars'), False) self.__multiyear.set_help(_('Whether to create Multiple year calendars or not.')) menu.add_option(category_name, 'multiyear', self.__multiyear) - self.__multiyear.connect('value-changed', self.__multiyear_changed) + self.__multiyear.connect('value-changed', self.__multiyear_changed) self.__start_year = NumberOption(_('Start Year for the Calendar(s)'), today.get_year(), 1900, 3000) @@ -1418,7 +1418,7 @@ class WebCalOptions(MenuReportOptions): holiday_table = libholiday.HolidayTable() countries = holiday_table.get_countries() countries.sort() - if (len(countries) == 0 or + if (len(countries) == 0 or (len(countries) > 0 and countries[0] != '')): countries.insert(0, '') count = 0 @@ -1433,7 +1433,7 @@ class WebCalOptions(MenuReportOptions): start_dow = EnumeratedListOption(_("First day of week"), 1) for count in range(1, 8): start_dow.add_item(count, - date_displayer.long_days[count].capitalize()) + date_displayer.long_days[count].capitalize()) start_dow.set_help(_("Select the first day of the week for the calendar")) menu.add_option(category_name, "start_dow", start_dow) @@ -1538,11 +1538,11 @@ class WebCalOptions(MenuReportOptions): makeoneday = BooleanOption(_('Create one day event pages for' ' Year At A Glance calendar'), False) makeoneday.set_help(_('Whether to create one day pages or not')) - menu.add_option(category_name, 'makeoneday', makeoneday) + menu.add_option(category_name, 'makeoneday', makeoneday) self.__links = BooleanOption(_('Link to Narrated Web Report'), False) self.__links.set_help(_('Whether to link data to web report or not')) - menu.add_option(category_name, 'link_to_narweb', self.__links) + menu.add_option(category_name, 'link_to_narweb', self.__links) self.__links.connect('value-changed', self.__links_changed) dbname = self.__db.get_dbname() @@ -1589,7 +1589,7 @@ class WebCalOptions(MenuReportOptions): def __links_changed(self): """ - Handle checkbox change. + Handle checkbox change. """ if self.__links.get_value(): self.__prefix.set_available(True) @@ -1606,7 +1606,7 @@ def _get_regular_surname(sex, name): surname = surname + ", " + suffix return surname -# Simple utility list to convert Gramps day-of-week numbering +# Simple utility list to convert Gramps day-of-week numbering # to calendar.firstweekday numbering dow_gramps2iso = [ -1, calendar.SUNDAY, calendar.MONDAY, calendar.TUESDAY, calendar.WEDNESDAY, calendar.THURSDAY, calendar.FRIDAY, @@ -1638,8 +1638,8 @@ def get_first_day_of_month(year, month): # first day of the month current_date = datetime.date(year, month, 1) - # monthinfo is filled using standard Python library - # calendar.monthcalendar. It fills a list of 7-day-lists. The first day + # monthinfo is filled using standard Python library + # calendar.monthcalendar. It fills a list of 7-day-lists. The first day # of the 7-day-list is determined by calendar.firstweekday. monthinfo = calendar.monthcalendar(year, month) @@ -1659,14 +1659,14 @@ def get_day_list(event_date, holiday_list, bday_anniv_list): Will fill day_list and return it to its caller: calendar_build() holiday_list -- list of holidays for event_date - bday_anniv_list -- list of birthdays and anniversaries + bday_anniv_list -- list of birthdays and anniversaries for event_date - event_date -- date for this day_list + event_date -- date for this day_list - 'day_list' - a combination of both dictionaries to be able - to create one day nyears, date, text, event --- are - necessary for figuring the age or years married for + 'day_list' - a combination of both dictionaries to be able + to create one day nyears, date, text, event --- are + necessary for figuring the age or years married for each day being created... """ @@ -1706,7 +1706,7 @@ def get_day_list(event_date, holiday_list, bday_anniv_list): txt_str = (text + ', ' # TRANSLATORS: expands to smth like "12 years old", # where "12 years" is already localized to your language - + (_('%s old') % str(age_str) + + (_('%s old') % str(age_str) if nyears else _('birth')) + '') @@ -1716,7 +1716,7 @@ def get_day_list(event_date, holiday_list, bday_anniv_list): if nyears == 0: txt_str = _('%(couple)s, wedding') % { 'couple' : text} - else: + else: years_str = '%s' % nyears # translators: leave all/any {...} untranslated txt_str = ngettext("{couple}, {years} year anniversary", @@ -1729,6 +1729,6 @@ def get_day_list(event_date, holiday_list, bday_anniv_list): # sort them based on number of years # holidays will always be on top of event list day_list= sorted(day_list, key=lambda x: (isinstance(x[0], str), x[0])) - + # return to its caller calendar_build() return day_list diff --git a/gramps/plugins/webreport/webplugins.gpr.py b/gramps/plugins/webreport/webplugins.gpr.py index 37ea84847..89c0d5a83 100644 --- a/gramps/plugins/webreport/webplugins.gpr.py +++ b/gramps/plugins/webreport/webplugins.gpr.py @@ -18,7 +18,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # diff --git a/gramps/plugins/webstuff/webstuff.gpr.py b/gramps/plugins/webstuff/webstuff.gpr.py index 60b5811e4..982987512 100644 --- a/gramps/plugins/webstuff/webstuff.gpr.py +++ b/gramps/plugins/webstuff/webstuff.gpr.py @@ -21,14 +21,14 @@ # plugins/webstuff/webstuff.gpr.py -MODULE_VERSION="5.0" +MODULE_VERSION="5.0" #------------------------------------------------------------------------ # # Stylesheets # #------------------------------------------------------------------------ -register(GENERAL, +register(GENERAL, id = 'system webstuff', category = "WEBSTUFF", name = _("Webstuff"), diff --git a/gramps/plugins/webstuff/webstuff.py b/gramps/plugins/webstuff/webstuff.py index b8dbcd2ba..37e384b66 100644 --- a/gramps/plugins/webstuff/webstuff.py +++ b/gramps/plugins/webstuff/webstuff.py @@ -82,10 +82,10 @@ def load_on_reg(dbstate, uistate, plugin): # Mainz style sheet with its images ["Mainz", 1, _("Mainz"), - path_css('Web_Mainz.css'), None, - [path_img("Web_Mainz_Bkgd.png"), - path_img("Web_Mainz_Header.png"), - path_img("Web_Mainz_Mid.png"), + path_css('Web_Mainz.css'), None, + [path_img("Web_Mainz_Bkgd.png"), + path_img("Web_Mainz_Header.png"), + path_img("Web_Mainz_Mid.png"), path_img("Web_Mainz_MidLight.png")], [] ], # Nebraska style sheet @@ -104,7 +104,7 @@ def load_on_reg(dbstate, uistate, plugin): # media reference regions style sheet ["behaviour", 0, "Behaviour", - path_css('behaviour.css'), None, [], [] ], + path_css('behaviour.css'), None, [], [] ], # NarrativeMap stylesheet/ image for NarrativeWeb place maps ["NarrativeMaps", 0, "", diff --git a/gramps/test/__init__.py b/gramps/test/__init__.py index 0f861e217..b205514db 100644 --- a/gramps/test/__init__.py +++ b/gramps/test/__init__.py @@ -27,18 +27,18 @@ It includes a test-running program regrtest.py, Also includes tests for code in the parent (src) directory and other tests that may be considered top-level tests - + Note: tests for utility code in this directory would be in a subdirectory also named test by convention for gramps testing. -Note: test subdirectories do not normally need to have a -package-enabling module __init__.py, but this one (src/test) does +Note: test subdirectories do not normally need to have a +package-enabling module __init__.py, but this one (src/test) does because it contains utilities used by other test modules. Thus, this package would allow test code like from test import test_util """ -# This file does not presently contain any code. +# This file does not presently contain any code. -#===eof=== +#===eof=== diff --git a/gramps/test/regrtest.py b/gramps/test/regrtest.py index 96e06b673..5b112a802 100755 --- a/gramps/test/regrtest.py +++ b/gramps/test/regrtest.py @@ -19,7 +19,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # test/regrtest.py -# Original: RunAllTests.py Written by Richard Taylor +# Original: RunAllTests.py Written by Richard Taylor # (jgs: revised for embedded "test" subdirs as regrtest.py ) """ @@ -29,7 +29,7 @@ Testing framework for performing a variety of unttests for GRAMPS. # TODO: review whether logging is really useful for unittest # it does seem to work .. try -v5 import logging - + import os import sys import unittest @@ -41,12 +41,12 @@ gramps_root=tu.path_append_parent() def make_parser(): usage = "usage: %prog [options]" parser = OptionParser(usage) - parser.add_option("-v", "--verbosity", type="int", + parser.add_option("-v", "--verbosity", type="int", dest="verbose_level", default=0, - help="Level of verboseness") - parser.add_option("-p", "--performance", action="store_true", + help="Level of verboseness") + parser.add_option("-p", "--performance", action="store_true", dest="performance", default=False, - help="Run the performance tests.") + help="Run the performance tests.") return parser @@ -79,7 +79,7 @@ def getTestSuites(loc=gramps_root): perf_suites = [] # note that test_mod and match_mod modify passed-in lists paths = [(path,files) for path,dirs,files in os.walk(loc) - if test_mod(path,dirs) and match_mod(files)] + if test_mod(path,dirs) and match_mod(files)] ## NO -- see explanation below ## oldpath = list(sys.path) @@ -98,7 +98,7 @@ def getTestSuites(loc=gramps_root): perf_suites.append(mod.perfSuite()) except: pass - # NO: was: remove temporary paths added + # NO: was: remove temporary paths added # this seems like it should be reasonable, # but it causes failure in _GrampsDbWRFactories_test.py # (I suspect it is an actual bug in the runner @@ -110,7 +110,7 @@ def getTestSuites(loc=gramps_root): ## sys.path = list(oldpath) return (test_suites,perf_suites) - + if __name__ == '__main__': def logging_init(): global logger @@ -122,7 +122,7 @@ if __name__ == '__main__': logger = logging.getLogger('Gramps') logger.addHandler(console) return console, logger - + def logging_adjust(verbose_level): if verbose_level == 1: logger.setLevel(logging.INFO) @@ -140,7 +140,7 @@ if __name__ == '__main__': else: logger.setLevel(logging.ERROR) console.setLevel(logging.ERROR) - + console,logger = logging_init() options,args = make_parser().parse_args() logging_adjust(options.verbose_level) @@ -159,7 +159,7 @@ if __name__ == '__main__': suite = unittest.TestSuite(ptests) else: suite = unittest.TestSuite(utests) - + unittest.TextTestRunner(verbosity=options.verbose_level).run(suite) #===eof=== diff --git a/gramps/test/test/test_util_test.py b/gramps/test/test/test_util_test.py index 0005a28cb..760df928c 100644 --- a/gramps/test/test/test_util_test.py +++ b/gramps/test/test/test_util_test.py @@ -33,7 +33,7 @@ usage_note=""" Testing (and runing) Gramps requires that PYTHONPATH include the path to the top Gramps directory (where gramps.py resides). - For example, in bash, a shell export would look like + For example, in bash, a shell export would look like export PYTHONPATH=/.../src with the ... filled in appropriately. ************************************************************** @@ -45,8 +45,8 @@ usage_note=""" # strongly advised to test this module to 100% coverage, # and in all calling variations, eg: # run directly, from this dir with and without ./ prefix -# run from other dirs (with path prefix) -# run from within regrtest.py +# run from other dirs (with path prefix) +# run from within regrtest.py # run from regrtest.py with other test modules present # which use the test_util module itself # @@ -57,16 +57,16 @@ try: ##here = tu.absdir() except ImportError: print("Cannot import 'test_util' from package 'test'" + usage_note) - exit(1) + exit(1) # grouping into multiple TestCases (classes) is not required, -# but may be useful for various reasons, such as collecting -# tests that share a setUp/tearDown mechanism or that share +# but may be useful for various reasons, such as collecting +# tests that share a setUp/tearDown mechanism or that share # some test data, or just because they're related. # # The test function name should not have docstrings, but should -# have names which add to the value of failure reporting, and +# have names which add to the value of failure reporting, and # which make it easy to find them within the source. @@ -98,12 +98,12 @@ class Test2(U.TestCase): e = os.path.basename(__file__).rstrip(".co") # eg in *.py[co] g = os.path.basename(tu._caller_context()[0]).rstrip('co') self.assertEqual(g,e, tu.msg(g,e, "_caller_context")) - + def test2b_absdir(self): here = tu.absdir(); g=tu.absdir(__file__) self.assertEqual(g, here, tu.msg(g, here, "absdir")) - + def test2c_path_append_parent(self): here = tu.absdir(); par = os.path.dirname(here) @@ -112,7 +112,7 @@ class Test2(U.TestCase): while par in sys.path: sys.path.remove(par) np = len(sys.path) - + for p in (None, __file__): self.assertFalse(par in sys.path, "par not in initial path") if not p: @@ -141,7 +141,7 @@ class Test3(U.TestCase): for sub in self.asubs: if os.path.isdir(sub): shutil.rmtree(sub) - + def setUp(self): self._rmsubs() if self.home and not os.path.isdir(self.home_junk): @@ -158,7 +158,7 @@ class Test3(U.TestCase): b,d = os.path.dirname(sub), os.path.basename(sub) md = tu.make_subdir(d, b) self.assertTrue(os.path.isdir(sub), "made dir %r" % sub) - self.assertEqual(md,sub, tu.msg(md,sub, + self.assertEqual(md,sub, tu.msg(md,sub, "make_subdir returns path")) s2 = os.path.join(sub,"sub2") @@ -169,7 +169,7 @@ class Test3(U.TestCase): open(f,"w").write("testing..") self.assertTrue(os.path.isfile(f), "file %r exists" % f) tu.delete_tree(sub) - self.assertFalse(os.path.isdir(sub), + self.assertFalse(os.path.isdir(sub), "delete_tree removes subdir %r" % sub ) def test3b_delete_tree_constraint(self): @@ -179,7 +179,7 @@ class Test3(U.TestCase): tu.delete_tree(self.home_junk) except tu.TestError as e: err = e.value - self.assertFalse(err is None, + self.assertFalse(err is None, "deltree on %r raises TestError" % (self.home_junk)) else: self.fail("Skip deltree constraint test, no '$HOME' var") @@ -202,7 +202,7 @@ class Test4(U.TestCase): logging.error(emsg) ll = tl.logfile_getlines() nl = len(ll) - self.assertEquals(nl,3, + self.assertEquals(nl,3, tu.msg(nl,3, "pass %d: expected line count" % i)) #del tl diff --git a/gramps/test/test_util.py b/gramps/test/test_util.py index 8679c3399..2cfd63c4b 100644 --- a/gramps/test/test_util.py +++ b/gramps/test/test_util.py @@ -32,17 +32,17 @@ import logging # _caller_context is primarily here to support and document the process # of determining the test-module's directory. -# +# # NB: the traceback 0-element is 'limit'-levels back, or earliest calling # context if that is less than limit. # The -1 element is this very function; -2 is its caller, etc. -# A traceback context tuple is: +# A traceback context tuple is: # (file, line, active function, text of the call-line) def _caller_context(): """Return context of first caller outside this module""" lim = 5 # 1 for this function, plus futrher chain within this module st = traceback.extract_stack(limit=lim) - thisfile = __file__.rstrip("co") # eg, in ".py[co] + thisfile = __file__.rstrip("co") # eg, in ".py[co] while st and st[-1][0] == thisfile: del(st[-1]) if not st: @@ -60,7 +60,7 @@ def _caller_dir(): class TestError(Exception): """Exception for use by test modules - + Use this, for example, to distuinguish testing errors. """ @@ -76,7 +76,7 @@ def msg(got, exp, msg, pfx=""): This improves unittest failure messages by showing data values Usage: assertEqual(got,exp, msg(got,exp,"mess" [,prefix]) - The failure message will show as + The failure message will show as [prefix: ] mess .....got:repr(value-of-got) expected:repr(value-of-exp) @@ -89,12 +89,12 @@ def msg(got, exp, msg, pfx=""): def absdir(path=None): """Return absolute dir of the specified path - + The path parm may be dir or file or missing. If a file, the dir of the file is used. If missing, the dir of test-module caller is used - Common usage is + Common usage is here = absdir() here = absdir(__file__) These 2 return the same result @@ -113,7 +113,7 @@ def path_append_parent(path=None): and return the abspath to the parent as a possible convenience The path parm may be a dir or a file or missing. - If a file, the dir of the file is used. + If a file, the dir of the file is used. If missing the test-module caller's dir is used. And then the parent of that dir is appended (if not already present) @@ -131,7 +131,7 @@ def path_append_parent(path=None): def make_subdir(dir, parent=None): """Make (if required) a subdir to a given parent and return its path - + The parent parm may be dir or file or missing If a file, the dir of the file us used If missing, the test-module caller's dir is used @@ -147,7 +147,7 @@ def make_subdir(dir, parent=None): def delete_tree(dir): """Recursively delete directory and content - + WARNING: this is clearly dangerous it will only operate on subdirs of the test module dir or of /tmp @@ -160,7 +160,7 @@ def delete_tree(dir): here = _caller_dir() + os.path.sep tmp = tempfile.gettempdir() + os.path.sep if not (sdir.startswith(here) or sdir.startswith(tmp)): - raise TestError("%r is not a subdir of here (%r) or %r" + raise TestError("%r is not a subdir of here (%r) or %r" % (dir, here, tmp)) shutil.rmtree(sdir) @@ -170,7 +170,7 @@ def delete_tree(dir): # I don't see any need to inherit from logging.Logger # (at present, test code needs nothing fancy) # but that might be considered for future needs -# NB: current code reflects limited expertise on the +# NB: current code reflects limited expertise on the # uses of the logging module # --------------------------------------------------------- class TestLogger(): @@ -179,7 +179,7 @@ class TestLogger(): provides simplified logging setup for test modules that need to setup logging for modules under test - (just instantiate a TestLogger to avoid error + (just instantiate a TestLogger to avoid error messages about logging handlers not available) There is also a simple logfile capability, to allow @@ -190,7 +190,7 @@ class TestLogger(): """ def __init__(self, lvl=logging.WARN): logging.basicConfig(level=lvl) - + def logfile_init(self, lfname): """init or re-init a logfile""" if getattr(self, "lfh", None): @@ -200,12 +200,12 @@ class TestLogger(): self.lfh = logging.FileHandler(lfname) logging.getLogger().addHandler(self.lfh) self.lfname = lfname - + def logfile_getlines(self): """get current content of logfile as list of lines""" txt = [] if self.lfname and os.path.isfile(self.lfname): - txt = open(self.lfname).readlines() + txt = open(self.lfname).readlines() return txt #===eof=== diff --git a/gramps/webapp/client.py b/gramps/webapp/client.py index 0a573079f..35850965e 100644 --- a/gramps/webapp/client.py +++ b/gramps/webapp/client.py @@ -44,4 +44,4 @@ def login(base_address, username=None, password=None): return None LOG.info('\t%s is logged in' % username) # save the cookies/opener for further actions - return opener + return opener diff --git a/gramps/webapp/connection.py b/gramps/webapp/connection.py index bf2074b80..c93427f50 100644 --- a/gramps/webapp/connection.py +++ b/gramps/webapp/connection.py @@ -35,8 +35,8 @@ class Connection(object): self.token = [x.value for x in cookies.cookiejar if x.name == 'csrftoken'][0] except IndexError: return Exception("no csrftoken") - params = dict(username=username, - password=password, + params = dict(username=username, + password=password, next="/", csrfmiddlewaretoken=self.token, ) diff --git a/gramps/webapp/default_settings.py b/gramps/webapp/default_settings.py index ceaf84bbf..6733c3ab8 100644 --- a/gramps/webapp/default_settings.py +++ b/gramps/webapp/default_settings.py @@ -44,12 +44,12 @@ DATABASES = { 'NAME': os.path.join(WEB_DIR, 'sqlite.db'), } } -DATABASE_ENGINE = 'sqlite3' +DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = os.path.join(WEB_DIR, 'sqlite.db') -DATABASE_USER = '' -DATABASE_PASSWORD = '' -DATABASE_HOST = '' -DATABASE_PORT = '' +DATABASE_USER = '' +DATABASE_PASSWORD = '' +DATABASE_HOST = '' +DATABASE_PORT = '' TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' SITE_ID = 1 diff --git a/gramps/webapp/grampsdb/admin.py b/gramps/webapp/grampsdb/admin.py index e6330bd41..cb6f15302 100644 --- a/gramps/webapp/grampsdb/admin.py +++ b/gramps/webapp/grampsdb/admin.py @@ -24,10 +24,10 @@ from gramps.webapp.grampsdb.models import * from django.contrib import admin ## FIXME: this no longer works in Django 1.5 -class MyAdmin(admin.ModelAdmin): - def change_view(self, request, object_id, extra_context=None): - result = super(MyAdmin, self).change_view(request, object_id, extra_context) - if '_addanother' not in request.POST and '_continue' not in request.POST: +class MyAdmin(admin.ModelAdmin): + def change_view(self, request, object_id, extra_context=None): + result = super(MyAdmin, self).change_view(request, object_id, extra_context) + if '_addanother' not in request.POST and '_continue' not in request.POST: result['Location'] = "/" return result diff --git a/gramps/webapp/grampsdb/forms.py b/gramps/webapp/grampsdb/forms.py index 2f0798b05..3d4784e4c 100644 --- a/gramps/webapp/grampsdb/forms.py +++ b/gramps/webapp/grampsdb/forms.py @@ -20,7 +20,7 @@ # webapp/grampsdb/forms.py -# forms.py forms for Django web project +# forms.py forms for Django web project # Django Modules: from django import forms @@ -38,8 +38,8 @@ import datetime class PersonForm(forms.ModelForm): class Meta: model = Person - exclude = ["death", "birth", "handle", "birth_ref_index", - "death_ref_index", "families", "parent_families", + exclude = ["death", "birth", "handle", "birth_ref_index", + "death_ref_index", "families", "parent_families", "cache"] def save(self, *args, **kwargs): self.instance.save_cache_q = kwargs.pop("save_cache", True) @@ -49,41 +49,41 @@ class NameForm(forms.ModelForm): class Meta: model = Name # Exclude these, so they don't get checked: - exclude = ["order", "calendar", "modifier", - "quality", - #"quality_estimated", "quality_calculated", - #"quality_interpreted", + exclude = ["order", "calendar", "modifier", + "quality", + #"quality_estimated", "quality_calculated", + #"quality_interpreted", "year1", "day1", "month1", "sortval", "newyear", "person"] # Add these because they are TextFields, which render as # Textareas: - first_name = forms.CharField(label="Given", - required=False, + first_name = forms.CharField(label="Given", + required=False, widget=TextInput(attrs={'size':'60'})) - title = forms.CharField(required=False, + title = forms.CharField(required=False, widget=TextInput(attrs={'size':'15'})) - call = forms.CharField(label="Call", - required=False, + call = forms.CharField(label="Call", + required=False, widget=TextInput(attrs={'size':'15'})) - nick = forms.CharField(label="Nick", - required=False, + nick = forms.CharField(label="Nick", + required=False, widget=TextInput(attrs={'size':'15'})) - group_as = forms.CharField(label="Group as", - required=False, + group_as = forms.CharField(label="Group as", + required=False, widget=TextInput(attrs={'size':'30'})) - suffix = forms.CharField(required=False, + suffix = forms.CharField(required=False, initial=' suffix ', widget=TextInput(attrs={'size':'15', 'style': 'font-style: italic; color: gray; ', 'onFocus': """if (this.value == ' suffix ') { - this.value = ''; + this.value = ''; } - this.style.color = "black"; + this.style.color = "black"; this.style.fontStyle = 'normal'; """, 'onBlur': """if (this.value == '') { - this.value = ' suffix '; - this.style.color = "gray"; + this.value = ' suffix '; + this.style.color = "gray"; this.style.fontStyle = 'italic'; } """})) @@ -93,10 +93,10 @@ class NameFormFromPerson(NameForm): model = Name # Exclude these, so they don't get checked: # Excludes sort_as and display_as - exclude = ["order", "calendar", "modifier", + exclude = ["order", "calendar", "modifier", "quality", - #"quality_estimated", "quality_calculated", - #"quality_interpreted", + #"quality_estimated", "quality_calculated", + #"quality_interpreted", "year1", "day1", "month1", "sortval", "newyear", "person", "group_as", "sort_as", "display_as"] @@ -106,35 +106,35 @@ class SurnameForm(forms.ModelForm): model = Surname exclude = ['name', 'order'] - surname = forms.CharField(label="Surname", - required=False, + surname = forms.CharField(label="Surname", + required=False, widget=TextInput(attrs={'size':'30'})) - connector = forms.CharField(label="Connector", - required=False, + connector = forms.CharField(label="Connector", + required=False, widget=TextInput(attrs={'size':'30'})) prefix = forms.CharField(label="Prefix", - required=False, + required=False, initial=' prefix ', widget=TextInput(attrs={'size':'15', 'style': 'font-style: italic; color: gray; ', 'onFocus': """if (this.value == ' prefix ') { - this.value = ''; + this.value = ''; } - this.style.color = "black"; + this.style.color = "black"; this.style.fontStyle = 'normal'; """, 'onBlur': """if (this.value == '') { - this.value = ' prefix '; - this.style.color = "gray"; + this.value = ' prefix '; + this.style.color = "gray"; this.style.fontStyle = 'italic'; } """})) class FamilyForm(forms.ModelForm): class Meta: model = Family - exclude = ["handle", "cache", "mother", "father"] + exclude = ["handle", "cache", "mother", "father"] class EventForm(forms.ModelForm): class Meta: @@ -152,7 +152,7 @@ class EventForm(forms.ModelForm): self._errors["date"] = self.error_class([msg]) del data["text"] return data - + def save(self, commit=True): from gramps.webapp.utils import dp from gramps.webapp.libdjango import DjangoInterface @@ -164,8 +164,8 @@ class EventForm(forms.ModelForm): model.save() return model - text = forms.CharField(label="Date", - required=False, + text = forms.CharField(label="Date", + required=False, widget=TextInput(attrs={'size':'45'})) class NoteForm(forms.ModelForm): @@ -191,7 +191,7 @@ class MediaForm(forms.ModelForm): self._errors["date"] = self.error_class([msg]) del data["text"] return data - + def save(self, commit=True): from gramps.webapp.utils import dp from gramps.webapp.libdjango import DjangoInterface @@ -204,14 +204,14 @@ class MediaForm(forms.ModelForm): model.save() return model - text = forms.CharField(label="Date", - required=False, + text = forms.CharField(label="Date", + required=False, widget=TextInput(attrs={'size':'70'})) - desc = forms.CharField(label="Title", - required=False, + desc = forms.CharField(label="Title", + required=False, widget=TextInput(attrs={'size':'70'})) - path = forms.CharField(label="Path", - required=False, + path = forms.CharField(label="Path", + required=False, widget=TextInput(attrs={'size':'70'})) class CitationForm(forms.ModelForm): @@ -229,7 +229,7 @@ class CitationForm(forms.ModelForm): self._errors["date"] = self.error_class([msg]) del data["text"] return data - + def save(self, commit=True): from gramps.webapp.utils import dp from gramps.webapp.libdjango import DjangoInterface @@ -241,8 +241,8 @@ class CitationForm(forms.ModelForm): model.save() return model - text = forms.CharField(label="Date", - required=False, + text = forms.CharField(label="Date", + required=False, widget=TextInput(attrs={'size':'70'})) class SourceForm(forms.ModelForm): @@ -255,14 +255,14 @@ class PlaceForm(forms.ModelForm): model = Place exclude = ["handle", "cache"] - title = forms.CharField(label="Title", - required=False, + title = forms.CharField(label="Title", + required=False, widget=TextInput(attrs={'size':'70'})) - long = forms.CharField(label="Longitude", - required=False, + long = forms.CharField(label="Longitude", + required=False, widget=TextInput(attrs={'size':'70'})) - lat = forms.CharField(label="Latitude", - required=False, + lat = forms.CharField(label="Latitude", + required=False, widget=TextInput(attrs={'size':'70'})) class RepositoryForm(forms.ModelForm): @@ -270,8 +270,8 @@ class RepositoryForm(forms.ModelForm): model = Repository exclude = ["handle", "cache"] - name = forms.CharField(label="Name", - required=False, + name = forms.CharField(label="Name", + required=False, widget=TextInput(attrs={'size':'70'})) class TagForm(forms.ModelForm): @@ -279,8 +279,8 @@ class TagForm(forms.ModelForm): model = Tag exclude = ["handle"] - name = forms.CharField(label="Name", - required=False, + name = forms.CharField(label="Name", + required=False, widget=TextInput(attrs={'size':'70'})) class EventRefForm(forms.ModelForm): @@ -295,7 +295,7 @@ class LogForm(forms.ModelForm): fields = ["reason"] reason = forms.CharField(label="Reason for change", - widget=forms.widgets.Textarea(attrs={'rows':'2', + widget=forms.widgets.Textarea(attrs={'rows':'2', 'cols': '65'})) class PickForm(forms.Form): picklist = forms.ChoiceField() diff --git a/gramps/webapp/grampsdb/models.py b/gramps/webapp/grampsdb/models.py index 15ad7c93b..2d61b2e71 100644 --- a/gramps/webapp/grampsdb/models.py +++ b/gramps/webapp/grampsdb/models.py @@ -81,7 +81,7 @@ def get_default_type_value(the_type): return [x for x in the_type._DATAMAP if x[0] == the_type._DEFAULT][0] def get_datamap(grampsclass): - return sorted([(x[0],x[2]) for x in grampsclass._DATAMAP], + return sorted([(x[0],x[2]) for x in grampsclass._DATAMAP], key=lambda item: item[1]) #--------------------------------------------------------------------------- @@ -92,19 +92,19 @@ def get_datamap(grampsclass): class mGrampsType(models.Model): """ - The abstract base class for all types. - Types are enumerated integers. One integer corresponds with custom, then + The abstract base class for all types. + Types are enumerated integers. One integer corresponds with custom, then custom_type holds the type name """ class Meta: abstract = True - + _CUSTOM = 0 _DEFAULT = 0 _DATAMAP = [] name = models.CharField(max_length=40) - - def __str__(self): + + def __str__(self): return str(self.name) def get_default_type(self): @@ -157,7 +157,7 @@ class ChildRefType(mGrampsType): _DATAMAP = get_datamap(ChildRefType) _CUSTOM = ChildRefType._CUSTOM _DEFAULT = get_default_type_value(ChildRefType) - val = models.IntegerField('child reference type', choices=_DATAMAP, + val = models.IntegerField('child reference type', choices=_DATAMAP, blank=False) class RepositoryType(mGrampsType): @@ -195,7 +195,7 @@ class FamilyRelType(mGrampsType): _DATAMAP = get_datamap(FamilyRelType) _CUSTOM = FamilyRelType._CUSTOM _DEFAULT = get_default_type_value(FamilyRelType) - val = models.IntegerField('family relation type', choices=_DATAMAP, + val = models.IntegerField('family relation type', choices=_DATAMAP, blank=False) class SourceMediaType(mGrampsType): @@ -203,7 +203,7 @@ class SourceMediaType(mGrampsType): _DATAMAP = get_datamap(SourceMediaType) _CUSTOM = SourceMediaType._CUSTOM _DEFAULT = get_default_type_value(SourceMediaType) - val = models.IntegerField('source medium type', choices=_DATAMAP, + val = models.IntegerField('source medium type', choices=_DATAMAP, blank=False) class EventRoleType(mGrampsType): @@ -243,7 +243,7 @@ class LdsType(mGrampsType): class LdsStatus(mGrampsType): _DATAMAP = [(0, "None"), - (1, "BIC"), + (1, "BIC"), (2, "Canceled"), (3, "Child"), (4, "Cleared"), @@ -282,7 +282,7 @@ class CalendarType(mGrampsType): (CAL_FRENCH, "French Republican"), (CAL_PERSIAN, "Persian"), (CAL_ISLAMIC, "Islamic"), - (CAL_SWEDISH, "Swedish")] + (CAL_SWEDISH, "Swedish")] _DEFAULT = _DATAMAP[0] val = models.IntegerField('Calendar', choices=_DATAMAP, blank=False) @@ -381,13 +381,13 @@ class DateObject(models.Model): """ Sets Date fields from a Gramps date object. """ - (self.calendar, self.modifier, self.quality, dateval, self.text, + (self.calendar, self.modifier, self.quality, dateval, self.text, self.sortval, self.newyear) = gdate.serialize() if dateval is None: (self.day1, self.month1, self.year1, self.slash1) = 0, 0, 0, False (self.day2, self.month2, self.year2, self.slash2) = 0, 0, 0, False elif len(dateval) == 8: - (self.day1, self.month1, self.year1, self.slash1, + (self.day1, self.month1, self.year1, self.slash1, self.day2, self.month2, self.year2, self.slash2) = dateval elif len(dateval) == 4: (self.day1, self.month1, self.year1, self.slash1) = dateval @@ -414,7 +414,7 @@ class Config(models.Model): class Tag(models.Model): handle = models.CharField(max_length=19, unique=True) gramps_id = models.TextField(blank=True, null=True) - last_saved = models.DateTimeField('last changed', auto_now=True) + last_saved = models.DateTimeField('last changed', auto_now=True) last_changed = models.DateTimeField('last changed', null=True, blank=True) # user edits last_changed_by = models.TextField(blank=True, null=True) @@ -445,7 +445,7 @@ class Tag(models.Model): return pickle.loads(base64.decodebytes(bytes(self.cache, "utf-8"))) def save_cache(self): - cache = self.make_cache() + cache = self.make_cache() if cache != self.cache: self.cache = cache models.Model.save(self) @@ -476,7 +476,7 @@ class PrimaryObject(models.Model): id = models.AutoField(primary_key=True) handle = models.CharField(max_length=19, unique=True) gramps_id = models.CharField('ID', max_length=25, blank=True) - last_saved = models.DateTimeField('last changed', auto_now=True) + last_saved = models.DateTimeField('last changed', auto_now=True) last_changed = models.DateTimeField('last changed', null=True, blank=True) # user edits last_changed_by = models.TextField(blank=True, null=True) @@ -489,7 +489,7 @@ class PrimaryObject(models.Model): dji = None save_cache_q = False - def __str__(self): + def __str__(self): return "%s: %s" % (self.__class__.__name__, self.gramps_id) @@ -533,7 +533,7 @@ class PrimaryObject(models.Model): return pickle.loads(base64.decodebytes(bytes(self.cache, "utf-8"))) def save_cache(self): - cache = self.make_cache() + cache = self.make_cache() if cache != self.cache: self.cache = cache models.Model.save(self) @@ -562,9 +562,9 @@ class Person(PrimaryObject): gender_type = models.ForeignKey('GenderType', verbose_name="Gender") probably_alive = models.BooleanField("Probably alive", default=True) families = models.ManyToManyField('Family', blank=True, null=True, through="MyFamilies") - parent_families = models.ManyToManyField('Family', + parent_families = models.ManyToManyField('Family', related_name="parent_families", - blank=True, null=True, + blank=True, null=True, through='MyParentFamilies') #addresses = models.ManyToManyField('Address', null=True, blank=True) references = generic.GenericRelation('PersonRef', #related_name="refs", @@ -577,7 +577,7 @@ class Person(PrimaryObject): death_ref_index = models.IntegerField("Death Reference Index", default=-1) # Others keys here: - # .name_set + # .name_set # .address_set # .lds_set # .url_set @@ -609,9 +609,9 @@ class Person(PrimaryObject): PrimaryObject.save(self, *args, **kwargs) class Family(PrimaryObject): - father = models.ForeignKey('Person', related_name="father_ref", + father = models.ForeignKey('Person', related_name="father_ref", null=True, blank=True) - mother = models.ForeignKey('Person', related_name="mother_ref", + mother = models.ForeignKey('Person', related_name="mother_ref", null=True, blank=True) family_rel_type = models.ForeignKey('FamilyRelType', verbose_name="Type") @@ -643,7 +643,7 @@ class Citation(DateObject, PrimaryObject): object_id_field="object_id") def __str__(self): - return "[%s] (%s, %s) to %s" % (self.gramps_id, + return "[%s] (%s, %s) to %s" % (self.gramps_id, self.confidence, self.page, self.source) @@ -673,8 +673,8 @@ class Event(DateObject, PrimaryObject): object_id_field="object_id") def __str__(self): - return "[%s] (%s) %s" % (self.gramps_id, - self.event_type, + return "[%s] (%s) %s" % (self.gramps_id, + self.event_type, self.description) class Repository(PrimaryObject): @@ -746,7 +746,7 @@ class Note(PrimaryObject): class SecondaryObject(models.Model): """ - We use interlinked objects, secondary object is the table for primary + We use interlinked objects, secondary object is the table for primary objects to refer to when linking to non primary objects """ class Meta: abstract = True @@ -762,7 +762,7 @@ class Surname(models.Model): """ Surname table, which links to name. """ - name_origin_type = models.ForeignKey('NameOriginType', + name_origin_type = models.ForeignKey('NameOriginType', verbose_name="Origin", related_name="name_origin_code", default=2) @@ -778,8 +778,8 @@ class Surname(models.Model): def get_url(self): # /person/handle/name/1/surname/2 - return "/person/%s/name/%s/surname/%s" % (self.name.person.handle, - self.name.order, + return "/person/%s/name/%s/surname/%s" % (self.name.person.handle, + self.name.order, self.order) class Name(DateObject, SecondaryObject): @@ -794,10 +794,10 @@ class Name(DateObject, SecondaryObject): nick = models.TextField(blank=True) famnick = models.TextField(blank=True) group_as = models.TextField(blank=True) - sort_as = models.ForeignKey('NameFormatType', + sort_as = models.ForeignKey('NameFormatType', related_name="sort_as", default=1) - display_as = models.ForeignKey('NameFormatType', + display_as = models.ForeignKey('NameFormatType', related_name="display_as", default=1) ## Key: @@ -834,7 +834,7 @@ class Name(DateObject, SecondaryObject): self.title = "" def make_surname_list(self): - return [(x.surname, x.prefix, x.primary, + return [(x.surname, x.prefix, x.primary, tuple(x.name_origin_type), x.connector) for x in self.surname_set.all()] @@ -849,7 +849,7 @@ class Lds(DateObject, SecondaryObject): SEAL_TO_PARENTS = 2 SEAL_TO_SPOUSE = 3 CONFIRMATION = 4 - + DEFAULT_TYPE = BAPTISM @@ -874,7 +874,7 @@ class Lds(DateObject, SecondaryObject): place = models.ForeignKey('Place', null=True) famc = models.ForeignKey('Family', related_name="famc", null=True) temple = models.TextField(blank=True) - status = models.ForeignKey('LdsStatus') + status = models.ForeignKey('LdsStatus') person = models.ForeignKey("Person", null=True, blank=True) family = models.ForeignKey("Family", null=True, blank=True) @@ -928,7 +928,7 @@ class Url(models.Model): private = models.BooleanField('private url?', default=True) path = models.TextField(blank=True, null=True) desc = models.TextField(blank=True, null=True) - url_type = models.ForeignKey('UrlType') + url_type = models.ForeignKey('UrlType') order = models.PositiveIntegerField() person = models.ForeignKey("Person", null=True, blank=True) @@ -937,7 +937,7 @@ class Url(models.Model): class Attribute(models.Model): private = models.BooleanField('private attribute?', default=True) - attribute_type = models.ForeignKey('AttributeType') + attribute_type = models.ForeignKey('AttributeType') value = models.TextField(blank=True, null=True) object_type = models.ForeignKey(ContentType) @@ -972,9 +972,9 @@ class BaseRef(models.Model): # /person/3536453463/reference/event/2 ref_by = self.object_type.model_class().objects.get(id=self.object_id) ref_to = self.get_reference_to() - return "/%s/%s/reference/%s/%s" % (ref_by.__class__.__name__.lower(), - ref_by.handle, - ref_to.__class__.__name__.lower(), + return "/%s/%s/reference/%s/%s" % (ref_by.__class__.__name__.lower(), + ref_by.handle, + ref_to.__class__.__name__.lower(), self.order) class Log(BaseRef): log_type = models.CharField(max_length=10) # edit, delete, add @@ -982,13 +982,13 @@ class Log(BaseRef): cache = models.TextField(blank=True, null=True) def __str__(self): - return "%s: %s on %s by %s" % (self.log_type, - self.referenced_by, + return "%s: %s on %s by %s" % (self.log_type, + self.referenced_by, self.last_changed, self.last_changed_by) class NoteRef(BaseRef): - ref_object = models.ForeignKey('Note') + ref_object = models.ForeignKey('Note') def get_reference_to(self): return self.ref_object @@ -1010,9 +1010,9 @@ class EventRef(BaseRef): # /person/3536453463/reference/event/2 ref_by = self.object_type.model_class().objects.get(id=self.object_id) ref_to = self.ref_object - return "/%s/%s/reference/%s/%s" % (ref_by.__class__.__name__.lower(), - ref_by.handle, - ref_to.__class__.__name__.lower(), + return "/%s/%s/reference/%s/%s" % (ref_by.__class__.__name__.lower(), + ref_by.handle, + ref_to.__class__.__name__.lower(), self.order) class RepositoryRef(BaseRef): @@ -1046,18 +1046,18 @@ class PersonRef(BaseRef): return "PersonRef to " + str(self.ref_object) class CitationRef(BaseRef): - citation = models.ForeignKey('Citation') + citation = models.ForeignKey('Citation') def __str__(self): return "CitationRef to " + str(self.citation) - + def get_reference_to(self): return self.citation class ChildRef(BaseRef): - father_rel_type = models.ForeignKey('ChildRefType', + father_rel_type = models.ForeignKey('ChildRefType', related_name="child_father_rel") - mother_rel_type = models.ForeignKey('ChildRefType', + mother_rel_type = models.ForeignKey('ChildRefType', related_name="child_mother_rel") ref_object = models.ForeignKey('Person') @@ -1206,8 +1206,8 @@ def clear_tables(*categories): flush_tables.append(model._meta.db_table) # tables = connection.introspection.table_names() # flush_tables = [table for table in tables if not table.endswith("type")] - statements = connection.ops.sql_flush(no_style(), - flush_tables, + statements = connection.ops.sql_flush(no_style(), + flush_tables, connection.introspection.sequence_list()) for statement in statements: cursor.execute(statement) @@ -1224,6 +1224,6 @@ def table_stats(*categories): pair[1].objects.all().count()) def get_tables(*categories): - return [pair for pair in TABLES if (pair[0] in categories) or + return [pair for pair in TABLES if (pair[0] in categories) or ("all" in categories) and pair[0] != "abstract"] diff --git a/gramps/webapp/grampsdb/templatetags/my_tags.py b/gramps/webapp/grampsdb/templatetags/my_tags.py index 10e814f57..ee533f727 100644 --- a/gramps/webapp/grampsdb/templatetags/my_tags.py +++ b/gramps/webapp/grampsdb/templatetags/my_tags.py @@ -50,7 +50,7 @@ class TemplateNode(template.Node): self.func = func def render(self, context): - value = self.func(*[eval_template_exp(item, context) + value = self.func(*[eval_template_exp(item, context) for item in self.args]) if self.var_name: context[self.var_name] = value @@ -210,7 +210,7 @@ def table_header(context, headers = None): context["headers"] = headers return context -register.inclusion_tag('table_header.html', +register.inclusion_tag('table_header.html', takes_context=True)(table_header) def paginator(context, adjacent_pages=2): @@ -226,5 +226,5 @@ def paginator(context, adjacent_pages=2): context.update({'results_this_page': results_this_page,}) return context -register.inclusion_tag('paginator.html', +register.inclusion_tag('paginator.html', takes_context=True)(paginator) diff --git a/gramps/webapp/grampsdb/view/citation.py b/gramps/webapp/grampsdb/view/citation.py index 9300445ee..a66968d3f 100644 --- a/gramps/webapp/grampsdb/view/citation.py +++ b/gramps/webapp/grampsdb/view/citation.py @@ -40,7 +40,7 @@ def process_citation(request, context, handle, act, add_to=None): # view, edit, context["tviews"] = _("Citations") context["action"] = "view" view_template = "view_citation_detail.html" - + if handle == "add": act = "add" if "action" in request.POST: @@ -49,24 +49,24 @@ def process_citation(request, context, handle, act, add_to=None): # view, edit, # Handle: edit, view, add, create, save, delete, share, save-share if act == "share": item, handle = add_to - context["pickform"] = PickForm("Pick citation", - Citation, + context["pickform"] = PickForm("Pick citation", + Citation, (), - request.POST) + request.POST) context["object_handle"] = handle context["object_type"] = item return render_to_response("pick.html", context) elif act == "save-share": - item, handle = add_to - pickform = PickForm("Pick citation", - Citation, + item, handle = add_to + pickform = PickForm("Pick citation", + Citation, (), request.POST) if pickform.data["picklist"]: parent_model = dji.get_model(item) # what model? parent_obj = parent_model.objects.get(handle=handle) # to add ref_handle = pickform.data["picklist"] - ref_obj = Citation.objects.get(handle=ref_handle) + ref_obj = Citation.objects.get(handle=ref_handle) dji.add_citation_ref_default(parent_obj, ref_obj) parent_obj.save_cache() # rebuild cache return redirect("/%s/%s%s#tab-citations" % (item, handle, build_search(request))) @@ -82,14 +82,14 @@ def process_citation(request, context, handle, act, add_to=None): # view, edit, citation = Citation(source=source, gramps_id=dji.get_next_id(Citation, "C")) citationform = CitationForm(instance=citation) citationform.model = citation - elif act in ["view", "edit"]: + elif act in ["view", "edit"]: citation = Citation.objects.get(handle=handle) citationform = CitationForm(instance=citation) citationform.model = citation source = citation.source sourceform = SourceForm(instance=source) sourceform.model = source - elif act == "save": + elif act == "save": citation = Citation.objects.get(handle=handle) citationform = CitationForm(request.POST, instance=citation) citationform.model = citation @@ -99,7 +99,7 @@ def process_citation(request, context, handle, act, add_to=None): # view, edit, act = "view" else: act = "edit" - elif act == "create": + elif act == "create": source = Source(handle=create_id()) sourceform = SourceForm(request.POST, instance=source) sourceform.model = source @@ -124,7 +124,7 @@ def process_citation(request, context, handle, act, add_to=None): # view, edit, act = "view" else: act = "add" - elif act == "delete": + elif act == "delete": citation = Citation.objects.get(handle=handle) citation.delete() return redirect("/citation/") @@ -137,5 +137,5 @@ def process_citation(request, context, handle, act, add_to=None): # view, edit, context["citation"] = citation context["source"] = source context["action"] = act - + return render_to_response(view_template, context) diff --git a/gramps/webapp/grampsdb/view/family.py b/gramps/webapp/grampsdb/view/family.py index 4a3676c1e..4d4a67f31 100644 --- a/gramps/webapp/grampsdb/view/family.py +++ b/gramps/webapp/grampsdb/view/family.py @@ -49,27 +49,27 @@ def process_family(request, context, handle, act, add_to=None): # view, edit, sa if act == "share": # Adds a person to an existing family item, handle = add_to - context["pickform"] = PickForm("Pick family", - Family, + context["pickform"] = PickForm("Pick family", + Family, (), - request.POST) + request.POST) context["object_handle"] = handle context["object_type"] = "person" return render_to_response("pick.html", context) elif act == "save-share": - item, handle = add_to - pickform = PickForm("Pick family", - Family, + item, handle = add_to + pickform = PickForm("Pick family", + Family, (), request.POST) if pickform.data["picklist"]: person = Person.objects.get(handle=handle) # to add ref_handle = pickform.data["picklist"] - ref_obj = Family.objects.get(handle=ref_handle) + ref_obj = Family.objects.get(handle=ref_handle) if item == "child": dji.add_child_ref_default(ref_obj, person) # add person to family #person.parent_families.add(ref_obj) # add family to child - pfo = MyParentFamilies(person=person, family=ref_obj, + pfo = MyParentFamilies(person=person, family=ref_obj, order=len(person.parent_families.all())+1) pfo.save() elif item == "spouse": @@ -80,7 +80,7 @@ def process_family(request, context, handle, act, add_to=None): # view, edit, sa else: ref_obj.father = person # FIXME: Unknown gender, add to open #person.families.add(ref_obj) # add family to person - pfo = MyFamilies(person=person, family=ref_obj, + pfo = MyFamilies(person=person, family=ref_obj, order=len(person.families.all())+1) pfo.save() ref_obj.save() @@ -108,13 +108,13 @@ def process_family(request, context, handle, act, add_to=None): # view, edit, sa else: # You have to pick one! family.father = person elif what == "child": - pass # FIXME: can't show child in table? + pass # FIXME: can't show child in table? # Table from children_table else: # unknown what! raise Exception("can't add_to: '%s'" % what) familyform = FamilyForm(instance=family) familyform.model = family - elif act in ["view", "edit"]: + elif act in ["view", "edit"]: family = Family.objects.get(handle=handle) familyform = FamilyForm(instance=family) familyform.model = family @@ -136,20 +136,20 @@ def process_family(request, context, handle, act, add_to=None): # view, edit, sa if familyform.cleaned_data["mother"]: if family not in familyform.cleaned_data["mother"].families.all(): #family.mother.families.add(family) - pfo = MyFamilies(person=familyform.cleaned_data["mother"], family=family, + pfo = MyFamilies(person=familyform.cleaned_data["mother"], family=family, order=len(familyform.cleaned_data["mother"].families.all())+1) pfo.save() if familyform.cleaned_data["father"]: if family not in familyform.cleaned_data["father"].families.all(): #family.father.families.add(family) - pfo = MyFamilies(person=family.father, family=family, + pfo = MyFamilies(person=family.father, family=family, order=len(familyform.cleaned_data["father"].families.all())+1) pfo.save() familyform.save() act = "view" else: act = "edit" - elif act == "create": + elif act == "create": family = Family(family_rel_type=FamilyRelType.objects.get( val=FamilyRelType._DEFAULT[0]), handle=create_id()) @@ -160,7 +160,7 @@ def process_family(request, context, handle, act, add_to=None): # view, edit, sa family = familyform.save() if family.mother: #family.mother.families.add(family) - pfo = MyFamilies(person=family.mother, family=family, + pfo = MyFamilies(person=family.mother, family=family, order=len(family.mother.families.all())+1) pfo.save() if family.father: @@ -185,7 +185,7 @@ def process_family(request, context, handle, act, add_to=None): # view, edit, sa act = "view" else: act = "add" - elif act == "delete": + elif act == "delete": family = Family.objects.get(handle=handle) family.delete() return redirect("/family/") @@ -197,5 +197,5 @@ def process_family(request, context, handle, act, add_to=None): # view, edit, sa context["family"] = family context["action"] = act view_template = "view_family_detail.html" - + return render_to_response(view_template, context) diff --git a/gramps/webapp/grampsdb/view/media.py b/gramps/webapp/grampsdb/view/media.py index aecd4f014..56ef9c264 100644 --- a/gramps/webapp/grampsdb/view/media.py +++ b/gramps/webapp/grampsdb/view/media.py @@ -24,7 +24,7 @@ from gramps.webapp.utils import _, boolean, update_last_changed, build_search from gramps.webapp.grampsdb.models import Media from gramps.webapp.grampsdb.forms import * from gramps.webapp.libdjango import DjangoInterface -from gramps.gen.config import config +from gramps.gen.config import config ## Django Modules from django.shortcuts import get_object_or_404, render_to_response, redirect @@ -49,7 +49,7 @@ dji = DjangoInterface() def pb2image(pb): width, height = pb.get_width(), pb.get_height() return Image.fromstring("RGB", (width,height), pb.get_pixels()) - + def process_media(request, context, handle, act, add_to=None): # view, edit, save """ Process act on person. Can return a redirect. @@ -58,7 +58,7 @@ def process_media(request, context, handle, act, add_to=None): # view, edit, sav context["tviews"] = _("Media") context["action"] = "view" view_template = "view_media_detail.html" - + if handle == "add": act = "add" if "action" in request.POST: @@ -67,24 +67,24 @@ def process_media(request, context, handle, act, add_to=None): # view, edit, sav # Handle: edit, view, add, create, save, delete, share, save-share if act == "share": item, handle = add_to - context["pickform"] = PickForm("Pick media", - Media, + context["pickform"] = PickForm("Pick media", + Media, (), - request.POST) + request.POST) context["object_handle"] = handle context["object_type"] = item return render_to_response("pick.html", context) elif act == "save-share": - item, handle = add_to - pickform = PickForm("Pick media", - Media, + item, handle = add_to + pickform = PickForm("Pick media", + Media, (), request.POST) if pickform.data["picklist"]: parent_model = dji.get_model(item) # what model? parent_obj = parent_model.objects.get(handle=handle) # to add ref_handle = pickform.data["picklist"] - ref_obj = Media.objects.get(handle=ref_handle) + ref_obj = Media.objects.get(handle=ref_handle) dji.add_media_ref_default(parent_obj, ref_obj) parent_obj.save_cache() # rebuild cache return redirect("/%s/%s%s#tab-media" % (item, handle, build_search(request))) @@ -154,11 +154,11 @@ def process_media(request, context, handle, act, add_to=None): # view, edit, sav media = Media(gramps_id=dji.get_next_id(Media, "M")) mediaform = MediaForm(instance=media) mediaform.model = media - elif act in ["view", "edit"]: + elif act in ["view", "edit"]: media = Media.objects.get(handle=handle) mediaform = MediaForm(instance=media) mediaform.model = media - elif act == "save": + elif act == "save": media = Media.objects.get(handle=handle) mediaform = MediaForm(request.POST, instance=media) mediaform.model = media @@ -168,7 +168,7 @@ def process_media(request, context, handle, act, add_to=None): # view, edit, sav act = "view" else: act = "edit" - elif act == "create": + elif act == "create": media = Media(handle=create_id()) mediaform = MediaForm(request.POST, instance=media) mediaform.model = media @@ -188,7 +188,7 @@ def process_media(request, context, handle, act, add_to=None): # view, edit, sav act = "view" else: act = "add" - elif act == "delete": + elif act == "delete": media = Media.objects.get(handle=handle) media.delete() return redirect("/media/") @@ -199,5 +199,5 @@ def process_media(request, context, handle, act, add_to=None): # view, edit, sav context["object"] = media context["media"] = media context["action"] = act - + return render_to_response(view_template, context) diff --git a/gramps/webapp/grampsdb/view/person.py b/gramps/webapp/grampsdb/view/person.py index 53edeed64..dfe760a29 100644 --- a/gramps/webapp/grampsdb/view/person.py +++ b/gramps/webapp/grampsdb/view/person.py @@ -144,10 +144,10 @@ def process_surname(request, handle, order, sorder, act="view"): neworder += 1 else: request.user.message_set.create(message="You can't delete the only surname") - return redirect("/person/%s/name/%s%s#tab-surnames" % (person.handle, name.order, + return redirect("/person/%s/name/%s%s#tab-surnames" % (person.handle, name.order, build_search(request))) elif act in ["add"]: - surname = Surname(name=name, primary=False, + surname = Surname(name=name, primary=False, name_origin_type=NameOriginType.objects.get(val=NameOriginType._DEFAULT[0])) surname.prefix = make_empty(True, surname.prefix, " prefix ") elif act == "create": @@ -155,7 +155,7 @@ def process_surname(request, handle, order, sorder, act="view"): sorder = 1 for surname in surnames: sorder += 1 - surname = Surname(name=name, primary=True, + surname = Surname(name=name, primary=True, name_origin_type=NameOriginType.objects.get(val=NameOriginType._DEFAULT[0]), order=sorder) sf = SurnameForm(request.POST, instance=surname) @@ -166,8 +166,8 @@ def process_surname(request, handle, order, sorder, act="view"): check_primary(surname, surnames) surname.save() person.save_cache() - return redirect("/person/%s/name/%s/surname/%s%s#tab-surnames" % - (person.handle, name.order, sorder, + return redirect("/person/%s/name/%s/surname/%s%s#tab-surnames" % + (person.handle, name.order, sorder, build_search(request))) act = "add" surname.prefix = make_empty(True, surname.prefix, " prefix ") @@ -181,7 +181,7 @@ def process_surname(request, handle, order, sorder, act="view"): check_primary(surname, name.surname_set.all().exclude(order=surname.order)) surname.save() person.save_cache() - return redirect("/person/%s/name/%s/surname/%s%s#tab-surnames" % + return redirect("/person/%s/name/%s/surname/%s%s#tab-surnames" % (person.handle, name.order, sorder, build_search(request))) act = "edit" @@ -231,15 +231,15 @@ def process_name(request, handle, order, act="view"): build_search(request))) elif act == "add": # add name person = Person.objects.get(handle=handle) - name = Name(person=person, + name = Name(person=person, preferred=False, - display_as=NameFormatType.objects.get(val=NameFormatType._DEFAULT[0]), - sort_as=NameFormatType.objects.get(val=NameFormatType._DEFAULT[0]), + display_as=NameFormatType.objects.get(val=NameFormatType._DEFAULT[0]), + sort_as=NameFormatType.objects.get(val=NameFormatType._DEFAULT[0]), name_type=NameType.objects.get(val=NameType._DEFAULT[0])) nf = NameForm(instance=name) nf.model = name - surname = Surname(name=name, - primary=True, + surname = Surname(name=name, + primary=True, order=1, name_origin_type=NameOriginType.objects.get(val=NameOriginType._DEFAULT[0])) sf = SurnameForm(request.POST, instance=surname) @@ -249,9 +249,9 @@ def process_name(request, handle, order, act="view"): person = Person.objects.get(handle=handle) name = Name(preferred=False) next_order = max([name.order for name in person.name_set.all()]) + 1 - surname = Surname(name=name, - primary=True, - order=next_order, + surname = Surname(name=name, + primary=True, + order=next_order, name_origin_type=NameOriginType.objects.get(val=NameOriginType._DEFAULT[0])) # combine with user data: nf = NameForm(request.POST, instance=name) @@ -280,7 +280,7 @@ def process_name(request, handle, order, act="view"): surname.primary = True # FIXME: why is this False? Remove from form? surname.save() person.save_cache() - return redirect("/person/%s/name/%s%s#tab-surnames" % (person.handle, name.order, + return redirect("/person/%s/name/%s%s#tab-surnames" % (person.handle, name.order, build_search(request))) else: act = "add" @@ -346,19 +346,19 @@ def process_person(request, context, handle, act, add_to=None): # view, edit, sa if request.user.is_authenticated(): if act == "share": item, handle = add_to - context["pickform"] = PickForm("Pick a person", - Person, - ("name__surname__surname", + context["pickform"] = PickForm("Pick a person", + Person, + ("name__surname__surname", "name__first_name"), - request.POST) + request.POST) context["object_handle"] = handle context["object_type"] = item return render_to_response("pick.html", context) elif act == "save-share": item, handle = add_to # ("Family", handle) - pickform = PickForm("Pick a person", - Person, - ("name__surname__surname", + pickform = PickForm("Pick a person", + Person, + ("name__surname__surname", "name__first_name"), request.POST) if pickform.data["picklist"]: @@ -393,7 +393,7 @@ def process_person(request, context, handle, act, add_to=None): # view, edit, sa elif act in ["save", "create"]: # could be create a new person # look up old data, if any: logform = LogForm(request.POST) - if handle: + if handle: person = Person.objects.get(handle=handle) name = person.name_set.get(preferred=True) surname = name.surname_set.get(primary=True) @@ -401,8 +401,8 @@ def process_person(request, context, handle, act, add_to=None): # view, edit, sa person = Person(handle=create_id()) name = Name(person=person, preferred=True) surname = Surname(name=name, primary=True, order=1) - surname = Surname(name=name, - primary=True, + surname = Surname(name=name, + primary=True, order=1, name_origin_type=NameOriginType.objects.get(val=NameOriginType._DEFAULT[0])) # combine with user data: @@ -449,7 +449,7 @@ def process_person(request, context, handle, act, add_to=None): # view, edit, sa return redirect("/%s/%s%s" % (item, handle, build_search(request))) person.save_cache() return redirect("/person/%s%s" % (person.handle, build_search(request))) - else: + else: # need to edit again if handle: act = "edit" @@ -496,14 +496,14 @@ def get_person_forms(handle, protect=False, empty=False, order=None): name = person.name_set.get(preferred=True) except: name = Name(person=person, preferred=True, - display_as=NameFormatType.objects.get(val=NameFormatType._DEFAULT[0]), - sort_as=NameFormatType.objects.get(val=NameFormatType._DEFAULT[0]), + display_as=NameFormatType.objects.get(val=NameFormatType._DEFAULT[0]), + sort_as=NameFormatType.objects.get(val=NameFormatType._DEFAULT[0]), name_type=NameType.objects.get(val=NameType._DEFAULT[0])) ## get a surname try: surname = name.surname_set.get(primary=True) except: - surname = Surname(name=name, primary=True, + surname = Surname(name=name, primary=True, name_origin_type=NameOriginType.objects.get(val=NameOriginType._DEFAULT[0]), order=1) diff --git a/gramps/webapp/grampsdb/view/place.py b/gramps/webapp/grampsdb/view/place.py index 4a8aed188..70b43eb96 100644 --- a/gramps/webapp/grampsdb/view/place.py +++ b/gramps/webapp/grampsdb/view/place.py @@ -51,11 +51,11 @@ def process_place(request, context, handle, act, add_to=None): # view, edit, sav place = Place(gramps_id=dji.get_next_id(Place, "P")) placeform = PlaceForm(instance=place) placeform.model = place - elif act in ["view", "edit"]: + elif act in ["view", "edit"]: place = Place.objects.get(handle=handle) placeform = PlaceForm(instance=place) placeform.model = place - elif act == "save": + elif act == "save": place = Place.objects.get(handle=handle) placeform = PlaceForm(request.POST, instance=place) placeform.model = place @@ -65,7 +65,7 @@ def process_place(request, context, handle, act, add_to=None): # view, edit, sav act = "view" else: act = "edit" - elif act == "create": + elif act == "create": place = Place(handle=create_id()) placeform = PlaceForm(request.POST, instance=place) placeform.model = place @@ -82,7 +82,7 @@ def process_place(request, context, handle, act, add_to=None): # view, edit, sav act = "view" else: act = "add" - elif act == "delete": + elif act == "delete": place = Place.objects.get(handle=handle) place.delete() return redirect("/place/") @@ -93,5 +93,5 @@ def process_place(request, context, handle, act, add_to=None): # view, edit, sav context["object"] = place context["place"] = place context["action"] = act - + return render_to_response(view_template, context) diff --git a/gramps/webapp/grampsdb/view/png.py b/gramps/webapp/grampsdb/view/png.py index c200fbe3e..434de5779 100644 --- a/gramps/webapp/grampsdb/view/png.py +++ b/gramps/webapp/grampsdb/view/png.py @@ -433,9 +433,9 @@ class Writer: connexions interlaced images can be partially decoded by the browser to give a rough view of the image that is successively refined as more image data appears. - + .. note :: - + Enabling the `interlace` option requires the entire image to be processed in working memory. @@ -623,7 +623,7 @@ class Writer: If `interlace` is specified (when creating the instance), then an interlaced PNG file will be written. Supply the rows in the normal image order; the interlacing is carried out internally. - + .. note :: Interlacing will require the entire image to be in working memory. @@ -646,7 +646,7 @@ class Writer: Most users are expected to find the :meth:`write` or :meth:`write_array` method more convenient. - + The rows should be given to this method in the order that they appear in the output file. For straightlaced images, this is the usual top to bottom ordering, but for interlaced @@ -681,7 +681,7 @@ class Writer: write_chunk(outfile, 'sBIT', struct.pack('%dB' % self.planes, *[self.rescale[0]]*self.planes)) - + # :chunk:order: Without a palette (PLTE chunk), ordering is # relatively relaxed. With one, gAMA chunk must precede PLTE # chunk which must precede tRNS and bKGD. @@ -1073,7 +1073,7 @@ def from_array(a, mode=None, info={}): only. It doesn't actually work. Please bear with us. Meanwhile enjoy the complimentary snacks (on request) and please use a 2-dimensional array. - + Unless they are specified using the *info* parameter, the PNG's height and width are taken from the array size. For a 3 dimensional array the first axis is the height; the second axis is the width; @@ -1128,7 +1128,7 @@ def from_array(a, mode=None, info={}): metadata (in the same style as the arguments to the :class:``png.Writer`` class). For this function the keys that are useful are: - + height overrides the height derived from the array dimensions and allows *a* to be an iterable. @@ -1266,10 +1266,10 @@ class Image: def __init__(self, rows, info): """ .. note :: - + The constructor is not public. Please do not call it. """ - + self.rows = rows self.info = info @@ -2100,7 +2100,7 @@ class Reader: This function returns a 4-tuple: (*width*, *height*, *pixels*, *metadata*). *width*, *height*, *metadata* are as per the :meth:`read` method. - + *pixels* is the pixel data in boxed row flat pixel format. """ diff --git a/gramps/webapp/grampsdb/view/repository.py b/gramps/webapp/grampsdb/view/repository.py index 692421719..1eb76a5a3 100644 --- a/gramps/webapp/grampsdb/view/repository.py +++ b/gramps/webapp/grampsdb/view/repository.py @@ -40,7 +40,7 @@ def process_repository(request, context, handle, act, add_to=None): # view, edit context["tviews"] = _("Repositories") context["action"] = "view" view_template = "view_repository_detail.html" - + if handle == "add": act = "add" if "action" in request.POST: @@ -49,24 +49,24 @@ def process_repository(request, context, handle, act, add_to=None): # view, edit # Handle: edit, view, add, create, save, delete, share, save-share if act == "share": item, handle = add_to - context["pickform"] = PickForm("Pick repository", - Repository, + context["pickform"] = PickForm("Pick repository", + Repository, (), - request.POST) + request.POST) context["object_handle"] = handle context["object_type"] = item return render_to_response("pick.html", context) elif act == "save-share": - item, handle = add_to - pickform = PickForm("Pick repository", - Repository, + item, handle = add_to + pickform = PickForm("Pick repository", + Repository, (), request.POST) if pickform.data["picklist"]: parent_model = dji.get_model(item) # what model? parent_obj = parent_model.objects.get(handle=handle) # to add ref_handle = pickform.data["picklist"] - ref_obj = Repository.objects.get(handle=ref_handle) + ref_obj = Repository.objects.get(handle=ref_handle) dji.add_repository_ref_default(parent_obj, ref_obj) parent_obj.save_cache() # rebuild cache return redirect("/%s/%s%s#tab-repositories" % (item, handle, build_search(request))) @@ -79,11 +79,11 @@ def process_repository(request, context, handle, act, add_to=None): # view, edit repository = Repository(gramps_id=dji.get_next_id(Repository, "R")) repositoryform = RepositoryForm(instance=repository) repositoryform.model = repository - elif act in ["view", "edit"]: + elif act in ["view", "edit"]: repository = Repository.objects.get(handle=handle) repositoryform = RepositoryForm(instance=repository) repositoryform.model = repository - elif act == "save": + elif act == "save": repository = Repository.objects.get(handle=handle) repositoryform = RepositoryForm(request.POST, instance=repository) repositoryform.model = repository @@ -93,7 +93,7 @@ def process_repository(request, context, handle, act, add_to=None): # view, edit act = "view" else: act = "edit" - elif act == "create": + elif act == "create": repository = Repository(handle=create_id()) repositoryform = RepositoryForm(request.POST, instance=repository) repositoryform.model = repository @@ -110,7 +110,7 @@ def process_repository(request, context, handle, act, add_to=None): # view, edit act = "view" else: act = "add" - elif act == "delete": + elif act == "delete": repository = Repository.objects.get(handle=handle) repository.delete() return redirect("/repository/") @@ -121,6 +121,6 @@ def process_repository(request, context, handle, act, add_to=None): # view, edit context["object"] = repository context["repository"] = repository context["action"] = act - + return render_to_response(view_template, context) diff --git a/gramps/webapp/grampsdb/view/source.py b/gramps/webapp/grampsdb/view/source.py index 8bcae2a4d..da1c2d041 100644 --- a/gramps/webapp/grampsdb/view/source.py +++ b/gramps/webapp/grampsdb/view/source.py @@ -40,7 +40,7 @@ def process_source(request, context, handle, act, add_to=None): # view, edit, sa context["tviews"] = _("Sources") context["action"] = "view" view_template = "view_source_detail.html" - + if handle == "add": act = "add" if "action" in request.POST: @@ -49,24 +49,24 @@ def process_source(request, context, handle, act, add_to=None): # view, edit, sa # Handle: edit, view, add, create, save, delete, share, save-share if act == "share": item, handle = add_to - context["pickform"] = PickForm("Pick source", - Source, + context["pickform"] = PickForm("Pick source", + Source, (), - request.POST) + request.POST) context["object_handle"] = handle context["object_type"] = item return render_to_response("pick.html", context) elif act == "save-share": - item, handle = add_to - pickform = PickForm("Pick source", - Source, + item, handle = add_to + pickform = PickForm("Pick source", + Source, (), request.POST) if pickform.data["picklist"]: parent_model = dji.get_model(item) # what model? parent_obj = parent_model.objects.get(handle=handle) # to add ref_handle = pickform.data["picklist"] - ref_obj = Source.objects.get(handle=ref_handle) + ref_obj = Source.objects.get(handle=ref_handle) dji.add_source_ref_default(parent_obj, ref_obj) parent_obj.save_cache() # rebuild cache return redirect("/%s/%s%s#tab-sources" % (item, handle, build_search(request))) @@ -79,11 +79,11 @@ def process_source(request, context, handle, act, add_to=None): # view, edit, sa source = Source(gramps_id=dji.get_next_id(Source, "S")) sourceform = SourceForm(instance=source) sourceform.model = source - elif act in ["view", "edit"]: + elif act in ["view", "edit"]: source = Source.objects.get(handle=handle) sourceform = SourceForm(instance=source) sourceform.model = source - elif act == "save": + elif act == "save": source = Source.objects.get(handle=handle) sourceform = SourceForm(request.POST, instance=source) sourceform.model = source @@ -94,7 +94,7 @@ def process_source(request, context, handle, act, add_to=None): # view, edit, sa act = "view" else: act = "edit" - elif act == "create": + elif act == "create": source = Source(handle=create_id()) sourceform = SourceForm(request.POST, instance=source) sourceform.model = source @@ -107,7 +107,7 @@ def process_source(request, context, handle, act, add_to=None): # view, edit, sa act = "view" else: act = "add" - elif act == "delete": + elif act == "delete": source = Source.objects.get(handle=handle) source.delete() return redirect("/source/") @@ -118,7 +118,7 @@ def process_source(request, context, handle, act, add_to=None): # view, edit, sa context["object"] = source context["source"] = source context["action"] = act - + return render_to_response(view_template, context) diff --git a/gramps/webapp/grampsdb/view/tag.py b/gramps/webapp/grampsdb/view/tag.py index 7e5460d6a..e3531ce85 100644 --- a/gramps/webapp/grampsdb/view/tag.py +++ b/gramps/webapp/grampsdb/view/tag.py @@ -40,7 +40,7 @@ def process_tag(request, context, handle, act, add_to=None): # view, edit, save context["tviews"] = _("Tags") context["action"] = "view" view_template = "view_tag_detail.html" - + if handle == "add": act = "add" if "action" in request.POST: @@ -51,11 +51,11 @@ def process_tag(request, context, handle, act, add_to=None): # view, edit, save tag = Tag() tagform = TagForm(instance=tag) tagform.model = tag - elif act in ["view", "edit"]: + elif act in ["view", "edit"]: tag = Tag.objects.get(handle=handle) tagform = TagForm(instance=tag) tagform.model = tag - elif act == "save": + elif act == "save": tag = Tag.objects.get(handle=handle) tagform = TagForm(request.POST, instance=tag) tagform.model = tag @@ -65,7 +65,7 @@ def process_tag(request, context, handle, act, add_to=None): # view, edit, save act = "view" else: act = "edit" - elif act == "create": + elif act == "create": tag = Tag(handle=create_id()) tagform = TagForm(request.POST, instance=tag) tagform.model = tag @@ -82,7 +82,7 @@ def process_tag(request, context, handle, act, add_to=None): # view, edit, save act = "view" else: act = "add" - elif act == "delete": + elif act == "delete": tag = Tag.objects.get(handle=handle) tag.delete() return redirect("/tag/") @@ -93,5 +93,5 @@ def process_tag(request, context, handle, act, add_to=None): # view, edit, save context["object"] = tag context["tag"] = tag context["action"] = act - + return render_to_response(view_template, context) diff --git a/gramps/webapp/libdjango.py b/gramps/webapp/libdjango.py index 9187b82e3..134659c7e 100644 --- a/gramps/webapp/libdjango.py +++ b/gramps/webapp/libdjango.py @@ -50,7 +50,7 @@ from gramps.gen.constfunc import conv_to_unicode # To get a django person from a django database: # djperson = dji.Person.get(handle='djhgsdh324hjg234hj24') -# +# # To turn the djperson into a Gramps Person: # tuple = dji.get_person(djperson) # gperson = lib.gen.Person(tuple) @@ -130,8 +130,8 @@ def get_datamap(grampsclass): class DjangoInterface(object): """ DjangoInterface for interoperating between Gramps and Django. - - This interface comes in a number of parts: + + This interface comes in a number of parts: get_ITEMS() add_ITEMS() @@ -142,7 +142,7 @@ class DjangoInterface(object): add_ITEM(data) Given a Gramps Raw Data tuple, add the data to the Django tables. - + """ def __init__(self): @@ -172,7 +172,7 @@ class DjangoInterface(object): """ ids = [o["gramps_id"] for o in obj.objects.values("gramps_id")] count = 1 - while "%s%04d" % (prefix, count) in ids: + while "%s%04d" % (prefix, count) in ids: count += 1 return "%s%04d" % (prefix, count) @@ -196,7 +196,7 @@ class DjangoInterface(object): def get_attribute_list(self, obj): obj_type = ContentType.objects.get_for_model(obj) - attribute_list = models.Attribute.objects.filter(object_id=obj.id, + attribute_list = models.Attribute.objects.filter(object_id=obj.id, object_type=obj_type) return list(map(self.pack_attribute, attribute_list)) @@ -206,7 +206,7 @@ class DjangoInterface(object): return Name.create(self.pack_name(names[0])) else: return Name() - + def get_alternate_names(self, person): names = person.name_set.filter(preferred=False).order_by("order") return [Name.create(self.pack_name(n)) for n in names] @@ -220,34 +220,34 @@ class DjangoInterface(object): return Name().serialize() else: return list(map(self.pack_name, names)) - - def get_source_attribute_list(self, source): + + def get_source_attribute_list(self, source): return [(map.private, map.key, map.value) for map in source.sourceattribute_set.all().order_by("order")] - def get_citation_attribute_list(self, citation): + def get_citation_attribute_list(self, citation): return [(map.private, map.key, map.value) for map in citation.citationattribute_set.all().order_by("order")] def get_media_list(self, obj): obj_type = ContentType.objects.get_for_model(obj) - mediarefs = models.MediaRef.objects.filter(object_id=obj.id, + mediarefs = models.MediaRef.objects.filter(object_id=obj.id, object_type=obj_type) return list(map(self.pack_media_ref, mediarefs)) def get_note_list(self, obj): obj_type = ContentType.objects.get_for_model(obj) - noterefs = models.NoteRef.objects.filter(object_id=obj.id, + noterefs = models.NoteRef.objects.filter(object_id=obj.id, object_type=obj_type) return [noteref.ref_object.handle for noteref in noterefs] def get_repository_ref_list(self, obj): obj_type = ContentType.objects.get_for_model(obj) - reporefs = models.RepositoryRef.objects.filter(object_id=obj.id, + reporefs = models.RepositoryRef.objects.filter(object_id=obj.id, object_type=obj_type) return list(map(self.pack_repository_ref, reporefs)) def get_place_ref_list(self, obj): obj_type = ContentType.objects.get_for_model(obj) - refs = models.PlaceRef.objects.filter(object_id=obj.id, + refs = models.PlaceRef.objects.filter(object_id=obj.id, object_type=obj_type) return list(map(self.pack_place_ref, refs)) @@ -284,17 +284,17 @@ class DjangoInterface(object): return list(map(self.pack_event_ref, eventrefs)) def get_family_list(self, person): # person has families - return [fam.family.handle for fam in + return [fam.family.handle for fam in models.MyFamilies.objects.filter(person=person).order_by("order")] - + def get_parent_family_list(self, person): # person's parents has families - return [fam.family.handle for fam in + return [fam.family.handle for fam in models.MyParentFamilies.objects.filter(person=person).order_by("order")] def get_person_ref_list(self, person): obj_type = ContentType.objects.get_for_model(person) - return list(map(self.pack_person_ref, - models.PersonRef.objects.filter(object_id=person.id, + return list(map(self.pack_person_ref, + models.PersonRef.objects.filter(object_id=person.id, object_type=obj_type))) def get_lds_list(self, obj): # person or family @@ -314,14 +314,14 @@ class DjangoInterface(object): description = event.description change = totime(event.last_changed) private = event.private - note_list = self.get_note_list(event) - citation_list = self.get_citation_list(event) - media_list = self.get_media_list(event) + note_list = self.get_note_list(event) + citation_list = self.get_citation_list(event) + media_list = self.get_media_list(event) attribute_list = self.get_attribute_list(event) date = self.get_date(event) place_handle = self.get_place_handle(event) tag_list = self.get_tag_list(event) - return (str(handle), gid, the_type, date, description, place_handle, + return (str(handle), gid, the_type, date, description, place_handle, citation_list, note_list, media_list, attribute_list, change, tag_list, private) @@ -332,7 +332,7 @@ class DjangoInterface(object): if markup.string and markup.string.isdigit(): value = int(markup.string) else: - value = markup.string + value = markup.string start_stop_list = markup.start_stop_list ss_list = eval(start_stop_list) retval += [(tuple(markup.styled_text_tag_type), value, ss_list)] @@ -350,13 +350,13 @@ class DjangoInterface(object): styled_text = [note.text, self.get_note_markup(note)] changed = totime(note.last_changed) tag_list = self.get_tag_list(note) - return (str(note.handle), - note.gramps_id, - styled_text, - note.preformatted, - tuple(note.note_type), - changed, - tag_list, + return (str(note.handle), + note.gramps_id, + styled_text, + note.preformatted, + tuple(note.note_type), + changed, + tag_list, note.private) def get_family(self, family): @@ -376,14 +376,14 @@ class DjangoInterface(object): mother_handle = family.mother.handle else: mother_handle = None - return (str(family.handle), family.gramps_id, + return (str(family.handle), family.gramps_id, father_handle, mother_handle, - child_ref_list, tuple(family.family_rel_type), + child_ref_list, tuple(family.family_rel_type), event_ref_list, media_list, - attribute_list, lds_seal_list, + attribute_list, lds_seal_list, citation_list, note_list, - totime(family.last_changed), - tag_list, + totime(family.last_changed), + tag_list, family.private) def get_repository(self, repository): @@ -391,14 +391,14 @@ class DjangoInterface(object): address_list = self.get_address_list(repository, with_parish=False) url_list = self.get_url_list(repository) tag_list = self.get_tag_list(repository) - return (str(repository.handle), - repository.gramps_id, + return (str(repository.handle), + repository.gramps_id, tuple(repository.repository_type), - repository.name, + repository.name, note_list, - address_list, - url_list, - totime(repository.last_changed), + address_list, + url_list, + totime(repository.last_changed), tag_list, repository.private) @@ -413,18 +413,18 @@ class DjangoInterface(object): handle = citation.source.handle else: handle = None - return (str(citation.handle), - citation.gramps_id, + return (str(citation.handle), + citation.gramps_id, date, - citation.page, - citation.confidence, + citation.page, + citation.confidence, handle, - note_list, - media_list, - attribute_list, - totime(citation.last_changed), + note_list, + media_list, + attribute_list, + totime(citation.last_changed), tag_list, - citation.private) + citation.private) def get_source(self, source): note_list = self.get_note_list(source) @@ -432,15 +432,15 @@ class DjangoInterface(object): attribute_list = self.get_source_attribute_list(source) reporef_list = self.get_repository_ref_list(source) tag_list = self.get_tag_list(source) - return (str(source.handle), - source.gramps_id, + return (str(source.handle), + source.gramps_id, source.title, - source.author, + source.author, source.pubinfo, note_list, media_list, source.abbrev, - totime(source.last_changed), + totime(source.last_changed), attribute_list, reporef_list, tag_list, @@ -452,10 +452,10 @@ class DjangoInterface(object): note_list = self.get_note_list(media) tag_list = self.get_tag_list(media) date = self.get_date(media) - return (str(media.handle), - media.gramps_id, + return (str(media.handle), + media.gramps_id, conv_to_unicode(media.path, None), - str(media.mime), + str(media.mime), str(media.desc), media.checksum, attribute_list, @@ -486,40 +486,40 @@ class DjangoInterface(object): tag_list = self.get_tag_list(person) return (str(person.handle), - person.gramps_id, + person.gramps_id, tuple(person.gender_type)[0], - primary_name, - alternate_names, - death_ref_index, - birth_ref_index, - event_ref_list, - family_list, - parent_family_list, - media_list, - address_list, - attribute_list, - url_list, - lds_ord_list, - pcitation_list, - pnote_list, - totime(person.last_changed), - tag_list, - person.private, + primary_name, + alternate_names, + death_ref_index, + birth_ref_index, + event_ref_list, + family_list, + parent_family_list, + media_list, + address_list, + attribute_list, + url_list, + lds_ord_list, + pcitation_list, + pnote_list, + totime(person.last_changed), + tag_list, + person.private, person_ref_list) def get_date(self, obj): if ((obj.calendar == obj.modifier == obj.quality == obj.sortval == obj.newyear == 0) and - obj.text == "" and (not obj.slash1) and (not obj.slash2) and - (obj.day1 == obj.month1 == obj.year1 == 0) and + obj.text == "" and (not obj.slash1) and (not obj.slash2) and + (obj.day1 == obj.month1 == obj.year1 == 0) and (obj.day2 == obj.month2 == obj.year2 == 0)): return None - elif ((not obj.slash1) and (not obj.slash2) and + elif ((not obj.slash1) and (not obj.slash2) and (obj.day2 == obj.month2 == obj.year2 == 0)): dateval = (obj.day1, obj.month1, obj.year1, obj.slash1) else: - dateval = (obj.day1, obj.month1, obj.year1, obj.slash1, + dateval = (obj.day1, obj.month1, obj.year1, obj.slash1, obj.day2, obj.month2, obj.year2, obj.slash2) - return (obj.calendar, obj.modifier, obj.quality, dateval, + return (obj.calendar, obj.modifier, obj.quality, dateval, obj.text, obj.sortval, obj.newyear) def get_placename(self, place): @@ -540,10 +540,10 @@ class DjangoInterface(object): tag_list = self.get_tag_list(place) place_ref_list = self.get_place_ref_list(place) placename = self.get_placename(place) - return (str(place.handle), + return (str(place.handle), place.gramps_id, - place.title, - place.long, + place.title, + place.long, place.lat, place_ref_list, placename, @@ -555,7 +555,7 @@ class DjangoInterface(object): media_list, citation_list, note_list, - totime(place.last_changed), + totime(place.last_changed), tag_list, place.private) @@ -569,14 +569,14 @@ class DjangoInterface(object): def pack_child_ref(self, child_ref): citation_list = self.get_citation_list(child_ref) - note_list = self.get_note_list(child_ref) - return (child_ref.private, citation_list, note_list, child_ref.ref_object.handle, + note_list = self.get_note_list(child_ref) + return (child_ref.private, citation_list, note_list, child_ref.ref_object.handle, tuple(child_ref.father_rel_type), tuple(child_ref.mother_rel_type)) def pack_person_ref(self, personref): citation_list = self.get_citation_list(personref) note_list = self.get_note_list(personref) - return (personref.private, + return (personref.private, citation_list, note_list, personref.ref_object.handle, @@ -591,14 +591,14 @@ class DjangoInterface(object): role = None else: role = (media_ref.x1, media_ref.y1, media_ref.x2, media_ref.y2) - return (media_ref.private, citation_list, note_list, attribute_list, + return (media_ref.private, citation_list, note_list, attribute_list, media_ref.ref_object.handle, role) def pack_repository_ref(self, repo_ref): note_list = self.get_note_list(repo_ref) - return (note_list, + return (note_list, repo_ref.ref_object.handle, - repo_ref.call_number, + repo_ref.call_number, tuple(repo_ref.source_media_type), repo_ref.private) @@ -610,16 +610,16 @@ class DjangoInterface(object): note_list = self.get_note_list(media_ref) attribute_list = self.get_attribute_list(media_ref) citation_list = self.get_citation_list(media_ref) - return (media_ref.private, citation_list, note_list, attribute_list, + return (media_ref.private, citation_list, note_list, attribute_list, media_ref.ref_object.handle, (media_ref.x1, media_ref.y1, media_ref.x2, media_ref.y2)) - + def pack_event_ref(self, event_ref): note_list = self.get_note_list(event_ref) attribute_list = self.get_attribute_list(event_ref) - return (event_ref.private, note_list, attribute_list, + return (event_ref.private, note_list, attribute_list, event_ref.ref_object.handle, tuple(event_ref.role_type)) def pack_citation(self, citation): @@ -636,8 +636,8 @@ class DjangoInterface(object): private = citation.private tag_list = self.get_tag_list(citation) return (handle, gid, date, page, confidence, source_handle, - note_list, media_list, attribute_list, changed, tag_list, - private) + note_list, media_list, attribute_list, changed, tag_list, + private) def pack_address(self, address, with_parish): citation_list = self.get_citation_list(address) @@ -687,17 +687,17 @@ class DjangoInterface(object): date = self.get_date(name) return (name.private, citation_list, note_list, date, name.first_name, name.make_surname_list(), name.suffix, - name.title, tuple(name.name_type), - name.group_as, name.sort_as.val, - name.display_as.val, name.call, name.nick, + name.title, tuple(name.name_type), + name.group_as, name.sort_as.val, + name.display_as.val, name.call, name.nick, name.famnick) def pack_location(self, loc, with_parish): if with_parish: - return ((loc.street, loc.locality, loc.city, loc.county, loc.state, loc.country, + return ((loc.street, loc.locality, loc.city, loc.county, loc.state, loc.country, loc.postal, loc.phone), loc.parish) else: - return (loc.street, loc.locality, loc.city, loc.county, loc.state, loc.country, + return (loc.street, loc.locality, loc.city, loc.county, loc.state, loc.country, loc.postal, loc.phone) def pack_url(self, url): @@ -706,28 +706,28 @@ class DjangoInterface(object): def pack_attribute(self, attribute): citation_list = self.get_citation_list(attribute) note_list = self.get_note_list(attribute) - return (attribute.private, - citation_list, - note_list, - tuple(attribute.attribute_type), + return (attribute.private, + citation_list, + note_list, + tuple(attribute.attribute_type), attribute.value) ## Export lists: - + def add_child_ref_list(self, obj, ref_list): ## Currently, only Family references children for child_data in ref_list: self.add_child_ref(obj, child_data) - + def add_citation_list(self, obj, citation_list): for citation_handle in citation_list: self.add_citation_ref(obj, citation_handle) - + def add_event_ref_list(self, obj, event_ref_list): for event_ref in event_ref_list: self.add_event_ref(obj, event_ref) - + def add_surname_list(self, name, surname_list): order = 1 for data in surname_list: @@ -737,12 +737,12 @@ class DjangoInterface(object): surname.surname = surname_text surname.prefix = prefix surname.primary = primary - surname.name_origin_type = models.get_type(models.NameOriginType, + surname.name_origin_type = models.get_type(models.NameOriginType, origin_type) surname.connector = connector surname.name = name surname.order = order - surname.save() + surname.save() order += 1 def add_note_list(self, obj, note_list): @@ -752,52 +752,52 @@ class DjangoInterface(object): note = models.Note.objects.get(handle=handle) self.add_note_ref(obj, note) except: - print(("ERROR: Note does not exist: '%s'" % + print(("ERROR: Note does not exist: '%s'" % str(handle)), file=sys.stderr) - + def add_alternate_name_list(self, person, alternate_names): for name in alternate_names: if name: self.add_name(person, name, False) - + def add_parent_family_list(self, person, parent_family_list): for parent_family_data in parent_family_list: self.add_parent_family(person, parent_family_data) - + def add_media_ref_list(self, person, media_list): for media_data in media_list: self.add_media_ref(person, media_data) - + def add_attribute_list(self, obj, attribute_list): for attribute_data in attribute_list: self.add_attribute(obj, attribute_data) - + def add_tag_list(self, obj, tag_list): for tag_handle in tag_list: try: tag = models.Tag.objects.get(handle=tag_handle) except: - print(("ERROR: Tag does not exist: '%s'" % + print(("ERROR: Tag does not exist: '%s'" % str(tag_handle)), file=sys.stderr) obj.tags.add(tag) - + def add_url_list(self, field, obj, url_list): if not url_list: return None count = 1 for url_data in url_list: - self.add_url(field, obj, url_data, count) + self.add_url(field, obj, url_data, count) count += 1 - + def add_person_ref_list(self, obj, person_ref_list): for person_ref_data in person_ref_list: self.add_person_ref(obj, person_ref_data) - + def add_address_list(self, field, obj, address_list): count = 1 for address_data in address_list: self.add_address(field, obj, address_data, count) count += 1 - + def add_lds_list(self, field, obj, lds_ord_list): count = 1 for ldsord in lds_ord_list: @@ -805,19 +805,19 @@ class DjangoInterface(object): #obj.lds_list.add(lds) #obj.save() count += 1 - + def add_repository_ref_list(self, obj, reporef_list): for data in reporef_list: self.add_repository_ref(obj, data) - + def add_place_ref_list(self, obj, placeref_list): for data in placeref_list: self.add_place_ref(obj, data) - + def add_family_ref_list(self, person, family_list): for family_handle in family_list: - self.add_family_ref(person, family_handle) - + self.add_family_ref(person, family_handle) + def add_alt_name_list(self, place, alt_name_list): print("FIXME: add alt_name_list!", alt_name_list) @@ -833,7 +833,7 @@ class DjangoInterface(object): person_ref.save() def add_person_ref(self, obj, person_ref_data): - (private, + (private, citation_list, note_list, handle, @@ -841,10 +841,10 @@ class DjangoInterface(object): try: person = models.Person.objects.get(handle=handle) except: - print(("ERROR: Person does not exist: '%s'" % + print(("ERROR: Person does not exist: '%s'" % str(handle)), file=sys.stderr) return - + count = person.references.count() person_ref = models.PersonRef(referenced_by=obj, ref_object=person, @@ -854,20 +854,20 @@ class DjangoInterface(object): person_ref.save() self.add_note_list(person_ref, note_list) self.add_citation_list(person_ref, citation_list) - + def add_note_ref(self, obj, note): count = note.references.count() - note_ref = models.NoteRef(referenced_by=obj, + note_ref = models.NoteRef(referenced_by=obj, ref_object=note, private=False, order=count + 1) note_ref.save() - + def add_media_ref_default(self, obj, media, private=False, role=None): count = media.references.count() if not role: role = (0,0,0,0) - media_ref = models.MediaRef(referenced_by=obj, + media_ref = models.MediaRef(referenced_by=obj, ref_object=media, x1=role[0], y1=role[1], @@ -878,18 +878,18 @@ class DjangoInterface(object): media_ref.save() def add_media_ref(self, obj, media_ref_data): - (private, citation_list, note_list, attribute_list, + (private, citation_list, note_list, attribute_list, ref, role) = media_ref_data try: media = models.Media.objects.get(handle=ref) except: - print(("ERROR: Media does not exist: '%s'" % + print(("ERROR: Media does not exist: '%s'" % str(ref)), file=sys.stderr) return count = media.references.count() if not role: role = (0,0,0,0) - media_ref = models.MediaRef(referenced_by=obj, + media_ref = models.MediaRef(referenced_by=obj, ref_object=media, x1=role[0], y1=role[1], @@ -901,7 +901,7 @@ class DjangoInterface(object): self.add_note_list(media_ref, note_list) self.add_attribute_list(media_ref, attribute_list) self.add_citation_list(media_ref, citation_list) - + def add_citation_ref_default(self, obj, citation, private=False): object_type = ContentType.objects.get_for_model(obj) count = models.CitationRef.objects.filter(object_id=obj.id,object_type=object_type).count() @@ -915,7 +915,7 @@ class DjangoInterface(object): try: citation = models.Citation.objects.get(handle=handle) except: - print(("ERROR: Citation does not exist: '%s'" % + print(("ERROR: Citation does not exist: '%s'" % str(handle)), file=sys.stderr) return @@ -933,9 +933,9 @@ class DjangoInterface(object): citation = models.Citation( handle=handle, gramps_id=gid, - private=private, + private=private, last_changed=todate(changed), - confidence=confidence, + confidence=confidence, page=page) citation.save(save_cache=False) @@ -945,20 +945,20 @@ class DjangoInterface(object): try: citation = models.Citation.objects.get(handle=handle) except: - print(("ERROR: Citation does not exist: '%s'" % + print(("ERROR: Citation does not exist: '%s'" % str(handle)), file=sys.stderr) return try: source = models.Source.objects.get(handle=source_handle) except: - print(("ERROR: Source does not exist: '%s'" % + print(("ERROR: Source does not exist: '%s'" % str(source_handle)), file=sys.stderr) return citation.source = source self.add_date(citation, date) citation.save(save_cache=False) - self.add_note_list(citation, note_list) - self.add_media_ref_list(citation, media_list) + self.add_note_list(citation, note_list) + self.add_media_ref_list(citation, media_list) self.add_citation_attribute_list(citation, attribute_list) self.add_tag_list(citation, tag_list) citation.save_cache() @@ -979,7 +979,7 @@ class DjangoInterface(object): try: child = models.Person.objects.get(handle=ref) except: - print(("ERROR: Person does not exist: '%s'" % + print(("ERROR: Person does not exist: '%s'" % str(ref)), file=sys.stderr) return object_type = ContentType.objects.get_for_model(obj) @@ -993,7 +993,7 @@ class DjangoInterface(object): child_ref.save() self.add_citation_list(child_ref, citation_list) self.add_note_list(child_ref, note_list) - + def add_event_ref_default(self, obj, event, private=False, role=models.EventRoleType._DEFAULT): object_type = ContentType.objects.get_for_model(obj) count = models.EventRef.objects.filter(object_id=obj.id,object_type=object_type).count() @@ -1009,7 +1009,7 @@ class DjangoInterface(object): try: event = models.Event.objects.get(handle=ref) except: - print(("ERROR: Event does not exist: '%s'" % + print(("ERROR: Event does not exist: '%s'" % str(ref)), file=sys.stderr) return object_type = ContentType.objects.get_for_model(obj) @@ -1023,7 +1023,7 @@ class DjangoInterface(object): self.add_note_list(event_ref, note_list) self.add_attribute_list(event_ref, attribute_list) - def add_repository_ref_default(self, obj, repository, private=False, call_number="", + def add_repository_ref_default(self, obj, repository, private=False, call_number="", source_media_type=models.SourceMediaType._DEFAULT): object_type = ContentType.objects.get_for_model(obj) count = models.RepositoryRef.objects.filter(object_id=obj.id,object_type=object_type).count() @@ -1035,17 +1035,17 @@ class DjangoInterface(object): ref_object=repository, order=count + 1) repos_ref.save() - + def add_repository_ref(self, obj, reporef_data): - (note_list, + (note_list, ref, - call_number, + call_number, source_media_type, private) = reporef_data try: repository = models.Repository.objects.get(handle=ref) except: - print(("ERROR: Repository does not exist: '%s'" % + print(("ERROR: Repository does not exist: '%s'" % str(ref)), file=sys.stderr) return object_type = ContentType.objects.get_for_model(obj) @@ -1059,12 +1059,12 @@ class DjangoInterface(object): order=count + 1) repos_ref.save() self.add_note_list(repos_ref, note_list) - + def add_family_ref(self, obj, handle): try: family = models.Family.objects.get(handle=handle) except: - print(("ERROR: Family does not exist: '%s'" % + print(("ERROR: Family does not exist: '%s'" % str(handle)), file=sys.stderr) return #obj.families.add(family) @@ -1072,9 +1072,9 @@ class DjangoInterface(object): order=len(models.MyFamilies.objects.filter(person=obj)) + 1) pfo.save() obj.save() - + ## Export individual objects: - + def add_source_attribute_list(self, source, attribute_list): ## FIXME: dict to list count = 1 @@ -1084,7 +1084,7 @@ class DjangoInterface(object): # datamap.source = source # datamap.save() # count += 1 - + def add_citation_attribute_list(self, citation, attribute_list): ## FIXME: dict to list count = 1 @@ -1094,7 +1094,7 @@ class DjangoInterface(object): # datamap.citation = citation # datamap.save() # count += 1 - + def add_lds(self, field, obj, data, order): (lcitation_list, lnote_list, date, type, place_handle, famc_handle, temple, status, private) = data @@ -1102,7 +1102,7 @@ class DjangoInterface(object): try: place = models.Place.objects.get(handle=place_handle) except: - print(("ERROR: Place does not exist: '%s'" % + print(("ERROR: Place does not exist: '%s'" % str(place_handle)), file=sys.stderr) place = None else: @@ -1111,13 +1111,13 @@ class DjangoInterface(object): try: famc = models.Family.objects.get(handle=famc_handle) except: - print(("ERROR: Family does not exist: '%s'" % + print(("ERROR: Family does not exist: '%s'" % str(famc_handle)), file=sys.stderr) famc = None else: famc = None lds = models.Lds(lds_type = models.get_type(models.LdsType, type), - temple=temple, + temple=temple, place=place, famc=famc, order=order, @@ -1136,14 +1136,14 @@ class DjangoInterface(object): str(field)) lds.save() return lds - + def add_address(self, field, obj, address_data, order): (private, acitation_list, anote_list, date, location) = address_data address = models.Address(private=private, order=order) self.add_date(address, date) address.save() self.add_location("address", address, location, 1) - self.add_note_list(address, anote_list) + self.add_note_list(address, anote_list) self.add_citation_list(address, acitation_list) if field == "person": address.person = obj @@ -1156,7 +1156,7 @@ class DjangoInterface(object): #obj.save() #obj.addresses.add(address) #obj.save() - + def add_attribute(self, obj, attribute_data): (private, citation_list, note_list, the_type, value) = attribute_data attribute_type = models.get_type(models.AttributeType, the_type) @@ -1169,7 +1169,7 @@ class DjangoInterface(object): self.add_note_list(attribute, note_list) #obj.attributes.add(attribute) #obj.save() - + def add_url(self, field, obj, url_data, order): (private, path, desc, type) = url_data url = models.Url(private=private, @@ -1189,7 +1189,7 @@ class DjangoInterface(object): url.save() #obj.url_list.add(url) #obj.save() - + def add_place_ref_default(self, obj, place, date=None): count = place.references.count() object_type = ContentType.objects.get_for_model(obj) @@ -1200,7 +1200,7 @@ class DjangoInterface(object): order=count + 1) self.add_date(obj, date) place_ref.save() - + def add_place_ref(self, obj, data): place_handle, date = data if place_handle: @@ -1221,19 +1221,19 @@ class DjangoInterface(object): try: family = models.Family.objects.get(handle=parent_family_handle) except: - print(("ERROR: Family does not exist: '%s'" % + print(("ERROR: Family does not exist: '%s'" % str(parent_family_handle)), file=sys.stderr) return #person.parent_families.add(family) pfo = models.MyParentFamilies( - person=person, + person=person, family=family, order=len(models.MyParentFamilies.objects.filter(person=person)) + 1) pfo.save() person.save() - + def add_date(self, obj, date): - if date is None: + if date is None: (calendar, modifier, quality, text, sortval, newyear) = \ (0, 0, 0, "", 0, 0) day1, month1, year1, slash1 = 0, 0, 0, 0 @@ -1261,14 +1261,14 @@ class DjangoInterface(object): obj.month2 = month2 obj.year2 = year2 obj.slash2 = slash2 - + def add_name(self, person, data, preferred): if data: (private, citation_list, note_list, date, first_name, surname_list, suffix, title, - name_type, group_as, sort_as, + name_type, group_as, sort_as, display_as, call, nick, famnick) = data - + count = person.name_set.count() name = models.Name() name.order = count + 1 @@ -1287,15 +1287,15 @@ class DjangoInterface(object): # we know person exists # needs to have an ID for key name.person = person - self.add_date(name, date) + self.add_date(name, date) name.save() self.add_surname_list(name, surname_list) self.add_note_list(name, note_list) self.add_citation_list(name, citation_list) #person.save() - + ## Export primary objects: - + def add_person(self, data): # Unpack from the BSDDB: (handle, # 0 @@ -1320,7 +1320,7 @@ class DjangoInterface(object): private, # 19 person_ref_list, # 20 ) = data - + person = models.Person(handle=handle, gramps_id=gid, last_changed=todate(change), @@ -1352,23 +1352,23 @@ class DjangoInterface(object): private, # 19 person_ref_list, # 20 ) = data - + try: person = models.Person.objects.get(handle=handle) except: - print(("ERROR: Person does not exist: '%s'" % + print(("ERROR: Person does not exist: '%s'" % str(handle)), file=sys.stderr) return if primary_name: self.add_name(person, primary_name, True) self.add_alternate_name_list(person, alternate_names) self.add_event_ref_list(person, event_ref_list) - self.add_family_ref_list(person, family_list) + self.add_family_ref_list(person, family_list) self.add_parent_family_list(person, parent_family_list) self.add_media_ref_list(person, media_list) self.add_note_list(person, pnote_list) self.add_attribute_list(person, attribute_list) - self.add_url_list("person", person, url_list) + self.add_url_list("person", person, url_list) self.add_person_ref_list(person, person_ref_list) self.add_citation_list(person, pcitation_list) self.add_address_list("person", person, address_list) @@ -1378,8 +1378,8 @@ class DjangoInterface(object): obj_type = ContentType.objects.get_for_model(person) events = models.EventRef.objects.filter( - object_id=person.id, - object_type=obj_type, + object_id=person.id, + object_type=obj_type, ref_object__event_type__val=models.EventType.BIRTH).order_by("order") all_events = self.get_event_ref_list(person) @@ -1388,8 +1388,8 @@ class DjangoInterface(object): person.birth_ref_index = lookup_role_index(models.EventType.BIRTH, all_events) events = models.EventRef.objects.filter( - object_id=person.id, - object_type=obj_type, + object_id=person.id, + object_type=obj_type, ref_object__event_type__val=models.EventType.DEATH).order_by("order") if events: person.death = events[0].ref_object @@ -1404,15 +1404,15 @@ class DjangoInterface(object): for markup in markup_list: markup_code, value, start_stop_list = markup m = models.Markup( - note=note, - order=count, + note=note, + order=count, styled_text_tag_type=models.get_type(models.StyledTextTagType, - markup_code, + markup_code, get_or_create=False), string=value, start_stop_list=str(start_stop_list)) m.save() - + def add_note(self, data): # Unpack from the BSDDB: (handle, gid, styled_text, format, note_type, @@ -1427,7 +1427,7 @@ class DjangoInterface(object): note_type=models.get_type(models.NoteType, note_type)) n.save(save_cache=False) self.save_note_markup(n, markup_list) - + def add_note_detail(self, data): # Unpack from the BSDDB: (handle, gid, styled_text, format, note_type, @@ -1443,10 +1443,10 @@ class DjangoInterface(object): child_ref_list, the_type, event_ref_list, media_list, attribute_list, lds_seal_list, citation_list, note_list, change, tag_list, private) = data - - family = models.Family(handle=handle, gramps_id=gid, + + family = models.Family(handle=handle, gramps_id=gid, family_rel_type = models.get_type(models.FamilyRelType, the_type), - last_changed=todate(change), + last_changed=todate(change), private=private) family.save(save_cache=False) @@ -1456,11 +1456,11 @@ class DjangoInterface(object): child_ref_list, the_type, event_ref_list, media_list, attribute_list, lds_seal_list, citation_list, note_list, change, tag_list, private) = data - + try: family = models.Family.objects.get(handle=handle) except: - print(("ERROR: Family does not exist: '%s'" % + print(("ERROR: Family does not exist: '%s'" % str(handle)), file=sys.stderr) return # father_handle and/or mother_handle can be None @@ -1468,14 +1468,14 @@ class DjangoInterface(object): try: family.father = models.Person.objects.get(handle=father_handle) except: - print(("ERROR: Father does not exist: '%s'" % + print(("ERROR: Father does not exist: '%s'" % str(father_handle)), file=sys.stderr) family.father = None if mother_handle: try: family.mother = models.Person.objects.get(handle=mother_handle) except: - print(("ERROR: Mother does not exist: '%s'" % + print(("ERROR: Mother does not exist: '%s'" % str(mother_handle)), file=sys.stderr) family.mother = None family.save(save_cache=False) @@ -1488,7 +1488,7 @@ class DjangoInterface(object): self.add_lds_list("family", family, lds_seal_list) self.add_tag_list(family, tag_list) family.save_cache() - + def add_source(self, data): (handle, gid, title, author, pubinfo, @@ -1517,24 +1517,24 @@ class DjangoInterface(object): try: source = models.Source.objects.get(handle=handle) except: - print(("ERROR: Source does not exist: '%s'" % + print(("ERROR: Source does not exist: '%s'" % str(handle)), file=sys.stderr) return source.save(save_cache=False) - self.add_note_list(source, note_list) + self.add_note_list(source, note_list) self.add_media_ref_list(source, media_list) self.add_source_attribute_list(source, attribute_list) self.add_repository_ref_list(source, reporef_list) self.add_tag_list(source, tag_list) source.save_cache() - + def add_repository(self, data): (handle, gid, the_type, name, note_list, address_list, url_list, change, tag_list, private) = data - + repository = models.Repository(handle=handle, gramps_id=gid, - last_changed=todate(change), + last_changed=todate(change), private=private, repository_type=models.get_type(models.RepositoryType, the_type), name=name) @@ -1546,7 +1546,7 @@ class DjangoInterface(object): try: repository = models.Repository.objects.get(handle=handle) except: - print(("ERROR: Repository does not exist: '%s'" % + print(("ERROR: Repository does not exist: '%s'" % str(handle)), file=sys.stderr) return repository.save(save_cache=False) @@ -1555,7 +1555,7 @@ class DjangoInterface(object): self.add_address_list("repository", repository, address_list) self.add_tag_list(repository, tag_list) repository.save_cache() - + def add_location(self, field, obj, location_data, order): # location now has 8 items # street, locality, city, county, state, @@ -1568,7 +1568,7 @@ class DjangoInterface(object): elif len(location_data) == 2: ((street, locality, city, county, state, country, postal, phone), parish) = location_data else: - print(("ERROR: unknown location: '%s'" % + print(("ERROR: unknown location: '%s'" % str(location_data)), file=sys.stderr) (street, locality, city, county, state, country, postal, phone, parish) = \ ("", "", "", "", "", "", "", "", "") @@ -1592,9 +1592,9 @@ class DjangoInterface(object): location.save() #obj.locations.add(location) #obj.save() - + def add_place(self, data): - ## ('cef246c95c132bcf6a0255d4d17', 'P0036', ('Santa Clara Co., CA, USA', DATE, "English"), + ## ('cef246c95c132bcf6a0255d4d17', 'P0036', ('Santa Clara Co., CA, USA', DATE, "English"), ## '', '', [('cef243fb5634559442323368f63', None)], 'Santa Clara Co.', [], (3, ''), '', [], [], [], [], [], 1422124781, [], False) (handle, gid, title, long, lat, place_ref_list, @@ -1607,19 +1607,19 @@ class DjangoInterface(object): media_list, citation_list, note_list, - change, + change, tag_list, private) = data place = models.Place( - handle=handle, - gramps_id=gid, + handle=handle, + gramps_id=gid, title=title, - long=long, - lat=lat, + long=long, + lat=lat, name=placename, lang=placelang, - place_type=models.get_type(models.PlaceType, place_type), - code=code, + place_type=models.get_type(models.PlaceType, place_type), + code=code, last_changed=todate(change), private=private) try: @@ -1639,21 +1639,21 @@ class DjangoInterface(object): media_list, citation_list, note_list, - change, + change, tag_list, private) = data try: place = models.Place.objects.get(handle=handle) except: - print(("ERROR: Place does not exist: '%s'" % + print(("ERROR: Place does not exist: '%s'" % str(handle)), file=sys.stderr) return - self.add_date(place, date) + self.add_date(place, date) place.save(save_cache=False) self.add_url_list("place", place, url_list) self.add_media_ref_list(place, media_list) self.add_citation_list(place, citation_list) - self.add_note_list(place, note_list) + self.add_note_list(place, note_list) self.add_tag_list(place, tag_list) self.add_place_ref_list(place, place_ref_list) self.add_alt_name_list(place, alt_name_list) @@ -1676,7 +1676,7 @@ class DjangoInterface(object): priority=priority, last_changed=todate(change)) tag.save(save_cache=False) - + def add_tag_detail(self, data): (handle, name, @@ -1702,7 +1702,7 @@ class DjangoInterface(object): private=private) self.add_date(media, date) media.save(save_cache=False) - + def add_media_detail(self, data): (handle, gid, path, mime, desc, checksum, @@ -1716,22 +1716,22 @@ class DjangoInterface(object): try: media = models.Media.objects.get(handle=handle) except: - print(("ERROR: Media does not exist: '%s'" % + print(("ERROR: Media does not exist: '%s'" % str(handle)), file=sys.stderr) return media.save(save_cache=False) - self.add_note_list(media, note_list) + self.add_note_list(media, note_list) self.add_citation_list(media, citation_list) self.add_attribute_list(media, attribute_list) self.add_tag_list(media, tag_list) media.save_cache() - + def add_event(self, data): - (handle, gid, the_type, date, description, place_handle, + (handle, gid, the_type, date, description, place_handle, citation_list, note_list, media_list, attribute_list, change, tag_list, private) = data event = models.Event(handle=handle, - gramps_id=gid, + gramps_id=gid, event_type=models.get_type(models.EventType, the_type), private=private, description=description, @@ -1740,20 +1740,20 @@ class DjangoInterface(object): event.save(save_cache=False) def add_event_detail(self, data): - (handle, gid, the_type, date, description, place_handle, + (handle, gid, the_type, date, description, place_handle, citation_list, note_list, media_list, attribute_list, change, tag_list, private) = data try: event = models.Event.objects.get(handle=handle) except: - print(("ERROR: Event does not exist: '%s'" % + print(("ERROR: Event does not exist: '%s'" % str(handle)), file=sys.stderr) return try: place = models.Place.objects.get(handle=place_handle) except: place = None - print(("ERROR: Place does not exist: '%s'" % + print(("ERROR: Place does not exist: '%s'" % str(place_handle)), file=sys.stderr) event.place = place event.save(save_cache=False) @@ -1794,14 +1794,14 @@ class DjangoInterface(object): """ Call this to check the caches for all primary models. """ - if not isinstance(callback, collections.Callable): + if not isinstance(callback, collections.Callable): callback = lambda percent: None # dummy callback(0) count = 0.0 - total = (self.Note.all().count() + + total = (self.Note.all().count() + self.Person.all().count() + - self.Event.all().count() + + self.Event.all().count() + self.Family.all().count() + self.Repository.all().count() + self.Place.all().count() + @@ -1898,7 +1898,7 @@ class DjangoInterface(object): why/why not. @param obj - an instance of any Primary object - @param objref - one of the PrimaryRef.objects + @param objref - one of the PrimaryRef.objects @return - a tuple containing a boolean (public?) and reason. There are three reasons why an item might not be public: @@ -1958,7 +1958,7 @@ class DjangoInterface(object): if obj.__class__.__name__ == "Event": objref = self.EventRef elif obj.__class__.__name__ == "Person": - objref = self.PersonRef + objref = self.PersonRef elif obj.__class__.__name__ == "Note": objref = self.NoteRef elif obj.__class__.__name__ == "Repository": @@ -1995,14 +1995,14 @@ class DjangoInterface(object): """ Call this to update probably_alive for all primary models. """ - if not isinstance(callback, collections.Callable): + if not isinstance(callback, collections.Callable): callback = lambda percent: None # dummy callback(0) count = 0.0 - total = (self.Note.all().count() + + total = (self.Note.all().count() + self.Person.all().count() + - self.Event.all().count() + + self.Event.all().count() + self.Family.all().count() + self.Repository.all().count() + self.Place.all().count() + @@ -2060,7 +2060,7 @@ class DjangoInterface(object): Call this to update primary_alive for people. """ from gramps.webapp.utils import probably_alive - if not isinstance(callback, collections.Callable): + if not isinstance(callback, collections.Callable): callback = lambda percent: None # dummy callback(0) count = 0.0 diff --git a/gramps/webapp/modules_checkpoint.py b/gramps/webapp/modules_checkpoint.py index 330138905..a690a2502 100644 --- a/gramps/webapp/modules_checkpoint.py +++ b/gramps/webapp/modules_checkpoint.py @@ -3,7 +3,7 @@ import sys class ModulesCheckpoint(object): def __init__(self): self.original = sys.modules.copy() - + def reset(self): # clear modules: for key in list(sys.modules.keys()): diff --git a/gramps/webapp/reports.py b/gramps/webapp/reports.py index f5cf175d6..347c79de8 100644 --- a/gramps/webapp/reports.py +++ b/gramps/webapp/reports.py @@ -96,7 +96,7 @@ def download(url, filename=None): def getFilename(url,openUrl): if 'Content-Disposition' in openUrl.info(): # If the response has Content-Disposition, try to get filename from it - cd = dict([x.strip().split('=') if '=' in x else (x.strip(),'') + cd = dict([x.strip().split('=') if '=' in x else (x.strip(),'') for x in openUrl.info().split(';')]) if 'filename' in cd: fname = cd['filename'].strip("\"'") diff --git a/gramps/webapp/urls.py b/gramps/webapp/urls.py index 8c2d735ac..2be960618 100644 --- a/gramps/webapp/urls.py +++ b/gramps/webapp/urls.py @@ -37,7 +37,7 @@ from django.contrib import admin admin.autodiscover() -from gramps.webapp.grampsdb.views import * +from gramps.webapp.grampsdb.views import * urlpatterns = patterns('', # Specific matches first: @@ -67,10 +67,10 @@ urlpatterns += patterns('', urlpatterns += patterns('', (r'^$', main_page), ## Prior to django 1.5, use this: - ##(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', + ##(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', ##{'url': '/styles/images/favicon.ico'}), # Django 1.5.4: - (r'^favicon\.ico$', 'django.shortcuts.redirect', + (r'^favicon\.ico$', 'django.shortcuts.redirect', {'url': '/styles/images/favicon.ico'}), (r'^user/$', user_page), (r'^json/$', process_json_request), @@ -78,32 +78,32 @@ urlpatterns += patterns('', (r'^browse/$', browse_page), (r'^login/$', 'django.contrib.auth.views.login'), (r'^logout/$', logout_page), - (r'^(?P(\w+))/$', + (r'^(?P(\w+))/$', view_list), # /view/ - (r'^(?P(\w+))/add$', + (r'^(?P(\w+))/add$', action, {"handle": None, "act": "add"}), # /view/add - (r'^(?P(\w+))/add/(?P(\w+))/(?P(\w+))$', + (r'^(?P(\w+))/add/(?P(\w+))/(?P(\w+))$', add_to), # /view/add/item/handle - (r'^(?P(\w+))/share/(?P(\w+))/(?P(\w+))$', + (r'^(?P(\w+))/share/(?P(\w+))/(?P(\w+))$', add_share), # /view/share/item/handle - (r'^(?P(\w+))/(?P(\w+))/$', action, + (r'^(?P(\w+))/(?P(\w+))/$', action, {"act": "view"}), # /view/handle/ - (r'^(?P(\w+))/(?P(\w+))/(?P(\w+))$', - action), # /view/handle/action - (r'^(?P(\w+))/(?P(\w+))/reference/(?P(\w+))/(?P(\w+))$', + (r'^(?P(\w+))/(?P(\w+))/(?P(\w+))$', + action), # /view/handle/action + (r'^(?P(\w+))/(?P(\w+))/reference/(?P(\w+))/(?P(\w+))$', process_reference), # /view/handle/reference/item/order - (r'^person/(?P(\w+))/name/(?P(\w+))$', process_name), - (r'^person/(?P(\w+))/name/(?P(\w+))/(?P(\w+))$', + (r'^person/(?P(\w+))/name/(?P(\w+))$', process_name), + (r'^person/(?P(\w+))/name/(?P(\w+))/(?P(\w+))$', process_name), - (r'^person/(?P(\w+))/name/(?P(\w+))/surname/(?P(\w+))$', + (r'^person/(?P(\w+))/name/(?P(\w+))/surname/(?P(\w+))$', process_surname), - (r'^person/(?P(\w+))/name/(?P(\w+))/surname/(?P(\w+))/(?P(\w+))$', + (r'^person/(?P(\w+))/name/(?P(\w+))/surname/(?P(\w+))/(?P(\w+))$', process_surname), (r'^family/(?P(\w+))/(?P(\w+))/child/(?P(\w+))$', process_child), ## (r'^profile/(?P(\w+)/)$', ), - (r'^(?P(\w+))/(?P(\w+))/(?P(\w+))/(?P(\w+))/(?P(\w+))$', + (r'^(?P(\w+))/(?P(\w+))/(?P(\w+))/(?P(\w+))/(?P(\w+))$', process_list_item), (r'^note/(?P(\w+))/person/(?P(\w+))/name/(?P(\w+))$', process_note_on_name),