forked from spakin/SimpInkScr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_inkscape_scripting.py
executable file
·2103 lines (1807 loc) · 78.3 KB
/
simple_inkscape_scripting.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 python
'''
Copyright (C) 2021-2022 Scott Pakin, [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 3 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.
'''
import base64
import collections.abc
import io
import math
import os
import random
import re
try:
import numpy
except ModuleNotFoundError:
pass
import PIL.Image
import lxml
import inkex
from inkex.localization import inkex_gettext as _
from tempfile import TemporaryDirectory
# ----------------------------------------------------------------------
# The following definitions are utilized by the user convenience
# functions.
# Define a prefix for all IDs we assign. This contains randomness so
# running the same script repeatedly will be unlikely to produce
# conflicting IDs.
_id_prefix = 'simp-ink-scr-%d-' % random.randint(100000, 999999)
# Keep track of the next ID to append to _id_prefix.
_next_obj_id = 1
# Maintain all top-level SVG state in _simple_top.
_simple_top = None
# Store a stack of user-specified default styles in _default_style.
_default_style = [{}]
# Most shapes use this as their default style.
_common_shape_style = {'stroke': 'black',
'fill': 'none'}
# Store a stack of user-specified default transforms in _default_transform.
_default_transform = [None]
def _debug_print(*args):
'Implement print in terms of inkex.utils.debug.'
inkex.utils.debug(' '.join([str(a) for a in args]))
def _split_two_or_one(val):
'''Split a tuple into two values and a scalar into two copies of the
same value.'''
try:
a, b = val
except TypeError:
a, b = val, val
return a, b
def _python_to_svg_str(val):
'Convert a Python value to a string suitable for use in an SVG attribute.'
if isinstance(val, str):
# Strings are used unmodified
return val
if isinstance(val, bool):
# Booleans are converted to lowercase strings.
return str(val).lower()
if isinstance(val, float):
# Floats are converted using a fair number of significant digits.
return '%.10g' % val
try:
# Each element of a sequence (other than strings, which were
# handled above) is converted recursively.
return ' '.join([_python_to_svg_str(v) for v in val])
except TypeError:
pass # Not a sequence
return str(val) # Everything else is converted to a string as usual.
def _svg_str_to_python(s):
'Convert an SVG attribute string to an appropriate Python type.'
# Recursively convert lists.
fields = s.replace(',', ' ').replace(';', ' ').split()
if len(fields) > 1:
return [_svg_str_to_python(f) for f in fields]
# Specially handle numerical data types then fall back to strings.
try:
return int(s)
except ValueError:
pass
try:
return float(s)
except ValueError:
pass
return s
def _abend(msg):
'Abnormally end execution with an error message.'
raise inkex.AbortExtension(msg)
class Mpath(inkex.Use):
'Point to a path object.'
tag_name = 'mpath'
class SimpleTopLevel():
"Keep track of top-level objects, both ours and inkex's."
def __init__(self, svg_root):
self._svg_root = svg_root
self._svg_attach = self.find_attach_point()
self._simple_objs = []
def find_attach_point(self):
'''Return a suitable point in the SVG XML tree at which to attach
new objects.'''
# The Inkscape GUI automatically adds a <sodipodi:namedview> element
# with an inkscape:current-layer attribute, and this will name either
# an actual layer or the <svg> element itself. In this case, we return
# the layer pointed to by inkscape:current-layer.
svg = self._svg_root
try:
namedview = svg.findone('sodipodi:namedview')
cur_layer_name = namedview.get('inkscape:current-layer')
cur_layer = svg.xpath('//*[@id="%s"]' % cur_layer_name)[0]
return cur_layer
except AttributeError:
pass
# If an extension is run from the command line, the input SVG file may
# lack a <sodipodi:namedview> element. (This is the case for
# /usr/share/inkscape/templates/default.svg in my installation, for
# example.) In this case, we return the topmost layer.
try:
return svg.xpath('//svg:g[@inkscape:groupmode="layer"]')[-1]
except IndexError:
pass
# A very minimal SVG input may contain no layers at all. In this case,
# we return the top-level <svg> element.
return svg
def append_obj(self, obj, to_root=False):
'Append a Simple Inkscape Scripting object to the document.'
# Check for a few error conditions.
if not isinstance(obj, SimpleObject):
raise ValueError('Only Simple Inkscape Scripting objects '
'can be appended')
if obj in self._simple_objs:
raise ValueError('Object has already been appended')
# Attach the underlying inkex object to the SVG attachment point if
# to_root is False or to the SVG root if to_root is True. Append
# the Simple Inkscape Scripting object to the list of simple
# objects.
if to_root:
self._svg_root.append(obj._inkscape_obj)
else:
self._svg_attach.append(obj._inkscape_obj)
self._simple_objs.append(obj)
def remove_obj(self, obj):
'Remove a Simple Inkscape Scripting object from the document.'
# Check for a few error conditions.
if not isinstance(obj, SimpleObject):
raise ValueError('Only Simple Inkscape Scripting objects '
'can be removed')
if obj not in self._simple_objs:
raise ValueError('Object does not appear at the top level')
# Elide the Simple Inkscape Scripting object and dissociate the
# underlying inkex object from its parent.
self._simple_objs = [o for o in self._simple_objs if o is not obj]
obj._inkscape_obj.delete()
def last_obj(self):
'Return the last Simple Inkscape Scripting object added by append_obj.'
return self._simple_objs[-1]
def append_def(self, obj):
'''Append either an inkex object or a Simple Inkscape Scripting object
to the document's <defs> section.'''
try:
self._svg_root.defs.append(obj._inkscape_obj)
except AttributeError:
self._svg_root.defs.append(obj)
@property
def svg_root(self):
'Return the root of the SVG tree.'
return self._svg_root
def __contains__(self, obj):
'''Return True if a given Simple Inkscape Scripting object appears at
the document's top level.'''
return obj in self._simple_objs
@property
def width(self):
'Return the width of the SVG document.'
try:
# Inkscape 1.2+
return self._svg_root.viewbox_width
except AttributeError:
# Inkscape 1.0 and 1.1
return self._svg_root.width
@property
def height(self):
'Return the height of the SVG document.'
try:
# Inkscape 1.2+
return self._svg_root.viewbox_height
except AttributeError:
# Inkscape 1.0 and 1.1
return self._svg_root.height
def get_existing_guides(self):
'''Return a list of existing Inkscape guides as Simple Inkscape
Scripting Guide objects.'''
guides = []
for iobj in self._svg_root.namedview.xpath('//sodipodi:guide'):
guides.append(Guide._from_inkex_object(iobj))
return guides
def replace_all_guides(self, guides):
'Replace all guides in the document with those in the given list.'
for iobj in self._svg_root.namedview.xpath('//sodipodi:guide'):
iobj.getparent().remove(iobj)
nv = self._svg_root.namedview
for obj in guides:
nv.add(obj.get_inkex_object())
class SVGOutputMixin():
'''Provide an svg method for converting an underlying inkex object to
a string.'''
def svg(self, xmlns=False, pretty_print=False):
'Return our underlying inkex object as a string.'
obj = self.get_inkex_object()
if xmlns or pretty_print:
# pretty_print currently implies xmlns.
return lxml.etree.tostring(obj,
encoding='unicode',
pretty_print=pretty_print)
return obj.tostring().decode('utf-8')
class SimpleObject(SVGOutputMixin):
'Encapsulate an Inkscape object and additional metadata.'
def __init__(self, obj, transform, conn_avoid, clip_path_obj, mask_obj,
base_style, obj_style, track=True):
'Wrap an Inkscape object within a SimpleObject.'
# Combine the current and default transforms.
ts = []
if transform is not None:
transform = str(transform) # Transform may be an inkex.Transform.
if transform != '':
ts.append(transform)
if _default_transform[-1] is not None and _default_transform[-1] != '':
ts.append(_default_transform[-1])
if ts == []:
self._transform = inkex.Transform()
else:
obj.transform = ' '.join(ts)
self._transform = inkex.Transform(obj.transform)
# Optionally indicate that connectors are to avoid this object.
if conn_avoid:
obj.set('inkscape:connector-avoid', 'true')
# Optionally employ a clipping path.
if clip_path_obj is not None:
if isinstance(clip_path_obj, str):
clip_str = clip_path_obj
else:
if not isinstance(clip_path_obj, SimpleClippingPath):
clip_path_obj = clip_path(clip_path_obj)
clip_str = 'url(#%s)' % clip_path_obj._inkscape_obj.get_id()
obj.set('clip-path', clip_str)
# Optionally employ a mask.
if mask_obj is not None:
if isinstance(mask_obj, str):
mask_str = mask_obj
else:
if not isinstance(mask_obj, SimpleMask):
mask_obj = mask(mask_obj)
mask_str = 'url(#%s)' % mask_obj._inkscape_obj.get_id()
obj.set('mask', mask_str)
# Combine the current and default styles.
ext_style = self._construct_style(base_style, obj_style)
if ext_style != '':
obj.style = ext_style
# Store the modified Inkscape object. If the object is new (as
# opposed to having been wrapped with inkex_object), attach it to
# the top-level connection point.
self._inkscape_obj = obj
if obj.getparent() is None:
if track:
_simple_top.append_obj(self)
self.parent = None
def __str__(self):
'''Return the object as a string of the form "url(#id)". This
enables the object to be used as a value in style key=value
arguments such as shape_inside.'''
return 'url(#%s)' % self._inkscape_obj.get_id()
@staticmethod
def _construct_style(base_style, new_style):
'''Combine a shape default style, a global default style, and an
object-specific style and return the result as a string.'''
# Start with the default style for the shape type.
style = base_style.copy()
# Update the style according to the current global default style.
style.update(_default_style[-1])
# Update the style based on the object-specific style.
for k, v in new_style.items():
k = k.replace('_', '-')
if v is None:
style[k] = None
else:
style[k] = _python_to_svg_str(v)
# Remove all keys whose value is None.
style = {k: v for k, v in style.items() if v is not None}
# Concatenate the style into a string.
return ';'.join(['%s:%s' % kv for kv in style.items()])
def _inkscape_bbox(self):
"""Return the object's bounding box as an inkex.transforms.BoundingBox.
This method works by writing the object to its own file and
spawning another copy of Inkscape to compute the bounding box. It
can therefore be expected to be quite slow. The code is derived
from inkex's get_inkscape_bbox but adapted to work with any object, not
just text, which is a limitation at the time of this writing."""
iobj = self.get_inkex_object()
with TemporaryDirectory(prefix='inkscape-command') as tmpdir:
svg_file = inkex.command.write_svg(iobj.root, tmpdir, 'input.svg')
out = inkex.command.inkscape(svg_file,
'-X', '-Y', '-W', '-H',
query_id=iobj.get_id())
out = list(map(iobj.root.viewport_to_unit, out.splitlines()))
if len(out) != 4:
raise ValueError('Bounding box computation failed')
return inkex.BoundingBox.new_xywh(*out)
def _need_inkscape_bbox(self, iobj):
'Return True if we need Inkscape to compute a bounding box.'
for elt in iobj.iter():
if elt.TAG in ['text', 'use', 'image']:
# <text> requires Inkscape. <use> can be anything so we
# assume pessimistally that it requires Inkscape. <image>
# requires Inkscape if the image is not embedded or if
# width and height are not specified. Rather than take
# chances we always invoke Inkscape if given an image.
return True
return False
def bounding_box(self):
"Return the object's bounding box as an inkex.transforms.BoundingBox."
# Ask inkex to compute a bounding box.
iobj = self._inkscape_obj
bbox = iobj.bounding_box()
# Bounding boxes for text, non-embedded images, or groups
# containing either of those are inaccurate. In such cases, try
# using a slow but more accurate approach.
if self._need_inkscape_bbox(iobj):
try:
bbox = self._inkscape_bbox()
except AttributeError:
# Running from Inkscape 1.0 or 1.1 instead of Inkscape 1.2+
pass
except inkex.command.ProgramRunError:
# Running from an AppImage build of Inkscape
pass
return bbox
def remove(self):
'Remove the current object from the list of rendered objects.'
try:
self.parent.ungroup(self)
except AttributeError:
pass # Not within a group
global _simple_top
if self in _simple_top:
_simple_top.remove_obj(self)
def to_def(self):
'''Convert the object to a definition, removing it from the list of
rendered objects.'''
self.remove()
global _simple_top
_simple_top.append_def(self)
return self
@staticmethod
def _path_to_curve(pe):
'''Convert a PathElement to a list of PathCommands that are primarily
curves.'''
# Convert to a CubicSuperPath and from that to a list of segments.
csp = pe.path.to_superpath()
segs = list(csp.to_segments())
new_segs = []
# Postprocess all linear curves to make them more suitable for
# conversion to B-splines.
prev = inkex.Vector2d()
for seg in segs:
if isinstance(seg, inkex.paths.Move):
first = seg.end_point(inkex.Vector2d(), prev)
new_segs.append(seg)
elif isinstance(seg, inkex.paths.Curve):
# Convert [a, a, b, b] to [a, 1/3[a, b], 2/3[a, b], b].
pt1 = prev
pt2 = inkex.Vector2d(seg.x2, seg.y2)
pt3 = inkex.Vector2d(seg.x3, seg.y3)
pt4 = inkex.Vector2d(seg.x4, seg.y4)
if pt1.is_close(pt2) and pt3.is_close(pt4):
pt2 = (2*pt1 + pt4)/3
pt3 = (pt1 + 2*pt4)/3
new_segs.append(inkex.paths.Curve(pt2.x, pt2.y,
pt3.x, pt3.y,
pt4.x, pt4.y))
elif isinstance(seg, inkex.paths.Line):
# Convert the line [a, b] to the curve [a, 1/3[a, b],
# 2/3[a, b], b].
pt1 = prev
pt4 = inkex.Vector2d(seg.x, seg.y)
pt2 = (2*pt1 + pt4)/3
pt3 = (pt1 + 2*pt4)/3
new_segs.append(inkex.paths.Curve(pt2.x, pt2.y,
pt3.x, pt3.y,
pt4.x, pt4.y))
elif isinstance(seg, inkex.paths.ZoneClose):
# Draw a line back to the first point.
pt1 = prev
pt4 = first
if not pt1.is_close(pt4):
pt2 = (2*pt1 + pt4)/3
pt3 = (pt1 + 2*pt4)/3
new_segs.append(inkex.paths.Curve(pt2.x, pt2.y,
pt3.x, pt3.y,
pt4.x, pt4.y))
new_segs.append(seg)
else:
_abend(_('internal error: unexpected path command '
'in _path_to_curve'))
prev = seg.end_point(first, prev)
return new_segs
def to_path(self, all_curves=False):
'''Convert the object to a path, removing it from the list of
rendered objects.'''
# Get a path version of the underlying object and use this to
# construct a path SimpleObject.
obj = self._inkscape_obj
try:
p = path(obj.get_path())
except TypeError:
_abend(_('Failed to convert object to a path'))
p_obj = p._inkscape_obj
# If all_curves was specified, replace the path with one created
# from the current path's CubicSuperPath segments.
if all_curves:
pes = self._path_to_curve(p_obj)
p.remove()
p = path(pes)
p_obj = p._inkscape_obj
# Copy over the original object's style and transform.
p_obj.set('style', obj.get('style'))
xform = obj.get('transform')
if xform is not None:
p.transform = xform
# Remove the old object and return the new object.
self.remove()
return p
def style(self, **style):
"""Augment the object's current style and return the new style as a
Python dict."""
# Merge the old and new styles and apply these to the object.
obj = self._inkscape_obj
obj.style = self._construct_style(dict(obj.style.items()), style)
# Convert the style to a dictionary with Python-compatible keys.
new_style = {}
for k, v in obj.style.items():
k = k.replace('-', '_')
v = _svg_str_to_python(v)
new_style[k] = v
return new_style
def _inverse_transform(self):
'Return an inkex.Transform that undoes the current transformation.'
xform = self._transform
m = numpy.array(list(xform.matrix) + [[0, 0, 1]])
m_inv = numpy.linalg.inv(m)
un_xform = inkex.Transform()
un_xform.add_matrix(m_inv[0][0], m_inv[1][0],
m_inv[0][1], m_inv[1][1],
m_inv[0][2], m_inv[1][2])
return un_xform
def _find_transform_point(self, around):
'Return the center point around which to apply a transformation.'
if isinstance(around, str):
obj = self._inkscape_obj
un_xform = self._inverse_transform()
bbox = obj.bounding_box(un_xform)
if bbox is None:
# Special case first encountered in Inkscape 1.2-dev when
# an empty layer is selected.
return inkex.Vector2d(0, 0)
if around in ['c', 'center']:
around = bbox.center
elif around == 'ul':
around = inkex.Vector2d(bbox.left, bbox.top)
elif around == 'ur':
around = inkex.Vector2d(bbox.right, bbox.top)
elif around == 'll':
around = inkex.Vector2d(bbox.left, bbox.bottom)
elif around == 'lr':
around = inkex.Vector2d(bbox.right, bbox.bottom)
else:
_abend(_('Unexpected transform argument %s') % repr(around))
else:
around = inkex.Vector2d(around)
return around
def translate(self, dist, first=False):
'Apply a translation transformation.'
tr = inkex.Transform()
tr.add_translate(dist[0], dist[1])
if first:
self._transform = self._transform * tr
else:
self._transform = tr * self._transform
self._apply_transform()
def rotate(self, angle, around='center', first=False):
'Apply a rotation transformation, optionally around a given point.'
tr = inkex.Transform()
around = self._find_transform_point(around)
tr.add_rotate(angle, around.x, around.y)
if first:
self._transform = self._transform * tr
else:
self._transform = tr * self._transform
self._apply_transform()
def scale(self, factor, around='center', first=False):
'Apply a scaling transformation.'
try:
sx, sy = factor
except (TypeError, ValueError):
sx, sy = factor, factor
around = inkex.Vector2d(self._find_transform_point(around))
tr = inkex.Transform()
tr.add_translate(around)
tr.add_scale(sx, sy)
tr.add_translate(-around)
if first:
self._transform = self._transform * tr
else:
self._transform = tr * self._transform
self._apply_transform()
def skew(self, angles, around='center', first=False):
'Apply a skew transformation.'
around = inkex.Vector2d(self._find_transform_point(around))
tr = inkex.Transform()
tr.add_translate(around)
tr.add_skewx(angles[0])
tr.add_skewy(angles[1])
tr.add_translate(-around)
if first:
self._transform = self._transform * tr
else:
self._transform = tr * self._transform
self._apply_transform()
@property
def transform(self):
"Return the object's current transformation as an inkex.Transform."
return self._transform
@transform.setter
def transform(self, xform):
'''Assign a new transformation to an object from either a string or
an inkex.Transform.'''
if isinstance(xform, inkex.Transform):
self._transform = xform
else:
self._transform = inkex.Transform(xform)
self._apply_transform()
@property
def tag(self):
'Return the element type of our underlying object.'
# Strip off the namespace prefix (e.g.,
# "{http://www.w3.org/2000/svg}circle" --> "circle").
return self._inkscape_obj.TAG
def svg_get(self, attr, as_str=False):
'Return the value of an SVG attribute.'
v = self._inkscape_obj.get(attr)
if v is None or as_str:
# None and as_str=True return strings.
return v
if attr == 'transform':
# Return the transform as an inkex.Transform.
return inkex.Transform(v)
if attr == 'style':
# Return the style as a dictionary.
return self.style()
# Everything else is returned as a Python data type.
return _svg_str_to_python(v)
def svg_set(self, attr, val):
'Set the value of an SVG attribute.'
obj = self._inkscape_obj
if attr == 'transform':
# "transform" is a special case because we maintain a shadow
# copy of the current transform within the SimpleObject.
self.transform = val
elif val is None:
# None removes an attribute.
obj.attrib.pop(attr, None) # "None" suppresses a KeyError
elif attr == 'style':
# "style" accepts a variety of data types.
if isinstance(val, dict):
# Dictionary
self.style(**val)
else:
# inkex.Style or other object convertible to str
obj.set(attr, str(val))
else:
# All other attribute values are applied directly to the
# underlying inkex object.
obj.set(attr, _python_to_svg_str(val))
def _apply_transform(self):
"Apply the SimpleObject's transform to the underlying SVG object."
self._inkscape_obj.set('transform', self._transform)
@staticmethod
def _diff_transforms(objs):
'Return a list of transformations to animate.'
# Determine if any object has a different transformation from any
# other.
xforms = [o.get('transform') for o in objs]
if all(x is None for x in xforms):
return [] # No transform on any object: nothing to animate.
for i, x in enumerate(xforms):
if x is None:
xforms[i] = inkex.Transform()
else:
xforms[i] = inkex.Transform(x)
if len({str(x) for x in xforms}) == 1:
return [] # All transforms are identical: nothing to animate.
hexads = [list(x.to_hexad()) for x in xforms]
# Find changes in translation.
xlate_values = []
for h in hexads:
xlate_values.append('%.5g %.5g' % (h[4], h[5]))
# Find changes in scale.
scale_values = []
for i, h in enumerate(hexads):
sx = math.sqrt(h[0]**2 + h[1]**2)
sy = math.sqrt(h[2]**2 + h[3]**2)
if abs(sx - sy) <= 0.00001:
scale_values.append('%.5g' % ((sx + sy)/2))
else:
scale_values.append('%.5g %.5g' % (sx, sy))
h[0] /= sx
h[1] /= sx
h[2] /= sy
h[3] /= sy
hexads[i] = h
# Find changes in rotation, initially as numeric radians.
rot_values = []
for h in hexads:
# Ignore transforms with inconsistent rotation angles.
angles = [math.acos(h[0]), math.asin(h[1]),
math.asin(-h[2]), math.acos(h[3])]
if abs(angles[0] - angles[3]) > 0.00001 or \
abs(angles[1] - angles[2]) > 0.00001:
return [] # Transform is too complicated for us to handle.
# Determine the angle in the correct quadrant.
if h[0] >= 0 and h[1] >= 0:
ang = angles[0]
elif h[0] < 0 and h[1] >= 0:
ang = angles[0]
elif h[0] < 0 and h[1] < 0:
ang = math.pi - angles[1]
else:
ang = 2*math.pi + angles[1]
rot_values.append(ang)
# Convert changes in rotation from radians to degrees and floats to
# strings.
rot_values = ['%.5g' % (r*180/math.pi) for r in rot_values]
# Return a list of transformations to apply.
xform_list = []
if len(set(scale_values)) > 1:
xform_list.append(('scale', scale_values))
if len(set(rot_values)) > 1:
xform_list.append(('rotate', rot_values))
if len(set(xlate_values)) > 1:
xform_list.append(('translate', xlate_values))
return xform_list
def _animate_transforms(self, objs, duration,
begin_time, key_times,
repeat_count, repeat_time,
keep, attr_filter):
'Specially handle animating transforms.'
# Determine the transforms to apply. We treat each transform as a
# filterable attribute.
xforms = self._diff_transforms(objs)
if attr_filter is not None:
xforms = [xf for xf in xforms if attr_filter(xf[0])]
if len(xforms) == 0:
return # No transforms to animate
# Animate each transform in turn.
target = self
for i, xf in enumerate(xforms):
# Only one transform animation can be applied per object.
# Hence, we keep wrapping the object in successive levels of
# groups and apply one transform to each group.
if i > 0:
target = group([target])
anim = lxml.etree.Element('animateTransform')
anim.set('attributeName', 'transform')
anim.set('type', xf[0])
anim.set('values', '; '.join(xf[1]))
if duration is not None:
anim.set('dur', _python_to_svg_str(duration))
if begin_time is not None:
anim.set('begin', _python_to_svg_str(begin_time))
if key_times is not None:
if len(key_times) != len(objs):
_abend('Expected %d key times but saw %d' %
(len(objs), len(key_times)))
anim.set('keyTimes',
'; '.join([_python_to_svg_str(kt)
for kt in key_times]))
if repeat_count is not None:
anim.set('repeatCount', _python_to_svg_str(repeat_count))
if repeat_time is not None:
anim.set('repeatDur', _python_to_svg_str(repeat_time))
if keep:
anim.set('fill', 'freeze')
target._inkscape_obj.append(anim)
@staticmethod
def _diff_attributes(objs):
'''Given a list of ShapeElements, return a dictionary mapping an
attribute name to a list of values it takes on across all of the
ShapeElements.'''
# Do nothing if we don't have at least two objects.
if len(objs) < 2:
return {} # Too few objects on which to compute differences
# For each attribute in the first object, produce a list of
# corresponding attributes in all other objects.
attr2vals = {}
for a in objs[0].attrib:
if a in ['id', 'style', 'transform']:
continue
vs = [o.get(a) for o in objs]
vs = [v for v in vs if v is not None]
if len(set(vs)) > 1:
attr2vals[a] = vs
# Handle styles specially.
if objs[0].get('style') is not None:
style = inkex.Style(objs[0].get('style'))
for a in style:
vs = []
for o in objs:
obj_style = inkex.Style(o.get('style'))
vs.append(obj_style.get(a))
if len(set(vs)) > 1:
attr2vals[a] = vs
return attr2vals
@staticmethod
def _key_times_string(key_times, num_objs, interpolation):
'Validate key-time values before converting them to a string.'
# Ensure the argument is the correct type (list of floats) and
# length and is ordered correctly.
orig_kt = [float(v) for v in key_times]
kt = sorted(orig_kt)
if kt != orig_kt:
_abend('Key times must be sorted: %s' % repr(orig_kt))
if len(kt) != num_objs:
_abend('Expected a list of %d key times but saw %d' %
(num_objs, len(kt)))
# Ensure the first and last values are as required by interpolation.
if interpolation is None:
interpolation = 'linear' # Default for SVG
if interpolation in ['linear', 'spline', 'discrete'] and kt[0] != 0:
_abend('The first key time must be 0: %s' % repr(kt))
if interpolation in ['linear', 'spline'] and kt[-1] != 1:
_abend('The final key time must be 1: %s' % repr(kt))
# Convert the key times to a string, and return it.
return '; '.join(['%.5g' % v for v in kt])
def animate(self, objs=None, duration=None,
begin_time=None, key_times=None,
repeat_count=None, repeat_time=None, keep=True,
interpolation=None, path=None, path_rotate=None,
at_end=False, attr_filter=None):
"Animate the object through each of the given objects' appearance."
# Prepare the list of objects.
objs = objs or []
try:
iobjs = [o._inkscape_obj for o in objs]
except TypeError:
objs = [objs]
iobjs = [o._inkscape_obj for o in objs]
if at_end:
all_iobjs = iobjs + [self._inkscape_obj]
else:
all_iobjs = [self._inkscape_obj] + iobjs
# Identify the differences among all the objects.
attr2vals = self._diff_attributes(all_iobjs)
if attr_filter is not None:
attr2vals = {k: v for k, v in attr2vals.items() if attr_filter(k)}
# Add one <animate> element per attribute.
for a, vs in attr2vals.items():
anim = lxml.etree.Element('animate')
anim.set('attributeName', a)
anim.set('values', '; '.join(vs))
if duration is not None:
anim.set('dur', _python_to_svg_str(duration))
if begin_time is not None:
anim.set('begin', _python_to_svg_str(begin_time))
if key_times is not None:
kt_str = self._key_times_string(key_times,
len(all_iobjs),
interpolation)
anim.set('keyTimes', kt_str)
if repeat_count is not None:
anim.set('repeatCount', _python_to_svg_str(repeat_count))
if repeat_time is not None:
anim.set('repeatDur', _python_to_svg_str(repeat_time))
if keep:
anim.set('fill', 'freeze')
if interpolation is not None:
anim.set('calcMode', _python_to_svg_str(interpolation))
self._inkscape_obj.append(anim)
# Add an <animateMotion> element if a path was supplied.
if path is not None:
# Create an <animateMotion> element.
anim_mo = lxml.etree.Element('animateMotion')
if duration is not None:
anim_mo.set('dur', _python_to_svg_str(duration))
if begin_time is not None:
anim_mo.set('begin', _python_to_svg_str(begin_time))
if key_times is not None:
kt_str = self._key_times_string(key_times,
len(all_iobjs),
interpolation)
anim.set('keyTimes', kt_str)
if repeat_count is not None:
anim_mo.set('repeatCount', _python_to_svg_str(repeat_count))
if repeat_time is not None:
anim_mo.set('repeatDur', _python_to_svg_str(repeat_time))
if keep:
anim_mo.set('fill', 'freeze')
if interpolation is not None:
anim_mo.set('calcMode', _python_to_svg_str(interpolation))
if path_rotate is not None:
anim_mo.set('rotate', _python_to_svg_str(path_rotate))
# Insert an <mpath> child under <animateMotion> that links to
# the given path.
mpath = Mpath()
mpath.href = path._inkscape_obj.get_id()
anim_mo.append(mpath)
# Add the <animateMotion> to the target object.
self._inkscape_obj.append(anim_mo)
# Handle animated transforms specially because only one can apply
# to a given object. We therefore add levels of grouping, each
# with one <animateTransform> applied to it, as necessary.
self._animate_transforms(all_iobjs, duration,
begin_time, key_times,
repeat_count, repeat_time,
keep, attr_filter)
# Remove all given objects from the top-level set of objects.
for o in objs:
if o is not self:
o.remove()
def get_inkex_object(self):
"Return the SimpleObject's underlying inkex object."
return self._inkscape_obj
def z_order(self, target, n=None):
'Raise or lower the SimpleObject in the stacking order.'
# These operations are performed entirely at the inkex level with
# no reecord at the Simple Inkscape Scripting level. We therefore
# start by acquiring our inkex object and its parent.
obj = self._inkscape_obj
p_obj = obj.getparent()
# Handle the main raising and lowering operations.
if target == 'top':
# Raise to top.
p_obj.append(obj)
return
if target == 'bottom':
# Lower to bottom.
p_obj.insert(0, obj)
return
if target == 'raise':
# Raise by n objects.
for i in range(n or 1):
next_obj = obj.getnext()
if next_obj is not None:
next_obj.addnext(obj)
return
if target == 'lower':
# Lower by n objects.
for i in range(n or 1):
prev_obj = obj.getprevious()
if prev_obj is not None:
prev_obj.addprevious(obj)
return
# Handle moving an object to a specific stack position.
if target == 'to':
# Move to a specific position by inserting right *before* the
# next position.
if n is None:
_abend(_("z_order('to') requires a second argument"))
if n >= 0:
try:
# Add before the next element.
p_obj[n + 1].addprevious(obj)
except IndexError:
# No next element: raise to top.
p_obj.append(obj)
else:
n += len(p_obj)
if n < 1:
# No previous element: lower to bottom.