-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathshapewidget.py
executable file
·2247 lines (1946 loc) · 78.1 KB
/
shapewidget.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
#
# Advene: Annotate Digital Videos, Exchange on the NEt
# Copyright (C) 2008-2017 Olivier Aubert <contact@olivieraubert.net>
#
# Advene 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.
#
# Advene 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 Advene; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
"""Simple Shape editor widget
==========================
This component provides a simple framework allowing to edit basic
shapes, and generate the corresponding XML.
This component should not have dependencies on Advene, so that it
can be reused in other projects.
Note: if given a background image at instanciation, ShapeDrawer will
use its size as reference, else it will use a hardcoded dimension
(see ShapeDrawer.__init__). When loading a SVG file, it will convert
its dimensions into the reference size. When saving the SVG again,
it will lose the original SVG dimensions and use instead the
background/hardcoded dimensions.
FIXME: XML load/dump should try to preserve unhandled information (especially TAL instructions)
FIXME: find a way to pass search paths for xlink:href elements resolution
FIXME: find a way to pass the background path
"""
import logging
logger = logging.getLogger(__name__)
import os
import sys
import gi
gi.require_version('Gdk', '3.0')
gi.require_version('Gtk', '3.0')
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import Gtk
import cairo
import math
import urllib.request, urllib.parse, urllib.error
import re
from math import atan2, cos, sin
import xml.etree.ElementTree as ET
from gettext import gettext as _
COLORS = [ 'red', 'green', 'blue', 'black', 'white', 'gray', 'yellow' ]
SVGNS = 'http://www.w3.org/2000/svg'
stroke_width_re=re.compile(r'stroke-width:\s*(\d+)')
stroke_color_re=re.compile(r'stroke:\s*(\w+)')
arrow_width_re=re.compile(r'#arrow(\d+)')
defined_shape_classes=[]
class Shape:
"""The generic Shape class.
@ivar name: the shape instance name
@type name: string
@ivar color: the shape color
@type color: string
@ivar linewidth: the line width
@type linewidth: int
@ivar filled: should the shape be filled ?
@type filled: boolean
@ivar tolerance: pixel tolerance for control point selection
@type tolerance: int
@ivar link: URL associated to the shape
@type link: string or None
@ivar link_label: label for the URL associated to the shape
@type link_label: string or None
@cvar SHAPENAME: the name of the shape class
@type SHAPENAME: translated string
"""
SHAPENAME=_("Generic shape")
# Tag used for the generation/parsing of SVG representation
SVGTAG=''
# If True, then the shape needs more than 2 control points to be
# created. This implies a different interaction.
MULTIPOINT = False
def __init__(self, name=None, color="green", dimensions=None):
self.name=name or self.SHAPENAME
self.color=color
self.linewidth=2
self.opacity = 1.0
self.filled = False
# Pixel tolerance for control point selection
self.tolerance = 6
self.link=None
self.link_label=None
if dimensions is None:
# It is needed since set_bounds initializes all the
# dimension-related attributes of the object.
dimensions = ( (0, 0), (10, 10) )
self.set_bounds(dimensions)
# Extra SVG attributes to preserve (esp. tal: instructions)
self.svg_attrib={}
def set_bounds(self, bounds):
"""Set the bounds of the shape.
The bounds are the coordinates of the rectangular selection
used to define the shape.
@param bounds: a tuple of 2 int couples
@type bounds: tuple
"""
pass
def get_bounds(self):
"""Return the bounds of the shape.
@return: a tuple of 2 int couples
@rtype: tuple
"""
return ( (0, 0), (10, 10) )
def render(self, context, invert=False):
"""Render the shape on the given context
@param context: the destination context
@type context: cairo.Context
@param invert: should the rendering inverse the selection ?
@type invert: boolean
"""
return
def render_setup(self, context, invert=False):
"""Setup context for common attributes.
"""
context.set_line_width(self.linewidth)
col = Gdk.RGBA()
col.parse(self.color)
col.alpha = self.opacity
Gdk.cairo_set_source_rgba(context, col)
if invert:
context.set_operator(cairo.OPERATOR_XOR)
else:
context.set_operator(cairo.OPERATOR_OVER)
def translate(self, vector):
"""Translate the shape.
@param vector: the translation vector
@type vector: a couple of int
"""
pass
def control_point(self, point):
"""Test if the given point is a control point.
If on a control point, return its coordinates (x, y) and those of the
other bound, else None
@param point: the tested point
@type point: a couple of int
@return: None, or a couple of coordinates
@rtype: tuple
"""
return None
def __contains__(self, point):
"""Test if the given point is inside the shape.
@param point: the tested point
@type point: a couple of int
@rtype: boolean
"""
return False
def __unicode__(self):
return "%s {%s}" % (self.SHAPENAME,
",".join("%s: %d" % (c[0], getattr(self, c[0])) for c in self.coords))
@classmethod
def parse_svg(cls, element, context):
"""Parse a SVG representation.
The context object must implement a 'dimensions' method that
will return a (width, height) tuple corresponding to the
canvas size.
@param element: etree.Element to parse
@param context: the svg context
@return: an appropriate shape, or None if the class could not parse the element
"""
if element.tag != cls.SVGTAG and element.tag != ET.QName(SVGNS, cls.SVGTAG):
return None
s=cls(name=element.attrib.get('name', cls.SHAPENAME))
s.filled=( element.attrib.get('fill', 'none') != 'none' )
s.color=element.attrib.get('stroke', None)
s.opacity = float(element.attrib.get('opacity', 1.0))
style=element.attrib.get('style', '')
m=stroke_width_re.search(style)
if m:
s.linewidth=int(m.group(1))
if s.color is None:
# Try to find it in style definition
m=stroke_color_re.search(style)
if m:
s.color = m.group(1)
else:
# Default fallback
s.color = 'green'
c=cls.xml2coords(cls.coords, element.attrib, context)
for n, v in c.items():
setattr(s, n, v)
s.svg_attrib=dict(element.attrib)
if hasattr(s, 'post_parse'):
s.post_parse()
return s
def get_svg(self, relative=False, size=None):
"""Return a SVG representation of the shape.
@param relative: should dimensions be relative to the container size or absolute?
@type relative: boolean
@param size: the container size in pixels
@type size: a couple of int
@return: the SVG representation
@rtype: elementtree.Element
"""
attrib=dict(self.svg_attrib)
attrib.update(self.coords2xml(relative, size))
if self.filled:
attrib['fill']=self.color
else:
attrib['fill']='none'
if self.opacity != 1.0 or "opacity" in attrib:
attrib['opacity'] = str(self.opacity)
attrib['stroke']=self.color
attrib['style']="stroke-width:%d" % self.linewidth
attrib['name']=self.name
e=ET.Element(ET.QName(SVGNS, self.SVGTAG), attrib=attrib)
if self.link:
a=ET.Element('a', attrib={ 'xlink:href': self.link,
'title': self.link_label or _("Link to %s") % self.link })
a.append(e)
yield a
else:
yield e
def copy_from(self, shape, style=False):
"""Copy data from another shape.
@param shape: the original shape
@param style: should the style be copied also?
@type style: boolean
"""
return
def clone(self, style=False):
"""Clone the shape.
@param style: should the style be copied also?
@type style: boolean
@return: a new shape
"""
s=self.__class__()
s.copy_from(self, style)
return s
@staticmethod
def xml2coords(coords, attrib, context):
"""Converts coordinates in XML format to their appropriate value
The context object must have 2 attributes:
- dimensions: a (width, height) tuple giving the display canvas dimensions.
- svg_dimensions: a (width, height) tuple giving the original SVG dimensions.
@param coords: a list of (name, dimension_index) tuple
@param attrib: an attributes dictionary
@param context: an object holding the context information
@return: a dictionary with values converted
"""
res={}
# Convert numeric attributes (possibly percentage) to float
for n, dimindex in coords:
v=attrib[n]
if v.endswith('%'):
# Convert it to absolute values
v=float(v[:-1]) * context.dimensions[dimindex] / 100
else:
if context.dimensions == context.svg_dimensions:
v=float(v)
else:
v=float(v) * context.dimensions[dimindex] / context.svg_dimensions[dimindex]
res[n]=int(v)
logger.debug("xml2coords %s -> %s", attrib, res)
return res
def coords2xml(self, relative, dimensions):
"""Converts coordinates to XML format
Note: we do not convert back to original SVG dimensions,
i.e. if a (640, 400) SVG was loaded over a (320, 200) canvas,
we will generate in return a (320, 200) SVG.
@param relative: convert to relative dimensions
@param dimensions: a (width, height) tuple
@return: a dictionary with values converted
"""
res={}
if relative:
for n, dimindex in self.coords:
res[n]="%.03f%%" % (getattr(self, n) * 100.0 / dimensions[dimindex])
else:
res = { n: str(getattr(self, n)) for n, d in self.coords }
return res
def edit_properties_widget(self):
"""Build a widget to edit the shape properties.
"""
vbox=Gtk.VBox()
def label_widget(label, widget, expand=False):
hb=Gtk.HBox()
hb.add(Gtk.Label(label=label))
hb.pack_start(widget, expand, True, 0)
return hb
# Name
namesel = Gtk.Entry()
namesel.set_text(self.name)
vbox.pack_start(label_widget(_("Name"), namesel), False, False, 0)
# Link
linksel = Gtk.Entry()
linksel.set_text(self.link or '')
vbox.pack_start(label_widget(_("Link"), linksel), False, False, 0)
# Linklabel
linklabelsel = Gtk.Entry()
linklabelsel.set_text(self.link_label or '')
vbox.pack_start(label_widget(_("Link label"), linklabelsel), False, False, 0)
# Color
colorsel = Gtk.ComboBoxText()
for s in COLORS:
colorsel.append_text(s)
try:
i=COLORS.index(self.color)
except IndexError:
i=0
colorsel.set_active(i)
vbox.pack_start(label_widget(_("Color"), colorsel), False, False, 0)
# Linewidth
linewidthsel = Gtk.HScale()
linewidthsel.set_range(1, 15)
linewidthsel.set_increments(1, 1)
linewidthsel.set_value(self.linewidth)
vbox.pack_start(label_widget(_("Linewidth"), linewidthsel, True), True, True, 0)
# Filled
filledsel = Gtk.ToggleButton()
filledsel.set_active(self.filled)
vbox.pack_start(label_widget(_("Filled"), filledsel), False, False, 0)
# Linewidth
opacitysel = Gtk.HScale()
opacitysel.set_range(0, 1)
opacitysel.set_digits(1)
opacitysel.set_increments(.1, .2)
opacitysel.set_value(self.opacity)
vbox.pack_start(label_widget(_("Opacity"), opacitysel, True), True, True, 0)
# svg_attrib
store=Gtk.ListStore(str, str)
for k, v in self.svg_attrib.items():
store.append([k, v])
treeview=Gtk.TreeView(model=store)
renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Attribute", renderer, text=0)
column.set_resizable(True)
treeview.append_column(column)
renderer = Gtk.CellRendererText()
renderer.set_property('editable', True)
column = Gtk.TreeViewColumn("Value", renderer, text=1)
column.set_resizable(True)
treeview.append_column(column)
treeview.show_all()
e=Gtk.Expander.new('SVG attributes')
e.add(treeview)
e.set_expanded(False)
vbox.add(e)
vbox.widgets = {
'name': namesel,
'color': colorsel,
'opacity': opacitysel,
'linewidth': linewidthsel,
'filled': filledsel,
'link': linksel,
'link_label': linklabelsel,
'attrib': treeview,
}
return vbox
def edit_properties(self):
"""Display a widget to edit the shape properties.
"""
edit=self.edit_properties_widget()
d = Gtk.Dialog(title=_("Properties of %s") % self.name,
parent=None,
flags=Gtk.DialogFlags.DESTROY_WITH_PARENT,
buttons=( Gtk.STOCK_OK, Gtk.ResponseType.OK,
Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL ) )
d.vbox.add(edit)
def keypressed_cb(widget=None, event=None):
if event.keyval == Gdk.KEY_Return:
d.response(Gtk.ResponseType.OK)
return True
elif event.keyval == Gdk.KEY_Escape:
d.response(Gtk.ResponseType.CANCEL)
return True
return False
d.connect('key-press-event', keypressed_cb)
edit.show_all()
res=d.run()
if res == Gtk.ResponseType.OK:
# Get new values
for n in ('name', 'link', 'link_label', 'uri', 'text'):
if n in edit.widgets:
setattr(self, n, edit.widgets[n].get_text())
self.color = COLORS[edit.widgets['color'].get_active()]
for n in ('linewidth', 'textsize', 'arrowwidth'):
if n in edit.widgets:
setattr(self, n, int(edit.widgets[n].get_value()))
for n in ('opacity', ):
if n in edit.widgets:
setattr(self, n, float(edit.widgets[n].get_value()))
for n in ('filled', 'arrow', 'closed'):
if n in edit.widgets:
setattr(self, n, edit.widgets[n].get_active())
d.destroy()
return True
else:
d.destroy()
return False
class Rectangle(Shape):
"""Rectangle shape.
It can be used as a baseclass for other shapes with corresponding
behaviour.
"""
SHAPENAME=_("Rectangle")
SVGTAG='rect'
# List of attributes holding the shape coordinates. The second
# element of the tuple is the index in the dimension tuple (width,
# height) used to compute relative sizes
coords=( ('x', 0),
('y', 1),
('width', 0),
('height', 1) )
def set_bounds(self, bounds):
self.x = int(min(bounds[0][0], bounds[1][0]))
self.y = int(min(bounds[0][1], bounds[1][1]))
self.width = int(abs(bounds[0][0] - bounds[1][0]))
self.height = int(abs(bounds[0][1] - bounds[1][1]))
def get_bounds(self):
return ( (self.x, self.y), (self.x + self.width, self.y + self.height) )
def render(self, context, invert=False):
self.render_setup(context, invert)
context.rectangle(self.x,
self.y,
self.width,
self.height)
if self.filled:
context.fill()
else:
context.stroke()
return
def translate(self, vector):
self.x += int(vector[0])
self.y += int(vector[1])
def copy_from(self, shape, style=False):
shape.x = self.x
shape.y = self.y
shape.width = self.width
shape.height = self.height
if style:
shape.color = self.color
shape.linewidth = self.linewidth
def control_point(self, point):
"""If on a control point, return its coordinates (x, y) and those of the other bound, else None
This version is fitted for rectangular areas
"""
x, y = point[0], point[1]
retval = [[None, None], [None, None]]
if abs(x - self.x) <= self.tolerance:
retval[0][0] = self.x + self.width
retval[1][0] = self.x
elif abs(x - self.x - self.width) <= self.tolerance:
retval[0][0] = self.x
retval[1][0] = self.x + self.width
else:
return None
if abs(y - self.y) <= self.tolerance:
retval[0][1] = self.y + self.height
retval[1][1] = self.y
elif abs(y - self.y - self.height) <= self.tolerance:
retval[0][1] = self.y
retval[1][1] = self.y + self.height
else:
return None
return retval
def __contains__(self, point):
x, y = point
return ( self.x <= x <= self.x + self.width
and self.y <= y <= self.y + self.height )
class Text(Rectangle):
"""Text shape.
"""
SHAPENAME=_("Text")
SVGTAG='text'
coords=( ('x', 0),
('y', 1) )
def __init__(self, name=SHAPENAME, color="green", dimensions=None):
super(Text, self).__init__(name, color, dimensions)
self.linewidth=1
self.filled=True
self.text='Some text'
# FIXME: maybe we should consider a relative size (wrt. canvas size)
self.textsize=20
def get_bounds(self):
return ( (self.x, self.y - self.height), (self.x + self.width, self.y) )
def render(self, context, invert=False):
self.render_setup(context, invert)
context.select_font_face("sans-serif", cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
context.set_font_size(self.textsize)
extents = context.text_extents(self.text)
# Fix width, height attributes
self.width = extents[2]
self.height = extents[3]
context.move_to(self.x, self.y)
try:
context.show_text(self.text)
self.width, self.height = extents[2:4]
except MemoryError:
logger.error("MemoryError while rendering text")
return
def control_point(self, point):
return None
@classmethod
def parse_svg(cls, element, context):
"""Parse a SVG representation.
The context object must implement a 'dimensions' method that
will return a (width, height) tuple corresponding to the
canvas size.
@param element: etree.Element to parse
@param context: the svg context
@return: an appropriate shape, or None if the class could not parse the element
"""
if element.tag != cls.SVGTAG and element.tag != ET.QName(SVGNS, cls.SVGTAG):
return None
s=cls(name=element.attrib.get('name', cls.SHAPENAME))
s.filled=( element.attrib.get('fill', 'none') != 'none' )
s.color=element.attrib.get('stroke', '2')
s.text=element.text or ''
style=element.attrib.get('style', '')
m=stroke_width_re.search(style)
if m:
s.linewidth=int(m.group(1))
c=cls.xml2coords(cls.coords, element.attrib, context)
for n, v in c.items():
setattr(s, n, v)
s.svg_attrib=dict(element.attrib)
if hasattr(s, 'post_parse'):
s.post_parse()
return s
def get_svg(self, relative=False, size=None):
"""Return a SVG representation of the shape.
"""
attrib=dict(self.svg_attrib)
attrib.update(self.coords2xml(relative, size))
attrib['name']=self.name
attrib['stroke']=self.color
if self.filled:
attrib['fill']=self.color
else:
attrib['fill']='none'
attrib['style']="stroke-width:%d; font-family: sans-serif; font-size: %d" % (self.linewidth, self.textsize)
e=ET.Element('text', attrib=attrib)
e.text=self.text
if self.link:
a=ET.Element('a', attrib={ 'xlink:href': self.link,
'title': self.link_label })
a.append(e)
yield a
else:
yield e
def __contains__(self, point):
# We cannot use the inherited method, since text is draw *above* x,y
x, y = point
return ( self.x <= x <= self.x + self.width
and self.y - self.height <= y <= self.y )
def edit_properties_widget(self):
"""Build a widget to edit the shape properties.
"""
vbox = super(Text, self).edit_properties_widget()
def label_widget(label, widget):
hb = Gtk.HBox()
hb.add(Gtk.Label(label=label))
hb.pack_start(widget, False, True, 0)
return hb
# Text
textsel = Gtk.Entry()
textsel.set_text(self.text)
label = label_widget(_("Text"), textsel)
vbox.pack_start(label, False, True, 0)
# Put the text at the beginning
vbox.reorder_child(label, 0)
vbox.widgets['text'] = textsel
# Text size
textsizesel = Gtk.SpinButton()
textsizesel.set_range(4, 80)
textsizesel.set_increments(1, 4)
textsizesel.set_value(self.textsize)
label = label_widget(_("Textsize"), textsizesel)
vbox.pack_start(label, False, True, 0)
vbox.reorder_child(label, 1)
vbox.widgets['textsize'] = textsizesel
return vbox
class Image(Rectangle):
"""Experimental Image shape.
It serves as a placeholder for the background image for the
moment, which is handled in the ShapeDrawer class. So the render
method is not implemented.
"""
SHAPENAME=_("Image")
SVGTAG='image'
# List of attributes holding the shape coordinates. The second
# element of the tuple is the index in the dimension tuple (width,
# height) used to compute relative sizes
coords=( ('x', 0),
('y', 1),
('width', 0),
('height', 1) )
def __init__(self, name=SHAPENAME, color="green", dimensions=None, uri=''):
super(Image, self).__init__(name, color, dimensions)
self.uri=uri
def render(self, context, invert=False):
# FIXME
return
@classmethod
def parse_svg(cls, element, context):
"""Parse a SVG representation.
The context object must implement a 'dimensions' method that
will return a (width, height) tuple corresponding to the
canvas size.
@param element: etree.Element to parse
@param context: the svg context
@return: an appropriate shape, or None if the class could not parse the element
"""
if element.tag != cls.SVGTAG and element.tag != ET.QName(SVGNS, cls.SVGTAG):
return None
s=cls(name=element.attrib.get('name', cls.SHAPENAME))
s.uri=element.attrib.get('xlink:href', element.attrib.get('{http://www.w3.org/1999/xlink}href', ''))
c=cls.xml2coords(cls.coords, element.attrib, context)
for n, v in c.items():
setattr(s, n, v)
s.svg_attrib=dict(element.attrib)
if hasattr(s, 'post_parse'):
s.post_parse()
return s
def get_svg(self, relative=False, size=None):
"""Return a SVG representation of the shape.
@param relative: should dimensions be relative to the container size or absolute?
@type relative: boolean
@param size: the container size in pixels
@type size: a couple of int
@return: the SVG representation
@rtype: elementtree.Element
"""
self.x=0
self.y=0
self.width=size[0]
self.height=size[1]
attrib=dict(self.svg_attrib)
attrib.update(self.coords2xml(relative, size))
attrib['name']=self.name
attrib['xlink:href']=self.uri
e=ET.Element(ET.QName(SVGNS, self.SVGTAG), attrib=attrib)
if self.link:
a=ET.Element('a', attrib={ 'xlink:href': self.link,
'title': self.link_label or _("Link to %s") % self.link })
a.append(e)
yield a
else:
yield e
def edit_properties_widget(self):
"""Build a widget to edit the shape properties.
"""
vbox=super(Image, self).edit_properties_widget()
def label_widget(label, widget):
hb=Gtk.HBox()
hb.add(Gtk.Label(label=label))
hb.pack_start(widget, False, True, 0)
return hb
# URI
urisel = Gtk.Entry()
urisel.set_text(self.uri)
vbox.pack_start(label_widget(_("Href"), urisel), False, False, 0)
vbox.widgets['uri']=urisel
return vbox
def __contains__(self, point):
return False
class Line(Rectangle):
"""A simple Line.
"""
SHAPENAME=_("Line")
SVGTAG='line'
coords=( ('x1', 0),
('y1', 1),
('x2', 0),
('y2', 1) )
def __init__(self, name=SHAPENAME, color="green", dimensions=None, arrow=False):
super(Line, self).__init__(name, color, dimensions)
self.arrow=arrow
self.arrowwidth=10
def set_bounds(self, bounds):
self.x1, self.y1 = bounds[0]
self.x2, self.y2 = bounds[1]
self.width = int(self.x2 - self.x1)
self.height = int(self.y2 - self.y1)
def get_bounds(self):
return ( (self.x1, self.y1), (self.x2, self.y2 ) )
def render(self, context, invert=False):
self.render_setup(context, invert)
context.move_to(self.x1, self.y1)
context.line_to(self.x2, self.y2)
if self.arrow:
theta=atan2( self.width, self.height )
ox=int(self.arrowwidth / 2) + 1
oy=self.arrowwidth
context.stroke()
context.new_path()
context.move_to(self.x2, self.y2)
context.line_to(int(self.x2 - ox * cos(theta) - oy * sin(theta)),
int(self.y2 + ox * sin(theta) - oy * cos(theta)))
context.line_to(int(self.x2 + ox * cos(theta) - oy * sin(theta)),
int(self.y2 - ox * sin(theta) - oy * cos(theta)))
context.close_path()
if self.filled:
context.fill()
else:
context.stroke()
return
def translate(self, vector):
self.x1 += int(vector[0])
self.x2 += int(vector[0])
self.y1 += int(vector[1])
self.y2 += int(vector[1])
# Recompute other attributes
self.set_bounds( self.get_bounds() )
def copy_from(self, shape, style=False):
shape.set_bounds( self.get_bounds() )
if style:
shape.color = self.color
shape.linewidth = self.linewidth
def control_point(self, point):
"""If on a control point, return its coordinates (x, y) and those of the other bound, else None
"""
x, y = point[0], point[1]
retval = None
if (abs(x - self.x1) <= self.tolerance
and abs(y - self.y1) <= self.tolerance):
retval = [ [self.x2, self.y2], [self.x1, self.y1] ]
elif (abs(x - self.x2) <= self.tolerance
and abs(y - self.y2) <= self.tolerance):
retval = [ [self.x1, self.y1], [self.x2, self.y2] ]
return retval
def __contains__(self, point):
x, y = point
if (self.x2 - self.x1) == 0:
return (min(self.y1, self.y2) < y < max(self.y1, self.y2)
and abs(x - self.x1) < self.tolerance )
a=1.0 * (self.y2 - self.y1) / (self.x2 - self.x1)
b=self.y1 - a * self.x1
return ( min(self.x1, self.x2) < x < max(self.x1, self.x2)
and min(self.y1, self.y2) < y < max(self.y1, self.y2)
and abs(y - (a * x + b)) < self.tolerance )
def edit_properties_widget(self):
"""Build a widget to edit the shape properties.
"""
vbox=super(Line, self).edit_properties_widget()
def label_widget(label, widget):
hb=Gtk.HBox()
hb.add(Gtk.Label(label=label))
hb.pack_start(widget, False, True, 0)
return hb
draw_arrow = Gtk.CheckButton(_("Draw an arrow"))
draw_arrow.set_active(self.arrow)
vbox.pack_start(draw_arrow, True, True, 0)
vbox.reorder_child(draw_arrow, 0)
vbox.widgets['arrow']=draw_arrow
# Arrow size
arrowsize = Gtk.SpinButton()
arrowsize.set_range(1, 40)
arrowsize.set_increments(1, 4)
arrowsize.set_value(self.arrowwidth)
label = label_widget(_("Arrow size"), arrowsize)
vbox.pack_start(label, False, True, 0)
vbox.reorder_child(label, 1)
vbox.widgets['arrowwidth']=arrowsize
return vbox
def post_parse(self):
"""Handle arrow markers.
"""
if 'marker-end' in self.svg_attrib:
self.arrow=True
self.arrowwidth=int(arrow_width_re.findall(self.svg_attrib['marker-end'])[0])
def get_svg(self, relative=False, size=None):
"""
<defs><marker id="myMarker" viewBox="0 0 10 10" refX="1" refY="5"
markerUnits="strokeWidth" orient="auto"
markerWidth="4" markerHeight="3">
<polyline points="0,0 10,5 0,10 1,5" fill="darkblue" />
</marker></defs>
"""
e=next(super(Line, self).get_svg(relative, size))
if self.arrow:
if e.tag == 'a' or e.tag == ET.QName(SVGNS, 'a'):
# It is a link. Use the child.
el=e[0]
else:
el=e
defs=ET.Element('defs')
marker=ET.Element('marker', {
'id': "arrow%d" % self.arrowwidth,
'viewBox': "0 0 10 10",
'refX': '5',
'refY': '5',
'orient': 'auto',
'markerWidth': str(int(self.arrowwidth / 2) + 1),
'markerHeight': str(self.arrowwidth) })
defs.append(marker)
marker.append(ET.Element('polyline', {
'points': "0,0 10,5 0,10 1,5",
'fill': self.color }))
el.attrib['marker-end']='url(#arrow%d)' % self.arrowwidth
yield defs
yield e
else:
yield e
class Path(Shape):
"""A path.
It is composed of multiple Lines.
"""
SHAPENAME=_("Path")
SVGTAG='path'
MULTIPOINT = True
coords = []
def __init__(self, name=SHAPENAME, color="green", dimensions=None):
# List of tuples (x, y) composing the path in absolute form
self.path = []
super(Path, self).__init__(name, color, dimensions)
self.controlled_point_index = -1
self.closed = False
def clone(self, style=None):
c = Path(self.name, self.color)
c.path = [ list(p) for p in self.path ]
return c
@property
def pathlines(self):
"""Returns the coordinates of the lines composing the path
"""
if self.closed:
return list(zip(self.path, self.path[1:] + self.path[:1]))
else:
return list(zip(self.path, self.path[1:]))
def set_controlled_point(self, index=None, point=None):
"""Specify the index of the controlled point.
If index is not given, then we will try to infer it from the
point information.
@param index: index of the point in self.path
@type index: integer (default -1)
@param point: coordinates of the controlled point
@type point: tuple (x, y)
"""
if index is None:
# Default will be last point in any case
index = -1
# Try to infer index from given point
for i, p in enumerate(self.path):
if p[0] == point[0] and p[1] == point[1]:
index = i
break
self.controlled_point_index = index
def add_point(self, point):
if self.path:
self.path.append( list(point) )
else:
self.path = [ list(point), list(point) ]
def remove_controlled_point(self):
del self.path[self.controlled_point_index]
self.controlled_point_index = -1
def set_bounds(self, bounds):
# Modify the controlled point
if self.path:
self.path[self.controlled_point_index] = list(bounds[1])