forked from gramps-project/addons-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDescendantsLines.py
1816 lines (1580 loc) · 70.5 KB
/
DescendantsLines.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2010 Adam Sampson <[email protected]>
# Copyright (C) 2010 Jerome Rapinat <[email protected]>
# Copyright (C) 2010, 2012 lcc <[email protected]>
# Copyright (C) 2015 Don Piercy
# Copyright (C) 2020 Giansalvo Gusinu <[email protected]>
#
# 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
# 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,
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# This program is based on the program located at
# http://offog.org/darcs/misccode/familytree. The license for that
# program is found at http://offog.org/darcs/misccode/NOTES.
# Distributed under the terms of the X11 license:
#
# Copyright 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
# 2008, 2009, 2010, 2011 Adam Sampson <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL ADAM SAMPSON BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
"""
Descendants Lines - Generate a Descendant's Tree Chart - Graphic plugin for
GRAMPS
Can display the Name, Image and selected Events for the head person and all
descendants. Events may include, type, date, place & description, formatted as
per the options menu. Each person is linked by connection lines showing
families (Spouse(s) & any children)
"""
#-------------------------------------------------------------------------
#
# python modules
#
#-------------------------------------------------------------------------
import re
import cairo
import os.path
#-------------------------------------------------------------------------
#
# gramps modules
#
#-------------------------------------------------------------------------
import gramps.gen.datehandler
from gramps.gen.plug.menu import (TextOption, NumberOption, PersonOption,
DestinationOption, BooleanOption,
EnumeratedListOption, StringOption)
from gramps.gen.plug.report import Report
from gramps.gen.plug.report import utils as ReportUtils
from gramps.gen.plug.report import MenuReportOptions
from gramps.gen.utils.thumbnails import get_thumbnail_path # for images
from gramps.gen.utils.file import media_path_full
from gramps.gen.const import GRAMPS_LOCALE as glocale
try:
_trans = glocale.get_addon_translator(__file__)
except ValueError:
_trans = glocale.translation
_ = _trans.gettext
from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle,
FONT_SANS_SERIF, PARA_ALIGN_LEFT)
from gramps.gen.display.name import displayer as name_displayer
from gramps.gen.const import USER_HOME
import gramps.gen.lib
from gramps.plugins.lib.libtreebase import * # for CalcLines
from gramps.plugins.lib.libsubstkeyword import SubstKeywords
from substkw import SubstKeywords2 # Modified version of libsubstkeywords.py
from gramps.gen.lib.eventtype import EventType # for selecting event types
from gramps.gen.lib.eventroletype import EventRoleType # for PRIMARY, FAMILY
# for sorting events with unknown dates
from gramps.gen.lib.date import NextYear
from gramps.gen.filters import GenericFilterFactory, rules
#-------------------------------------------------------------------------
#
# Set up Logging
#
#-------------------------------------------------------------------------
import logging
log = logging.getLogger("DescendantsLines")
#-------------------------------------------------------------------------
#
# variables
#
#-------------------------------------------------------------------------
S_DOWN = 20
S_UP = 10
S_VPAD = 10
FL_PAD = 20
OL_PAD = 10
O_DOWN = 30
C_PAD = 10
F_PAD = 20
C_UP = 15
SP_PAD = 10
MIN_C_WIDTH = 40
TEXT_PAD = 2
TEXT_LINE_PAD = 2
OUTPUT_FMT = 'PNG'
OUTPUT_FN = None
gender_colors = False
INC_PLACES = False
INC_MARRIAGES = False
INC_DNUM = False
MAX_GENERATION = 0
TEXT_ALIGNMENT = 'center' # 'center', 'left'
STROKE_RECTANGLE = False
same_width = True
same_height = True
MARGIN_HEADER = 100 # Margin used for the header. In pixels
MARGIN_FOOTER = 100 # Margin used for the footer. In pixels
MARGIN_LEFT = 100 # Left margin
MARGIN_RIGHT = 100 # Right margin
# global variables used in conjunction with same_width/same_height options
global first_pass
global max_image_width
global max_image_height
global max_text_width
global max_text_height
# Static variable for do_person()
CUR_GENERATION = 0
global HIGH_GENERATION # tracks the highest generation in chart, used for
# fill colour generation
HIGH_GENERATION = 0
# extra Padding for STROKE_RECTANGLE == True
RECTANGLE_TEXT_PAD = 1
IMAGE_PAD = 2
global BACKGROUND_COLOR
global FOREGROUND_COLOR
BACKGROUND_COLOR = (1.0, 1.0, 1.0)
FOREGROUND_COLOR = (1.0, 1.0, 1.0)
LINE_DARKNESS = 256
GRAMPS_DB = None
INC_IMAGE = True
MAX_IMAGE_H = 0
MAX_IMAGE_W = 0
IMAGE_LOC = None
REPLACEMENT_LIST = None
ctx = None
font_name = 'sans-serif'
base_font_size = 12
_event_cache = {}
def find_event(database, handle):
if handle in _event_cache:
obj = _event_cache[handle]
else:
obj = database.get_event_from_handle(handle)
_event_cache[handle] = obj
return obj
def event_type(event_name):
""" returns the event types number if it matches the event_name string """
for i in range(0, len(EventType._DATAMAP)):
if event_name.capitalize() == EventType._DATAMAP[i][2]:
return(EventType._DATAMAP[i][0])
return(None)
def parse_event_disp(line):
"""
Parse an event display option line
convert the text event names into DB event types
[event_type_list](event_format)
"""
etl = []
ef = ''
r = re.search(r'(?P<el>\[[\w, ]*\])(?P<ef>.*)', line)
if r:
x = r.group('el')
y = x.replace(' ', '')
el = y[1:-1].split(',')
if el:
for event_name in el:
etype = event_type(event_name)
log.debug(' Parse Event=%s ET=%s', event_name, etype)
if etype:
etl.append(etype)
else:
log.warning('Event type "%s" NOT found', event_name)
ef = r.group('ef')
log.debug(' Parsed event display list=%s, fmt=%s', etl, ef)
return(etl, ef)
class DescendantsLinesReport(Report):
"""
DescendantsLines Report class - Initialized and write_report are called by
GRAMPS's report plugin feature
"""
def __init__(self, database, options_class, user):
"""
Create the object that produces the report.
The arguments are:
database - the GRAMPS database instance
options_class - instance of the Options class for this report
user - a gen.user.User() instance
This report needs the following parameters (class variables)
that come in the options class.
S_DOWN - The length of the vertical edge from descendant to spouse-bar
S_UP - The length of the vertical edge from spouse-bar to spouse
S_VPAD - Vertical space spouse-bar to other spouse
FL_PAD - Horizontal distance spouse to family edge
OL_PAD -
O_DOWN - The length of the vertical edge from spouse-bar to child-bar
C_PAD - Children distance
F_PAD - Horizonal space family to family
C_UP - The length of the vertical edge from child to child-bar
SP_PAD - Horizontal space descendant to spouse
MIN_C_WIDTH -
TEXT_PAD- Space around text
TEXT_LINE_PAD - Space between lines of text
output_fmt - The output format
output_fn - The output filename
max_gen - Maximum number of generations to include. (0 for unlimited)
gender_colors - Whether to use colored names indicating person gender
in the output.
name_disp - The name format
inc_dnum - Whether to use d'Aboville descendant numbering system
style - The predefined output style
inc_image - Include an image
replace_list - Replacement list
same_width -All Person's blocks have the same width
same_height-All Person's blocks have the same height
"""
Report.__init__(self, database, options_class, user)
self.options = {}
menu = options_class.menu
self.database = database
global GRAMPS_DB
GRAMPS_DB = database
#log.debug('dB= %s', GRAMPS_DB)
for name in menu.get_all_option_names():
self.options[name] = menu.get_option_by_name(name).get_value()
global S_DOWN
global S_UP
global S_VPAD
global FL_PAD
global OL_PAD
global O_DOWN
global C_PAD
global F_PAD
global C_UP
global SP_PAD
global MIN_C_WIDTH
global TEXT_PAD
global TEXT_LINE_PAD
global _event_cache
S_DOWN = self.options["S_DOWN"]
S_UP = self.options["S_UP"]
S_VPAD = self.options["S_VPAD"]
FL_PAD = self.options["FL_PAD"]
OL_PAD = self.options["OL_PAD"]
O_DOWN = self.options["O_DOWN"]
C_PAD = self.options["C_PAD"]
F_PAD = self.options["F_PAD"]
C_UP = self.options["C_UP"]
SP_PAD = self.options["SP_PAD"]
MIN_C_WIDTH = self.options["MIN_C_WIDTH"]
TEXT_PAD = self.options["TEXT_PAD"]
TEXT_LINE_PAD = self.options["TEXT_LINE_PAD"]
_event_cache = {}
self.output_fmt = self.options['output_fmt']
self.output_fn = self.options['output_fn']
self.output_fn = '%s.%s' % (os.path.splitext(self.output_fn)[0],
self.output_fmt.lower())
self.max_gen = self.options['max_gen']
self.gender_colors = self.options['gender_colors']
self.inc_dnum = self.options['inc_dnum']
global OUTPUT_FMT
global OUTPUT_FN
global MAX_GENERATION
global GENDER_COLORS
global FILL_COLORS
global TEXT_ALIGNMENT
global STROKE_RECTANGLE
global same_width
global same_height
global MAX_NOTE_LEN
global INC_DNUM
OUTPUT_FMT = self.output_fmt
OUTPUT_FN = self.output_fn
MAX_GENERATION = self.max_gen
GENDER_COLORS = self.gender_colors
FILL_COLORS = self.options['fill_colors']
TEXT_ALIGNMENT = self.options['text_alignment']
STROKE_RECTANGLE = self.options['stroke_rectangle']
same_width = self.options['same_width']
same_height = self.options['same_height']
MAX_NOTE_LEN = self.options['max_note_len']
INC_DNUM = self.inc_dnum
global INC_IMAGE
global MAX_IMAGE_H
global MAX_IMAGE_W
global IMAGE_LOC
global REPLACEMENT_LIST
INC_IMAGE = self.options['inc_image']
MAX_IMAGE_H = float(self.options['image_h'])
MAX_IMAGE_W = float(self.options['image_w'])
IMAGE_LOC = self.options['image_loc']
REPLACEMENT_LIST = self.options['replace_list']
global DESCEND_ALPHA
global SPOUSE_ALPHA
DESCEND_ALPHA = self.options['descend_alpha']
SPOUSE_ALPHA = self.options['spouse_alpha']
#LINE_ALPHA = constant for now (see above)
global PROTECT_PRIVATE
PROTECT_PRIVATE = self.options['protect_private']
global PRIVATE_TEXT
PRIVATE_TEXT = self.options['private_text']
global NAME_FORMAT
NAME_FORMAT = self.options['name_disp']
global OR_SIMILAR_EVENTS
OR_SIMILAR_EVENTS = {
EventType.BIRTH: (EventType.BIRTH, EventType.BAPTISM,
EventType.CHRISTEN),
EventType.DEATH: (EventType.DEATH, EventType.BURIAL,
EventType.CREMATION, EventType.PROBATE),
EventType.MARRIAGE: (EventType.MARRIAGE, EventType.MARR_LIC,
EventType.ENGAGEMENT),
EventType.DIVORCE: (EventType.DIVORCE, EventType.ANNULMENT,
EventType.DIV_FILING)}
global FAMILY_EVENTS
FAMILY_EVENTS = [EventType.MARRIAGE, EventType.MARR_LIC,
EventType.ENGAGEMENT, EventType.DIVORCE,
EventType.ANNULMENT, EventType.DIV_FILING]
global OR_SIMILAR
OR_SIMILAR = self.options['or_similar_events']
global SORT_EVENTS
SORT_EVENTS = self.options['sort_events']
# used in sorting to move events with unknown dates to end
# (not used for birth related events)
global FUTUREDATE
FUTUREDATE = NextYear()
global DESCEND_DISP
DESCEND_DISP = []
for line in self.options['descend_disp']:
#log.debug('ReportInit: Descendant Line=%s', line)
DESCEND_DISP.append(parse_event_disp(line))
log.debug('ReportInit: DESCEND_DISP=%s', DESCEND_DISP)
global SPOUSE_DISP
SPOUSE_DISP = []
for line in self.options['spouse_disp']:
#log.debug('ReportInit: Spouse Line=%s', line)
SPOUSE_DISP.append(parse_event_disp(line))
log.debug('ReportInit: SPOUSE_DISP=%s', SPOUSE_DISP)
# increase text pad to allow for box's line
if STROKE_RECTANGLE:
TEXT_PAD += RECTANGLE_TEXT_PAD
self.title = menu.get_option_by_name('title').get_value()
self.footer = menu.get_option_by_name('footer').get_value()
self.header_coeff = menu.get_option_by_name('header_coeff').get_value()
def write_report(self):
"""
This routine actually creates the report.
At this point, the document is opened and ready for writing.
"""
pid = self.options_class.menu.get_option_by_name('pid').get_value()
log.debug('Top PID=%s', pid)
# Creates dummy drawing context for image sizing during creation of
# tree:
init_file(None, PNGWriter())
# calculate max_box_width, max_box_height, max_image_width,
# max_image_height
global first_pass
global max_image_width
global max_image_height
global max_text_width
global max_text_height
first_pass = True
max_text_width = 0
max_text_height = 0
max_image_height = 0
max_image_width = 0
p1 = load_gramps(pid) #TODO p1 can be disposed after this call
# Generates a tree of person records and the family linkages for the
# chart:
first_pass = False
p = load_gramps(pid)
# traverses tree and generates the chart with "person" boxes and the
# "family" relationship lines.
draw_file(p, self.output_fn, PNGWriter(), self.title, self.footer, self.header_coeff)
# Matches all that is used currently, families might be collected later
filter_class = GenericFilterFactory('Person')
filter = filter_class()
filter.add_rule(rules.person.IsDescendantFamilyOf([pid, 1]))
plist = self.database.get_person_handles(sort_handles=True)
if PROTECT_PRIVATE:
import gramps.gen.proxy
self.database = gramps.gen.proxy.PrivateProxyDb(self.database)
ind_list = filter.apply(self.database, plist)
# writes textual informations on secondary output file
if self.options_class.handler.format_name == 'svg':
self._user.warn(_("Using SVG type for supplemental document is"
" not supported!"))
return
for person_handle in ind_list:
person = self.database.get_person_from_handle(person_handle)
#log.debug(person_handle)
self.doc.start_paragraph("DL-name")
if person:
mark = ReportUtils.get_person_mark(self.database, person)
name = person.get_primary_name()
surname = name.get_surname()
firstname = name.get_first_name()
self.doc.write_text(surname + ' ' + firstname, mark)
else:
from gramps.gen.config import config
PRIVATE_RECORD_TEXT = config.get(
'preferences.private-record-text')
self.doc.write_text(PRIVATE_TEXT + PRIVATE_RECORD_TEXT)
self.doc.end_paragraph()
self.doc.start_paragraph("DL-name")
self.doc.write_text('%s people' % len(ind_list))
self.doc.end_paragraph()
def draw_text(text, x, y, total_w, top_centered_lines=0):
"""
Draw the block if text at the specified location.
Total width defines the block's width to allow centering.
Top_centered_lines overrides the Text alignment set in options menu for
the specified # of lines. This allows centering of the first line
containing the user's name
"""
#(total_w, total_h) = size_text(text, ctx)
n = 1
for (size, color, line) in text:
ctx.select_font_face(font_name)
ctx.set_font_size(base_font_size * size)
(ascent, _, height, _, _) = ctx.font_extents()
(lx, _, width, _, _, _,) = ctx.text_extents(line)
if ((TEXT_ALIGNMENT == 'center') or (n <= top_centered_lines)):
ctx.move_to(MARGIN_LEFT + x - lx + (total_w - width + lx) / 2, y +
ascent + TEXT_PAD + MARGIN_HEADER)
elif TEXT_ALIGNMENT == 'left':
ctx.move_to(MARGIN_LEFT + x - lx + TEXT_PAD, y + ascent + TEXT_PAD + MARGIN_HEADER)
else:
raise AttributeError("DT: no such text alignment: '%s'" %
TEXT_ALIGNMENT)
ctx.set_source_rgb(*color)
ctx.show_text(line)
y += height + TEXT_LINE_PAD
n += 1
def draw_header_footer(x, y, line, coeff):
ctx.select_font_face(font_name)
ctx.set_font_size(base_font_size * coeff)
(ascent, _, height, _, _) = ctx.font_extents()
(lx, _, width, _, _, _,) = ctx.text_extents(line)
total_w = 0
ctx.move_to(MARGIN_LEFT +x - lx + (total_w - width + lx) / 2,
y + ascent)
ctx.show_text(line)
def size_text(text, cntx):
text_width = 0
text_height = 0
first = True
for (size, color, line) in text:
if first:
first = False
else:
text_height += TEXT_LINE_PAD
cntx.select_font_face(font_name)
cntx.set_font_size(base_font_size * size)
(_, _, height, _, _) = cntx.font_extents()
(lx, _, width, _, _, _,) = cntx.text_extents(line)
text_width = max(text_width, width - lx)
text_height += height
text_width += 2 * TEXT_PAD
text_height += 2 * TEXT_PAD
return (text_width, text_height)
def calc_image_scale(iw, ih):
"""
Calculate the scaling factor for the image to fit the Max size set in the
Options
The Max height & width from the Options are MAX_IMAGE_H & MAX_IMAGE_W
a value of 0 means there is no limit in that direction.
"""
if MAX_IMAGE_H == 0:
if MAX_IMAGE_W == 0:
return 1.0
else:
return MAX_IMAGE_W / iw
else:
if MAX_IMAGE_W == 0:
return MAX_IMAGE_H / ih
else:
# log.debug('Calc Scale, min of H=%f, W=%f',
# MAX_IMAGE_H/ih, MAX_IMAGE_W/iw)
return min(MAX_IMAGE_W / iw, MAX_IMAGE_H / ih)
def size_image(image_path):
"""
Gets the size of the image
Need to use a dummy CTX (dctx) as using the final ctx to get this
information seems to ruin the final image.
"""
dctx.save()
iw = 0
ih = 0
image = cairo.ImageSurface.create_from_png(image_path)
if image:
iw = cairo.ImageSurface.get_width(image)
ih = cairo.ImageSurface.get_height(image)
log.debug('Image Size (unscaled): height=%d width=%d', ih, iw)
dctx.restore()
return (iw, ih)
def draw_image(image_path, ix, iy, iw, ih, scale_factor):
# log.debug('Draw Image at x=%d y=%d, w=%d, h=%d, to be scaled by %d',
# ix, iy, iw, ih, scale_factor)
ctx.save()
image = cairo.ImageSurface.create_from_png(image_path)
if scale_factor != 1.0:
log.debug('Draw Image: scale factor=%f; result: H=%f, W=%f',
scale_factor, ih, iw)
ctx.scale(scale_factor, scale_factor)
ctx.set_source_surface(image, (ix + IMAGE_PAD) / scale_factor,
(iy + IMAGE_PAD) / scale_factor)
ctx.paint()
ctx.restore()
def get_image(phandle):
"""
Searches through a person's media and returns the first usable image.
If the Privacy menu option is enabled, it will return the first
non-private image.
It will create a thumbnail image (PNG) if one does not exist.
These currently default to a Maximum size of 96x96.
"""
imagePath = None
if GRAMPS_DB is None:
log.error('get_image: No DataBase to get images from!')
else:
p = GRAMPS_DB.get_person_from_handle(phandle)
if PROTECT_PRIVATE and p.private:
log.debug('get_image: Private Person %s',
p.primary_name.get_regular_name())
return(None)
else:
mediaList = p.get_media_list()
for media_item in mediaList:
mediaHandle = media_item.get_reference_handle()
media = GRAMPS_DB.get_media_from_handle(mediaHandle)
if not (PROTECT_PRIVATE and media.private):
mediaMimeType = media.get_mime_type()
if mediaMimeType[0:5] == "image":
rect = media_item.get_rectangle()
# this will create a .PNG thumbnail ("NORMAL" size) if
# one does not exist.
# rect is the user defined section of the original
# image (TL x,y & BR x,y {1..100})
imagePath = get_thumbnail_path(
media_path_full(GRAMPS_DB, media.get_path()),
rectangle=rect)
if imagePath.endswith('/image-missing.png'):
imagePath = None # skip GRAMPS image-missing icon
log.warning('get_image: %s has Missing Image',
p.primary_name.get_regular_name())
else:
break # found the first image
if imagePath:
log.debug('get_image, imagePath: %s',
imagePath.replace(USER_HOME + '/gramps/thumb/', ''))
else:
log.debug('get_image: No Media found for: %s',
p.primary_name.get_regular_name())
return(imagePath)
class Person_Block:
"""
This class holds information to be displayed about a person (text, image
location) and how to display it (widths & heights, image scaling)
"""
def __init__(self, phandle, text):
self.text = text # array of tuples containing text.
self.phandle = phandle # to access image
self.iw = 0.0 # Image Width (initially unscaled, then scaled)
self.ih = 0.0 # Image Height (initially unscaled, then scaled)
self.tw = 0.0 # Text Width
self.th = 0.0 # Text Height
self.boxw = 0.0 # Box (containing image & text) Width
self.boxh = 0.0 # Box Height
self.ipath = None # Path to (thumbnail) image
self.iscale = 1.0 # Scaling factor to use on thumbnail image
(self.tw, self.th) = size_text(self.text, dctx)
if INC_IMAGE and (phandle is not None):
self.ipath = get_image(self.phandle)
if self.ipath:
(self.iw, self.ih) = size_image(self.ipath)
self.iscale = calc_image_scale(self.iw, self.ih)
self.iw = self.iw * self.iscale + 2 * IMAGE_PAD
self.ih = self.ih * self.iscale + 2 * IMAGE_PAD
log.debug('PBlk: Have image for %s, p_handle=%s',
self.text[0][2], self.phandle)
# log.debug('PBlk: imagePath: %s',
# self.ipath.replace(USER_PATH + '/gramps/thumb/',
# ''))
if IMAGE_LOC == 'Above Text':
self.boxw = max(self.tw , self.iw)
self.boxh = self.th + self.ih
elif IMAGE_LOC == 'Left of Text':
self.boxw = self.tw + self.iw
self.boxh = max(self.th, self.ih)
else:
log.warning('PBlk: Image location not valid: %s', IMAGE_LOC)
else:
self.boxw = self.tw
self.boxh = self.th
# log.debug('PBlk Width: bw=%d, tw=%d, iw=%d',
# self.boxw, self.tw, self.iw)
# log.debug('PBlk Height: bh=%d, th=%d, ih=%d',
# self.boxh, self.th, self.ih)
global max_image_width
global max_image_height
global max_text_width
global max_text_height
if first_pass:
max_image_width = max(max_image_width, self.iw)
max_image_height = max(max_image_height, self.ih)
max_text_width = max(max_text_width, self.tw)
max_text_height = max(max_text_height, self.th)
else:
if same_width:
if IMAGE_LOC == 'Above Text':
self.boxw = max(max_text_width , max_image_width)
elif IMAGE_LOC == 'Left of Text':
self.boxw = max_text_width + max_image_width
else:
log.warning('PBlk: Image location not valid: %s', IMAGE_LOC)
self.tw = max_text_width
self.iw = max_image_width
if same_height:
if IMAGE_LOC == 'Above Text':
self.boxh = max_text_height + max_image_height
elif IMAGE_LOC == 'Left of Text':
self.boxh = max(max_text_height, max_image_height)
else:
log.warning('PBlk: Image location not valid: %s', IMAGE_LOC)
self.th = max_text_height
self.ih = max_image_height
def __str__(self):
return (self.text[0] + '_PBlk')
mem_depth = 0
class Memorised:
def get(self, name):
try:
getattr(self, '_memorised')
except:
self._memorised = {}
global mem_depth
mem_depth += 1
if name in self._memorised:
#cached = '*'
v = self._memorised[name]
else:
#cached = ' '
v = getattr(self, name)()
self._memorised[name] = v
mem_depth -= 1
return v
class Person(Memorised):
"""
This class is for each person in the descendants chart and contains:
- linkages for the descendants tree (families, from family,
prevsib, next sib)
- information to be displayed about the person (text, ipath)
- how to display it (generation, widths & heights, image scaling
"""
def __init__(self, pblk, gen):
self.text = pblk.text # lines of text (tuples of str, colour and size)
self.ipath = pblk.ipath
self.iscale = pblk.iscale # to scale thumbnail image using cario
# for chart sizing and alignment:
self.boxw = pblk.boxw # width of box containing text & image
self.boxh = pblk.boxh
self.iw = pblk.iw # image width (scaled)
self.ih = pblk.ih
self.tw = pblk.tw # text width
self.th = pblk.th
self.generation = gen # for background colour
self.families = []
self.from_family = None
self.prevsib = None
self.nextsib = None
def __str__(self):
return '[' + self.text + ']'
def add_family(self, fam):
if self.families != []:
self.families[-1].nextfam = fam
fam.prevfam = self.families[-1]
self.families.append(fam)
def draw(self):
#set_bg_style(ctx)
#ctx.set_source_rgba(1, 0, 0, 0.1) #very pale red
#ctx.rectangle(self.get('x'), self.get('y'), self.get('w'),
# self.get('h'))
#ctx.fill()
ixo = 0.0 # image X blockoffset from box's top left corner
iyo = 0.0 # image Y blockoffset
txo = 0.0 # text X blockoffset
tyo = 0.0 # text Y blockoffset
if INC_IMAGE is True:
if IMAGE_LOC == 'Above Text':
ixo = (self.boxw - self.iw) / 2
#iyo = 0
txo = (self.boxw - self.tw) / 2
tyo = self.ih
elif IMAGE_LOC == 'Left of Text':
#ixo = 0
iyo = (self.boxh - self.ih) / 2
txo = self.iw
tyo = (self.boxh - self.th) / 2
else:
log.warning('PD: Image location not valid: %s', IMAGE_LOC)
log.debug('PD: Draw descendant %s Gen:%d',
self.text[0][2], self.generation)
# log.debug('PD: bw=%d, get.bw=%d, tw=%d, iw=%d, x=%d, ixo=%d, txo=%d,'
# ' get.tx=%d', self.boxw, self.get('bw'), self.tw, self.iw,
# self.get('x'), ixo, txo, self.get('tx'))
# log.debug('PD: bh=%d, get.bh=%d, th=%d, ih=%d, y=%d, ixo=%d, txo=%d',
# self.boxh, self.get('bh'), self.th, self.ih, self.get('y'),
# iyo, tyo)
#set_fg_style(ctx)
if FILL_COLORS:
set_gen_style(ctx, self.generation, DESCEND_ALPHA)
else:
set_fg_style(ctx)
ctx.rectangle(MARGIN_LEFT + self.get('tx'), self.get('y') + MARGIN_HEADER, self.boxw, self.boxh)
if STROKE_RECTANGLE is True:
ctx.fill_preserve()
set_line_style(ctx)
ctx.stroke()
else:
ctx.fill()
draw_text(self.text, self.get('tx') + txo, self.get('y') + tyo,
self.tw, top_centered_lines=1)
if self.ipath != None:
# log.debug('PD: imagePath: %s', self.ipath.replace(
# '/Users/ndpiercy/Library/Application Support/gramps/thumb/',
# ''))
draw_image(self.ipath, MARGIN_LEFT + self.get('tx') + ixo, self.get('y') + iyo + MARGIN_HEADER,
self.iw, self.ih, self.iscale)
for f in self.families:
f.draw()
def x(self):
if self.from_family is None:
return 0
else:
return self.from_family.get('cx') + self.get('o')
def tx(self):
return (self.get('x') + self.get('go')) - self.get('bw') / 2
def y(self):
if self.from_family is None:
return 0
else:
return self.from_family.get('cy')
def bw(self):
return self.boxw
def bh(self):
return self.boxh
def glh(self):
total = 0
for f in self.families:
total += f.get('glh')
return total
def o(self):
if self.prevsib is None:
return 0
else:
return self.prevsib.get('o') + self.prevsib.get('w') + C_PAD
def ch(self):
biggest = 0
for f in self.families:
if f.get('ch') > biggest:
biggest = f.get('ch')
return biggest + O_DOWN + C_UP if biggest else 0
def w(self):
w = self.get('go') + self.get('bw') / 2
w = max(w, MIN_C_WIDTH)
if self.families != []:
ff = self.families[0]
to_sp = self.get('go') + ff.get('flw')
w = max(w, to_sp + ff.spouse.get('bw') / 2)
w = max(w, (to_sp - FL_PAD + ff.get('cw')) - ff.get('oloc'))
return w
def h(self):
return self.get('bh') + self.get('glh') + self.get('ch')
def go(self):
go = self.get('bw') / 2
if self.families != []:
lf = self.families[-1]
if lf.children != []:
go = max(go, lf.get('oloc') - (lf.get('flw') - FL_PAD))
return go
def to(self):
return self.get('go') - self.get('bw') / 2
def glx(self):
return self.get('x') + self.get('go')
class Family(Memorised):
def __init__(self, main, spouse):
self.main = main
self.spouse = spouse
self.children = []
self.prevfam = None
self.nextfam = None
main.add_family(self)
#self.generation = None
self.generation = self.main.generation
def __str__(self):
return '(:' + str(self.main) + '+' + str(self.spouse) + ':)'
def add_child(self, child):
if self.children != []:
self.children[-1].nextsib = child
child.prevsib = self.children[-1]
self.children.append(child)
child.from_family = self
def draw(self):
#(px, py) = (self.main.get('x'), self.main.get('y'))
# set_line_style(ctx)
# Draw lines between spouse(s) for each "family"
set_gen_style(ctx, self.generation, LINE_DARKNESS)
ctx.set_dash([20, 5])
ctx.new_path()
# center bottom of "Descendant" box
ctx.move_to(MARGIN_LEFT + self.get('glx'), self.get('gly') + MARGIN_HEADER)
ctx.rel_line_to(0, self.get('glh'))
ctx.rel_line_to(self.get('flw'), 0)
# to center bottom of "Spouse" box
ctx.rel_line_to(0, -S_UP)
ctx.stroke()
ctx.set_dash([]) # restore line style to non-dash
ixo = 0 # image X blockoffset from box
iyo = 0 # image Y blockoffset from box
txo = 0 # text X blockoffset from box
tyo = 0 # text Y blockoffset from box
if INC_IMAGE is True:
if IMAGE_LOC == 'Above Text':
ixo = (self.spouse.boxw - self.spouse.iw) / 2
#iyo = 0
txo = (self.spouse.boxw - self.spouse.tw) / 2
tyo = self.spouse.ih
elif IMAGE_LOC == 'Left of Text':
#ixo = 0
iyo = (self.spouse.boxh - self.spouse.ih) / 2
txo = self.spouse.iw
tyo = (self.spouse.boxh - self.spouse.th) / 2
else:
log.warning('FD: Image location not valid: %s', IMAGE_LOC)
log.debug('FD: Draw Fam/Sp %s Gen:%d',
self.spouse.text[0][2], self.generation)
# log.debug('FD: bw=%d, get.bw=%d, tw=%d, iw=%d, spx=%d, ixo=%d,'
# ' txo=%d', self.spouse.boxw, self.spouse.get('bw'),
# self.spouse.tw, self.spouse.iw, self.get('spx'), ixo, txo)
# log.debug('FD: bh=%d, get.bh=%d, th=%d, ih=%d, spy=%d, ixo=%d,'
# ' txo=%d', self.spouse.boxh, self.spouse.get('bh'),
# self.spouse.th, self.spouse.ih, self.get('spy'), iyo, tyo)
# log.debug('FD: glx=%d, gly=%d, glh=%d, flw=%d', self.get('glx'),
# self.get('gly'), self.get('glh'), self.get('flw'))
if FILL_COLORS:
set_gen_style(ctx, self.generation, SPOUSE_ALPHA)
else:
set_fg_style(ctx)
ctx.rectangle(MARGIN_LEFT + self.get('spx'), self.get('spy') + MARGIN_HEADER,
self.spouse.boxw, self.spouse.boxh)
if STROKE_RECTANGLE is True:
ctx.fill_preserve()
set_line_style(ctx)
ctx.stroke()
else:
ctx.fill()