File: base.py

package info (click to toggle)
svgwrite 1.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 2,092 kB
  • sloc: python: 12,603; makefile: 117; sh: 5
file content (282 lines) | stat: -rw-r--r-- 8,231 bytes parent folder | download
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
#!/usr/bin/env python
#coding:utf-8
# Author:  mozman
# Purpose: svg base element
# Created: 08.09.2010
# Copyright (C) 2010, Manfred Moitzi
# License: MIT License
"""
The **BaseElement** is the root for all SVG elements.
"""

from svgwrite.etree import etree

import copy

from svgwrite.params import Parameter
from svgwrite.utils import AutoID, to_unicode, PYTHON3


class BaseElement(object):
    """
    The **BaseElement** is the root for all SVG elements. The SVG attributes
    are stored in **attribs**, and the SVG subelements are stored in
    **elements**.

    """
    elementname = 'baseElement'

    def __init__(self, **extra):
        """
        :param extra: extra SVG attributes (keyword arguments)

          * add trailing '_' to reserved keywords: ``'class_'``, ``'from_'``
          * replace inner '-' by '_': ``'stroke_width'``


        SVG attribute names will be checked, if **debug** is `True`.

        workaround for removed **attribs** parameter in Version 0.2.2::

            # replace
            element = BaseElement(attribs=adict)

            #by
            element = BaseElement()
            element.update(adict)

        """
        # the keyword 'factory' specifies the object creator
        factory = extra.pop('factory', None)
        if factory is not None:
            # take parameter from 'factory'
            self._parameter = factory._parameter
        else:
            # default parameter debug=True profile='full'
            self._parameter = Parameter()

        # override debug setting
        debug = extra.pop('debug', None)
        if debug is not None:
            self._parameter.debug = debug

        # override profile setting
        profile = extra.pop('profile', None)
        if profile is not None:
            self._parameter.profile = profile

        self.attribs = dict()
        self.update(extra)
        self.elements = list()

    def update(self, attribs):
        """ Update SVG Attributes from `dict` attribs.

        Rules for keys:

        1. trailing '_' will be removed (``'class_'`` -> ``'class'``)
        2. inner '_' will be replaced by '-' (``'stroke_width'`` -> ``'stroke-width'``)

        """
        for key, value in attribs.items():
            # remove trailing underscores
            # and replace inner underscores
            key = key.rstrip('_').replace('_', '-')
            self.__setitem__(key, value)

    def copy(self):
        newobj = copy.copy(self)  # shallow copy of object
        newobj.attribs = copy.copy(self.attribs)  # shallow copy of attributes
        newobj.elements = copy.copy(self.elements)  # shallow copy of subelements
        if 'id' in newobj.attribs:  # create a new 'id'
            newobj['id'] = newobj.next_id()
        return newobj

    @property
    def debug(self):
        return self._parameter.debug

    @property
    def profile(self):
        return self._parameter.profile

    @property
    def validator(self):
        return self._parameter.validator

    @validator.setter
    def validator(self, value):
        self._parameter.validator = value

    @property
    def version(self):
        return self._parameter.get_version()

    def set_parameter(self, parameter):
        self._parameter = parameter

    def next_id(self, value=None):
        return AutoID.next_id(value)

    def get_id(self):
        """ Get the object `id` string, if the object does not have an `id`,
        a new `id` will be created.

        :returns: `string`
        """
        if 'id' not in self.attribs:
            self.attribs['id'] = self.next_id()
        return self.attribs['id']

    def get_iri(self):
        """
        Get the `IRI` reference string of the object. (i.e., ``'#id'``).

        :returns: `string`
        """
        return "#%s" % self.get_id()

    def get_funciri(self):
        """
        Get the `FuncIRI` reference string of the object. (i.e. ``'url(#id)'``).

        :returns: `string`
        """
        return "url(%s)" % self.get_iri()

    def __getitem__(self, key):
        """ Get SVG attribute by `key`.

        :param string key: SVG attribute name
        :return: SVG attribute value

        """
        return self.attribs[key]

    def __setitem__(self, key, value):
        """ Set SVG attribute by `key` to `value`.

        :param string key: SVG attribute name
        :param object value: SVG attribute value

        """
        # Attribute checking is only done by using the __setitem__() method or
        # by self['attribute'] = value
        if self.debug:
            self.validator.check_svg_attribute_value(self.elementname, key, value)
        self.attribs[key] = value

    def add(self, element):
        """ Add an SVG element as subelement.

        :param element: append this SVG element
        :returns: the added element

        """
        if self.debug:
            self.validator.check_valid_children(self.elementname, element.elementname)
        self.elements.append(element)
        return element

    def tostring(self):
        """ Get the XML representation as unicode `string`.

        :return: unicode XML string of this object and all its subelements

        """
        xml = self.get_xml()
        # required for Python 2 support
        xml_utf8_str = etree.tostring(xml, encoding='utf-8')
        return xml_utf8_str.decode('utf-8')
        # just Python 3: return etree.tostring(xml, encoding='unicode')
    
    def _repr_svg_(self):
        """ Show SVG in IPython, Jupyter Notebook, and Jupyter Lab

        :return: unicode XML string of this object and all its subelements

        """
        return self.tostring()

    def get_xml(self):
        """ Get the XML representation as `ElementTree` object.

        :return: XML `ElementTree` of this object and all its subelements

        """
        xml = etree.Element(self.elementname)
        if self.debug:
            self.validator.check_all_svg_attribute_values(self.elementname, self.attribs)
        for attribute, value in sorted(self.attribs.items()):
            # filter 'None' values
            if value is not None:
                value = self.value_to_string(value)
                if value:  # just add not empty attributes
                    xml.set(attribute, value)

        for element in self.elements:
            xml.append(element.get_xml())
        return xml

    def value_to_string(self, value):
        """
        Converts *value* into a <string> includes a value check, depending
        on :attr:`self.debug` and :attr:`self.profile`.

        """
        if isinstance(value, (int, float)):
            if self.debug:
                self.validator.check_svg_type(value, 'number')
            if isinstance(value, float) and self.profile == 'tiny':
                value = round(value, 4)
        return to_unicode(value)

    def set_desc(self, title=None, desc=None):
        """ Insert a **title** and/or a **desc** element as first subelement.
        """
        if desc is not None:
            self.elements.insert(0, Desc(desc))
        if title is not None:
            self.elements.insert(0, Title(title))

    def set_metadata(self, xmldata):
        """
        :param xmldata: an xml.etree.ElementTree - Element() object.
        """
        metadata = Metadata(xmldata)
        if len(self.elements) == 0:
            self.elements.append(metadata)
        else:
            pos = 0
            while self.elements[pos].elementname in ('title', 'desc'):
                pos += 1
                if pos == len(self.elements):
                    self.elements.append(metadata)
                    return
            self.elements.insert(pos, metadata)


class Title(object):
    elementname = 'title'

    def __init__(self, text):
        self.xml = etree.Element(self.elementname)
        self.xml.text = to_unicode(text)

    def get_xml(self):
        return self.xml


class Desc(Title):
    elementname = 'desc'


class Metadata(Title):
    elementname = 'metadata'

    def __init__(self, xmldata):
        """
        :param xmldata: an xml.etree.ElementTree - Element() object.
        """
        self.xml = etree.Element('metadata')
        self.xml.append(xmldata)