-
Notifications
You must be signed in to change notification settings - Fork 28
/
countersheet.py
executable file
·2606 lines (2288 loc) · 86.3 KB
/
countersheet.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
#!/usr/bin/env python3
# Code format using:
# black --line-length 79 countersheet.py
# (https://github.com/psf/black)
# Copyright 2008-2023 Pelle Nilsson and contributors
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
import inkex
from inkex import NSS
from inkex.base import SvgOutputMixin
from inkex.command import inkscape
import csv
import fnmatch
import re
import os
import os.path
import lxml
from lxml import etree
from copy import deepcopy
import sys
from tempfile import mkstemp
import subprocess
NSS["cs"] = "http://www.hexandcounter.org/countersheetsextension/"
# A bit of a hack because of rounding errors sometimes
# making boxes not fill up properly.
# There should be a better fix.
BOX_MARGIN = 2.0
# Hardcoded (for now?) what DPI to use for
# some non-vector content in exported PDF.
PDF_DPI = 300
DEFAULT_REGISTRATION_MARK_STYLE = "stroke:#aaa"
DEFAULT_FOLDING_LINE_STYLE = "stroke:#aaa;stroke-dasharray:0.9,0.15;"
def popen3(cmd):
p = subprocess.Popen(
cmd,
shell=True,
universal_newlines=True,
close_fds=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return p.communicate()
class Counter:
def __init__(self, repeat):
self.repeat = repeat
self.parts = []
self.subst = {}
self.back = None
self.id = None
self.endbox = False
self.endrow = False
self.hasback = False
self.attrs = {}
self.excludeids = []
self.includeids = []
self.bleed_up = []
self.bleed_left = []
self.elements = [] # generated top-level groups
self.width = 0 # actual width when generated
self.height = 0 # actual height when generated
self.bleed_added = {}
def can_add_another(self):
return self.repeat.can_add_another()
def added_one(self, last_on_row, last_in_box, last_on_sheet):
self.repeat.added_one(last_on_row, last_in_box, last_on_sheet)
def set(self, setting):
setting.applyto(self)
def addpart(self, id):
self.parts.append(id)
def excludeid(self, id):
self.excludeids.append(id)
def includeid(self, id):
self.includeids.append(id)
def addattr(self, id, attribute, source):
if not id in self.attrs:
self.attrs[id] = {}
self.attrs[id][attribute] = source
def addsubst(self, name, value):
self.subst[name] = value
def doublesided(self):
if not self.back:
self.back = Counter(DummyRepeat())
return self.back
def is_included(self, eid):
if eid is None:
return True
for iglob in self.includeids:
if fnmatch.fnmatchcase(eid, iglob):
return True
for eglob in self.excludeids:
if fnmatch.fnmatchcase(eid, eglob):
return False
return True
class CounterSettingHolder:
def __init__(self):
self.copytoback = False
self.setting = NoSetting()
self.back = False
def setcopytoback(self):
self.copytoback = True
return self
def setback(self):
self.back = True
def set(self, setting):
self.setting = setting
def applyto(self, counter):
self.setting.applyto(counter)
if self.copytoback:
back = counter.doublesided()
self.setting.applyto(back)
class DummyRepeat:
def can_add_another(self):
return False
def added_one(self, last_on_row, last_in_box, last_on_sheet):
pass
class Repeat:
def __init__(self, nr):
self.nr = nr
self.keep_going = True
def can_add_another(self):
return self.nr > 0 or self.keep_going
class RepeatExact(Repeat):
def added_one(self, last_on_row, last_in_box, last_on_sheet):
self.nr -= 1
self.keep_going = False
class RepeatMinFillRow(Repeat):
def added_one(self, last_on_row, last_in_box, last_on_sheet):
self.nr -= 1
if last_on_row and self.nr <= 0:
self.keep_going = False
class RepeatMinFillBox(Repeat):
def added_one(self, last_on_row, last_in_box, last_on_sheet):
self.nr -= 1
if last_in_box and self.nr <= 0:
self.keep_going = False
class RepeatMinFillSheet(Repeat):
def added_one(self, last_on_row, last_in_box, last_on_sheet):
self.nr -= 1
if last_on_sheet and self.nr <= 0:
self.keep_going = False
class BleedMaker:
def __init__(self, svg, defs):
self.defs = defs
self.bleed_added = {}
self.unbleed = {}
def getbleed(
self, width, height, bleed_up, bleed_left, bleed_down, bleed_right
):
"""
Create a clippath rectangle in svg defs and return its name.
Or just return the name if it already exists.
Note that with the current implementation there is always
bleed drawn below and to the right of every counter.
That is almost always the correct thing to do. Possibly
always for all practical purposes. Except on counter
backs where left and right are exchanged, so they will
always have bleed_left, but not always bleed_right.
Leaving this generic enough to handle clip-paths extended
in all directions since it is not a huge additional
effort anyway to handle 3 instead of 4 directions.
"""
name = "bleed_%dx%d_%r_%r_%r_%r" % (
width,
height,
bleed_up,
bleed_left,
bleed_down,
bleed_right,
)
existing = self.defs.xpath(
"svg:clipPath[@id='%s']" % name, namespaces=NSS
)
if len(existing) == 0:
clipPath = etree.Element(inkex.addNS("clipPath", "svg"))
clipPath.set("id", name)
rect = etree.Element(inkex.addNS("rect", "svg"))
x1 = 0
y1 = 0
x2 = width
y2 = height
if bleed_up:
y1 -= height
if bleed_left:
x1 -= width
if bleed_down:
y2 += height
if bleed_right:
x2 += width
rect.set("x", str(min(x1, x2)))
rect.set("y", str(min(y1, y2)))
rect.set("width", str(abs(x1 - x2)))
rect.set("height", str(abs(y1 - y2)))
clipPath.append(rect)
self.defs.append(clipPath)
return name
def add_bleed_to(self, counters):
for counter in counters:
front_unbleed = self.getbleed(
counter.width, counter.height, False, False, False, False
)
for i, element in enumerate(counter.elements):
bleedclip = self.getbleed(
counter.width,
counter.height,
counter.bleed_up[i],
counter.bleed_left[i],
True,
True,
)
self.setclip(element, bleedclip)
self.bleed_added[element] = bleedclip
self.unbleed[bleedclip] = front_unbleed
if counter.hasback:
back_unbleed = self.getbleed(
counter.back.width,
counter.back.height,
False,
False,
False,
False,
)
for i, element in enumerate(counter.back.elements):
back_bleedclip = self.getbleed(
counter.back.width,
counter.back.height,
counter.bleed_up[i],
True,
True,
counter.bleed_left[i],
)
self.setclip(element, back_bleedclip)
self.bleed_added[element] = back_bleedclip
self.unbleed[back_bleedclip] = back_unbleed
def setclip(self, element, clip):
element.set("clip-path", "url(#%s)" % clip)
def hideall(self):
for element, clip in self.bleed_added.items():
self.setclip(element, self.unbleed[clip])
def showall(self):
for element, clip in self.bleed_added.items():
self.setclip(element, clip)
class NoSetting:
def applyto(self, counter):
pass
class CounterPart:
def __init__(self, id):
self.id = id
def applyto(self, counter):
counter.addpart(self.id)
class CounterExcludeID:
def __init__(self, id):
self.id = id
self.exceptions = set()
def addexception(self, id):
self.exceptions.add(id)
def applyto(self, counter):
counter.excludeid(self.id)
for e in self.exceptions:
counter.includeid(e)
class CounterAttribute:
def __init__(self, id, attribute, source):
self.id = id
self.attribute = attribute
self.source = source
def applyto(self, counter):
counter.addattr(self.id, self.attribute, self.source)
class CounterSubst:
def __init__(self, name, value):
self.name = name
self.value = value
def applyto(self, counter):
counter.addsubst(self.name, self.value)
class CounterID:
def __init__(self, id):
self.id = id
def applyto(self, counter):
counter.id = self.id
class Rectangle:
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
class CountersheetEffect(inkex.Effect, SvgOutputMixin):
def __init__(self):
inkex.Effect.__init__(self)
self.log = False
self.nextid = 1000000
self.arg_parser.add_argument("-,", "--name")
self.arg_parser.add_argument("-l", "--log", type=str, dest="logfile")
self.arg_parser.add_argument(
"-n", "--suffix", type=str, dest="suffix", default="", help="Name"
)
self.arg_parser.add_argument(
"-N", "--sheets-bitmap-name", dest="bitmapname", default=""
) # undocumented, for svgtests
self.arg_parser.add_argument(
"-d",
"--data",
type=str,
dest="datafile",
default="countersheet.csv",
help="CSV or XML data file.",
)
self.arg_parser.add_argument(
"-I",
"--imagedir",
type=str,
dest="imagedir",
default="",
help="Base path to external images",
)
self.arg_parser.add_argument(
"-w",
"--bitmapw",
type=int,
dest="bitmapwidth",
default="56",
help="ID bitmap width",
)
self.arg_parser.add_argument(
"-F",
"--rotatefronts",
type=int,
dest="rotatefronts",
default="0",
help="Rotate Fronts (degrees)",
)
self.arg_parser.add_argument(
"-G",
"--rotatebacks",
type=int,
dest="rotatebacks",
default="0",
help="Rotate Backs (degrees)",
)
self.arg_parser.add_argument(
"-y",
"--bitmaph",
type=int,
dest="bitmapheight",
default="56",
help="Number of columns.",
)
self.arg_parser.add_argument(
"-f",
"--bitmapsheetsdpi",
type=int,
dest="bitmapsheetsdpi",
default="0",
)
self.arg_parser.add_argument(
"-b", "--bitmapdir", type=str, dest="bitmapdir"
)
self.arg_parser.add_argument("-p", "--pdfdir", type=str, dest="pdfdir")
self.arg_parser.add_argument(
"-r",
"--registrationmarkslen",
type=str,
default="",
dest="registrationmarkslen",
)
self.arg_parser.add_argument(
"-z",
"--registrationmarksdist",
type=str,
default="",
dest="registrationmarksdist",
)
self.arg_parser.add_argument(
"-R",
"--fullregistrationmarks",
dest="fullregistrationmarks",
default="false",
)
self.arg_parser.add_argument(
"-D",
"--registrationmarksbothsides",
dest="registrationmarksbothsides",
default="false",
)
self.arg_parser.add_argument(
"-O", "--outlinedist", type=str, dest="outlinedist", default=""
)
self.arg_parser.add_argument(
"-S", "--spacing", type=str, dest="spacing", default="0"
)
self.arg_parser.add_argument(
"-i",
"--inlineimagesizepercent",
type=int,
dest="inlineimagesizepercent",
default="200",
)
self.arg_parser.add_argument(
"-P",
"--inlineimageplaceholder",
type=str,
dest="inlineimageplaceholder",
default="X",
)
self.arg_parser.add_argument(
"-s",
"--inlineimageoffset",
type=float,
dest="inlineimageoffset",
default="0.20",
)
self.arg_parser.add_argument(
"-m", "--textmarkup", dest="textmarkup", default="true"
)
self.arg_parser.add_argument(
"-B", "--bleed", dest="bleed", default="false"
)
self.arg_parser.add_argument(
"-1", "--onlyone", default="false", dest="onlyone"
)
self.arg_parser.add_argument(
"-o", "--oneside", default="false", dest="oneside"
)
self.arg_parser.add_argument(
"-L", "--foldingline", default="false", dest="foldingline"
)
self.arg_parser.add_argument(
"-X", "--backoffsetx", default="0mm", dest="backoffsetx"
)
self.arg_parser.add_argument(
"-Y", "--backoffsety", default="0mm", dest="backoffsety"
)
self.translatere = re.compile("translate[(]([-0-9.]+),([-0-9.]+)[)]")
self.matrixre = re.compile(
"(matrix[(](?:[-0-9.]+,){4})([-0-9.]+),([-0-9.]+)[)]"
)
self.placeholders = {}
self.nr_styles_added = 0
def logwrite(self, msg):
logfile = self.options.logfile
if not self.log and logfile and not os.path.isdir(logfile):
self.log = open(logfile, "w")
if self.log:
try:
self.log.write(msg)
except UnicodeEncodeError:
self.log.write(msg.encode("utf8"))
def replaceattrs(self, elements, attrs):
for n in elements:
id = n.get("id")
if not id:
continue
for glob, attr in attrs.items():
if fnmatch.fnmatchcase(id, glob):
for a, v in attr.items():
if a.startswith("style:"):
pname = a[6:]
a = "style"
v = stylereplace(n.get(a), pname, v)
if ":" in a:
[ns, tag] = a.split(":")
a = inkex.addNS(tag, ns)
n.set(a, v)
def translate_element(self, element, dx, dy, append=False):
self.logwrite("translate_element %f,%f\n" % (dx, dy))
translate = "translate(%f,%f)" % (dx, dy)
old_transform = element.get("transform")
if old_transform and append:
self.logwrite("old transform append: %s\n" % old_transform)
element.set("transform", old_transform + " " + translate)
elif old_transform:
self.logwrite("old transform prepend: %s\n" % old_transform)
element.set("transform", translate + " " + old_transform)
else:
element.set("transform", translate)
def rotate_element(self, element, degrees, width, height):
if degrees == 0:
return
rotate = "rotate(%f,%f,%f)" % (degrees, width / 2.0, height / 2.0)
if degrees == 90 or degrees == -90:
rotate_xshift = (height - width) / 2.0
rotate_yshift = (width - height) / 2.0
rotate = "translate(%f,%f) %s" % (
rotate_xshift,
rotate_yshift,
rotate,
)
old_transform = element.get("transform")
if old_transform:
element.set("transform", old_transform + " " + rotate)
else:
element.set("transform", rotate)
def translate_use_element(self, use, old_ref, new_ref):
self.logwrite("translate_use_element %s %s\n" % (old_ref, new_ref))
old_element = self.document.xpath(
"//*[@id='%s']" % old_ref, namespaces=NSS
)[0]
new_elements = self.document.xpath(
"//*[@id='%s']" % new_ref, namespaces=NSS
)
if len(new_elements) < 1:
sys.exit("Failed to find new clone target: %s" % new_ref)
new_element = new_elements[0]
(old_x, old_y) = self.find_reasonable_center_xy(old_element)
(new_x, new_y) = self.find_reasonable_center_xy(new_element)
self.logwrite(
" use data: old %f,%f new %f,%f\n" % (old_x, old_y, new_x, new_y)
)
self.translate_element(use, old_x - new_x, old_y - new_y, True)
def find_reasonable_center_xy(self, element):
rect = self.geometry[element.get("id")]
return (rect.x + rect.w / 2.0, rect.y + rect.h / 2.0)
def setMultilineFlowRoot(self, element, name, lines):
self.logwrite("setting multiline flowRoot: %s\n" % lines)
for c in element.getchildren():
if c.tag == inkex.addNS("flowPara", "svg"):
style = c.get("style")
if style is not None:
self.logwrite(" found flowPara style: " + style)
element_style = element.get("style")
if element_style:
combstyle = dict(inkex.Style.parse_str(element_style))
else:
combstyle = {}
combstyle.update(inkex.Style.parse_str(style))
element.set("style", str(inkex.Style(combstyle)))
break
else:
self.logwrite(" found flowPara without style")
self.deleteTextChildren(element)
added_style = {}
for line in lines:
para = etree.Element(inkex.addNS("flowLine", "svg"))
self.setFormattedText(
para,
name,
line,
"flowSpan",
added_style,
inkex.Style.parse_str(element.get("style")),
)
element.append(para)
def setMultilineText(self, element, name, lines):
self.logwrite("setting multiline text: %s\n" % lines)
self.deleteTextChildren(element)
added_style = {}
tspan = etree.Element(inkex.addNS("tspan", "svg"))
joined_lines = "\n".join(lines)
self.setFormattedText(
tspan,
name,
joined_lines,
"tspan",
added_style,
inkex.Style.parse_str(element.get("style")),
)
element.append(tspan)
def deleteTextChildren(self, parent):
for c in parent.getchildren():
if c.tag != inkex.addNS("flowRegion", "svg"):
parent.remove(c)
def setFormattedText(
self, element, name, text, spantag, added_style, styles
):
self.logwrite(
"setFormattedText: %s %s %s %s\n"
% (element.tag, text, spantag, styles)
)
if not self.textmarkup:
element.text = text
return
first_bold = text.find("*")
first_italics = text.find("/")
second_bold = text.find("*", first_bold + 1)
second_italics = text.find("/", first_italics + 1)
self.logwrite(
"first_bold: %d, first_italics: %d, "
"second_bold: %d, second_italics: %d\n"
% (first_bold, first_italics, second_bold, second_italics)
)
skip = False
if (
first_italics > first_bold
and second_bold > first_italics
and second_italics > second_bold
or first_bold > first_italics
and second_italics > first_bold
and second_bold > second_italics
):
self.logwrite(
"Bad nesting bold/italics (skip format): %s\n" % text
)
skip = True
if first_bold >= 0 and second_bold < 0:
self.logwrite("Single bold-mark (*) (skip format): %s\n" % text)
skip = True
if first_italics >= 0 and second_italics < 0:
self.logwrite("Single italics-mark (/) (skip format): %s\n" % text)
skip = True
if (
not skip
and first_bold >= 0
and second_bold > first_bold
and (first_italics < 0 or first_bold < first_italics)
):
self.formatTextPart(
element,
name,
text,
spantag,
first_bold,
second_bold,
"font-weight",
"bold",
added_style,
"b",
styles,
)
elif (
not skip
and first_italics >= 0
and second_italics > first_italics
and (first_bold < 0 or first_italics < first_bold)
):
self.formatTextPart(
element,
name,
text,
spantag,
first_italics,
second_italics,
"font-style",
"italic",
added_style,
"i",
styles,
)
else:
self.formatTextImages(
element, name, text, spantag, added_style, styles
)
def formatTextImages(
self, element, name, text, spantag, added_style, styles
):
m = re.search(r"[{][^{}]+[}]", text)
if m:
self.logwrite("Inline image: %s\n" % m.group(0))
self.insertImagePlaceholder(
element,
name,
text,
spantag,
m.start(),
m.end() - 1,
added_style,
styles,
)
else:
element.text = text
def insertImagePlaceholder(
self,
element,
name,
text,
spantag,
begin_index,
end_index,
added_style,
styles,
):
filename = text[begin_index + 1 : end_index]
if spantag != "tspan":
sys.exit(
"Failed to insert inlined image %s "
"in a %s element (size: %d%%). Unfortunately only "
"one-line text elements can have inlined "
"images for boring technical reasons. "
"Perhaps in a future version of Inkscape "
"it will be possible to add support for "
"inlined images in (flowing) multi-line "
"text elements."
% (
filename,
spantag,
self.options.inlineimagesizepercent,
self.options.inlineimageplaceholder,
)
)
span = etree.Element(inkex.addNS(spantag, "svg"))
if "image" in added_style:
nr = added_style["image"] + 1
else:
nr = 1
spanid = "%s-%d-cs-image-%s" % (name, len(self.placeholders), nr)
span.set("id", spanid)
span.text = self.options.inlineimageplaceholder
span.set(
"style",
"font-size: %d%%;fill-opacity:0;"
"font-style:normal;font-weight:normal;"
"font-variant:normal;font-family:sans-serif;"
% self.options.inlineimagesizepercent,
)
self.logwrite("inline image placeholder: %s %s\n" % (spanid, filename))
self.placeholders[spanid] = {
"parent": element,
"span": span,
"filename": filename,
}
restspan = etree.Element(inkex.addNS(spantag, "svg"))
resttext = text[end_index + 1 :]
self.setFormattedText(
restspan, name, resttext, spantag, added_style, styles
)
element.text = text[:begin_index]
element.append(span)
element.append(restspan)
def formatTextPart(
self,
element,
name,
text,
spantag,
begin_index,
end_index,
style,
style_value,
added_style,
style_tag,
styles,
):
if style_tag in added_style:
nr = added_style[style_tag] + 1
else:
nr = 1
added_style[style_tag] = nr
self.nr_styles_added += 1
stylespan = etree.Element(inkex.addNS(spantag, "svg"))
combinedStyles = dict(styles)
combinedStyles[style] = style_value
stylespan.set("style", str(inkex.Style(combinedStyles)))
spanid = "%s-%d-cs-%s-%s" % (name, self.nr_styles_added, style_tag, nr)
self.logwrite("setting %s style id %s" % (style_value, spanid))
stylespan.set("id", spanid)
self.setFormattedText(
stylespan,
name,
text[begin_index + 1 : end_index],
spantag,
added_style,
styles,
)
restspan = etree.Element(inkex.addNS(spantag, "svg"))
restspan.set("style", str(inkex.Style(styles)))
self.setFormattedText(
restspan, name, text[end_index + 1 :], spantag, added_style, styles
)
self.formatTextImages(
element, name, text[:begin_index], spantag, added_style, styles
)
element.append(stylespan)
element.append(restspan)
def setFirstTextChild(self, element, name, text):
"""Find the first child of a text element that already has
some text in it. This could be a tspan in a tspan nested
any number of times. Then delete all other tspans from the
text. Otherwise parts of the original text will remain
after the substitution. It is important to drill down and
find the first tspan that actually contains text (if any)
because that will have the style that the user expects
the new text to have, as any empty tspan will be invisible
(and is probably there by accident)."""
if (
(
element.tag == inkex.addNS("text", "svg")
or element.tag == inkex.addNS("tspan", "svg")
)
and element.text is not None
and len(element.text) > 0
):
self.logwrite(
"text replace %s %s %r\n"
% (element.get("id"), element.tag, text)
)
self.deleteTextChildren(element)
self.setFormattedText(
element,
name,
text,
"tspan",
{},
inkex.Style.parse_str(element.get("style")),
)
return True
elif (
(
element.tag == inkex.addNS("flowPara", "svg")
or element.tag == inkex.addNS("flowLine", "svg")
or element.tag == inkex.addNS("flowSpan", "svg")
)
and element.text is not None
and len(element.text) > 0
):
self.logwrite(
"flow replace %s %s %r\n"
% (element.get("id"), element.tag, text)
)
self.deleteTextChildren(element)
self.setFormattedText(
element,
name,
text,
"flowSpan",
{},
inkex.Style.parse_str(element.get("style")),
)
return True
replaced = False
for c in element.getchildren():
if replaced and c.tag != inkex.addNS("flowRegion", "svg"):
element.remove(c)
elif c.tag != inkex.addNS("flowRegion", "svg"):
child_replaced = self.setFirstTextChild(c, name, text)
if child_replaced:
replaced = True
else:
element.remove(c)
return replaced
def addLayer(self, svg, suffix, nr, extra=""):
suffixlabel = ""
suffixid = ""
extralabel = ""
extraid = ""
if len(suffix) > 0:
suffixlabel = " %s" % suffix
suffixid = "_%s" % suffix
if len(extra) > 0:
extralabel = " (%s)" % extra
extraid = "_%s" % extra
llabel = "Countersheet%s %d%s" % (suffixlabel, nr, extralabel)
lid = "cs_layer%s_%04d%s" % (suffixid, nr, extraid)
if self.find_layer(svg, llabel, "") is not None:
sys.exit(
"Image already contains a layer '%s'. "
"Remove that layer before running extension again. "
'Or set a different "Suffix" when '
"running the extension. "
"Or just rename the existing layer." % llabel
)
layer = etree.Element(inkex.addNS("g", "svg"))
layer.set(inkex.addNS("label", "inkscape"), llabel)
layer.set("id", lid)
layer.set(inkex.addNS("groupmode", "inkscape"), "layer")
return layer
def generatecounter(self, c, rects, layer, colx, rowy, rotate):
oldcs = self.document.xpath("//svg:g[@id='%s']" % c.id, namespaces=NSS)
if len(oldcs):
self.logwrite(
"Found existing %d old counters for %s" % (len(oldcs), c.id)
)
for oldc in oldcs:
oldc.set("id", "")
clonegroup = etree.Element(inkex.addNS("g", "svg"))
c.elements.append(clonegroup)
if c.id != None and len(c.id):
clonegroup.set("id", c.id)
self.exportids.append(c.id)
self.logwrite(
"adding counter with %d parts at %d,%d\n"
% (len(c.parts), colx, rowy)
)
for p in c.parts:
if len(p) == 0:
continue
rectname = p
killrect = False
if rectname[0] == "@":
killrect = True
rectname = rectname[1:]
if rectname not in rects:
sys.exit(
"Unable to find rectangle with id '%s' "
"that was specified in the CSV data file." % rectname