c4b76af56183f2f5147fc376f7d3c6dda1abdc91
[flexagon-toolkit.git] / src / diagram / svgwrite_diagram.py
1 #!/usr/bin/env python
2 #
3 # A Diagram abstraction based on svgwrite
4 #
5 # Copyright (C) 2018  Antonio Ospite <ao2@ao2.it>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 import warnings
21 from math import degrees
22 import svgwrite
23 from svgwrite.data.types import SVGAttribute
24 from .diagram import Diagram
25
26
27 class InkscapeDrawing(svgwrite.Drawing):
28     """An svgwrite.Drawing subclass which supports Inkscape layers"""
29     def __init__(self, *args, **kwargs):
30         super(InkscapeDrawing, self).__init__(*args, **kwargs)
31
32         inkscape_attributes = {
33             'xmlns:inkscape': SVGAttribute('xmlns:inkscape',
34                                            anim=False,
35                                            types=[],
36                                            const=frozenset(['http://www.inkscape.org/namespaces/inkscape'])),
37             'inkscape:groupmode': SVGAttribute('inkscape:groupmode',
38                                                anim=False,
39                                                types=[],
40                                                const=frozenset(['layer'])),
41             'inkscape:label': SVGAttribute('inkscape:label',
42                                            anim=False,
43                                            types=frozenset(['string']),
44                                            const=[])
45         }
46
47         self.validator.attributes.update(inkscape_attributes)
48
49         elements = self.validator.elements
50
51         svg_attributes = set(elements['svg'].valid_attributes)
52         svg_attributes.add('xmlns:inkscape')
53         elements['svg'].valid_attributes = frozenset(svg_attributes)
54
55         g_attributes = set(elements['g'].valid_attributes)
56         g_attributes.add('inkscape:groupmode')
57         g_attributes.add('inkscape:label')
58         elements['g'].valid_attributes = frozenset(g_attributes)
59
60         self['xmlns:inkscape'] = 'http://www.inkscape.org/namespaces/inkscape'
61
62     def layer(self, **kwargs):
63         """Create an inkscape layer.
64
65         An optional 'label' keyword argument can be passed to set a user
66         friendly name for the layer."""
67         label = kwargs.pop('label', None)
68
69         new_layer = self.g(**kwargs)
70         new_layer['inkscape:groupmode'] = 'layer'
71
72         if label:
73             new_layer['inkscape:label'] = label
74
75         return new_layer
76
77
78 class SvgwriteDiagram(Diagram):
79     def __init__(self, width, height, **kwargs):
80         super(SvgwriteDiagram, self).__init__(width, height, **kwargs)
81
82         self.svg = InkscapeDrawing(None, profile='full', size=(str(width) + "px", str(height) + "px"))
83         self.active_group = self.svg
84
85     def clear(self):
86         # Reset the SVG object
87         self.svg.elements = []
88         self.svg.add(self.svg.defs)
89
90         rect = self.svg.rect((0, 0), ('100%', '100%'))
91         self._fill(rect, self.background)
92         self.svg.add(rect)
93
94     def save_svg(self, filename):
95         self.svg.saveas(filename)
96
97     def add(self, element):
98         self.active_group.add(element)
99
100     def color_to_rgba(self, color):
101         color = super(SvgwriteDiagram, self).color_to_rgba(color)
102
103         return color[0] * 255, color[1] * 255, color[2] * 255, color[3]
104
105     def _fill(self, element, fill_color):
106         if fill_color:
107             r, g, b, a = self.color_to_rgba(fill_color)
108             fill_color = svgwrite.utils.rgb(r, g, b, mode='RGB')
109             element['fill'] = fill_color
110             element['fill-opacity'] = a
111         else:
112             element['fill'] = 'none'
113
114     def _stroke(self, element, stroke_color):
115         if stroke_color:
116             r, g, b, a = self.color_to_rgba(stroke_color)
117             stroke_color = svgwrite.utils.rgb(r, g, b, mode='RGB')
118             element['stroke'] = stroke_color
119             element['stroke-opacity'] = a
120             element['stroke-linejoin'] = 'round'
121             element['stroke-width'] = self.stroke_width
122         else:
123             element['stroke'] = 'none'
124
125     def draw_polygon_by_verts(self, verts,
126                               stroke_color=(0, 0, 0),
127                               fill_color=None):
128         polygon = self.svg.polygon(verts)
129
130         self._fill(polygon, fill_color)
131         self._stroke(polygon, stroke_color)
132
133         self.add(polygon)
134
135     def draw_star_by_verts(self, cx, cy, verts, stroke_color=(0, 0, 0)):
136         for v in verts:
137             line = self.svg.line((cx, cy), v)
138             self._stroke(line, stroke_color)
139             self.add(line)
140
141     def draw_circle(self, cx, cy, radius=10.0,
142                     stroke_color=None,
143                     fill_color=(0, 0, 0, 0.5)):
144         circle = self.svg.circle((cx, cy), radius)
145
146         self._fill(circle, fill_color)
147         self._stroke(circle, stroke_color)
148
149         self.add(circle)
150
151     def draw_line(self, x1, y1, x2, y2, stroke_color=(0, 0, 0, 1)):
152         line = self.svg.line((x1, y1), (x1, y2))
153         self._stroke(line, stroke_color)
154
155         self.add(line)
156
157     def draw_rect(self, x, y, width, height, theta=0,
158                   stroke_color=None,
159                   fill_color=(1, 1, 1, 0.8)):
160         rect = self.svg.rect((x, y), (width, height))
161
162         rect['transform'] = 'rotate(%f, %f, %f)' % (degrees(theta), x, y)
163
164         self._fill(rect, fill_color)
165         self._stroke(rect, stroke_color)
166
167         self.add(rect)
168
169     def draw_centered_text(self, cx, cy, text, theta=0.0,
170                            color=(0, 0, 0),
171                            align_baseline=False,
172                            bb_stroke_color=None,
173                            bb_fill_color=None):
174
175         # Using font_size to calculate dy is not optimal as the font _height_ may
176         # be different from the font_size, but it's better than nothing.
177         text_element = self.svg.text(text, x=[cx], y=[cy], dy=[self.font_size / 2.])
178         self._fill(text_element, color)
179         text_element['font-size'] = self.font_size
180         text_element['text-anchor'] = 'middle'
181         text_element['transform'] = 'rotate(%f, %f, %f)' % (degrees(theta), cx, cy)
182         self.add(text_element)
183
184         if align_baseline:
185             warnings.warn("The align_baseline option has not been implemented yet.")
186
187         if bb_stroke_color or bb_fill_color:
188             warnings.warn("Drawing the bounding box has not been implemented yet.")