File: utils.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 (288 lines) | stat: -rw-r--r-- 7,783 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
283
284
285
286
287
288
#!/usr/bin/env python
#coding:utf-8
# Author:  mozman
# Purpose: svg util functions and classes
# Created: 08.09.2010
# Copyright (C) 2010, Manfred Moitzi
# License: MIT License
"""

.. autofunction:: rgb

.. autofunction:: iterflatlist

.. autofunction:: strlist

.. autofunction:: get_unit

.. autofunction:: split_coordinate

.. autofunction:: split_angle

.. autofunction:: rect_top_left_corner

.. autofunction:: pretty_xml

"""
from __future__ import unicode_literals
import sys
import os
import base64

PYTHON3 = sys.version_info[0] > 2
from functools import partial

# Python 3 adaption
if PYTHON3:
    from urllib.request import urlopen
    to_unicode = str
    basestring = str
else:
    import warnings
    warnings.warn("Python 2 support will be dropped with version 1.4", DeprecationWarning)
    from urllib import urlopen
    def to_unicode(value):
        return unicode(value, encoding='utf8') if isinstance(value, str) else unicode(value)
# Python 3 adaption


def is_string(value):
    return isinstance(value, basestring)

from svgwrite.data import pattern


def rgb(r=0, g=0, b=0, mode='RGB'):
    """
    Convert **r**, **g**, **b** values to a `string`.

    :param r: red part
    :param g: green part
    :param b: blue part
    :param string mode: ``'RGB | %'``

    :rtype: string

    ========= =============================================================
    mode      Description
    ========= =============================================================
    ``'RGB'`` returns a rgb-string format: ``'rgb(r, g, b)'``
    ``'%'``   returns percent-values as rgb-string format: ``'rgb(r%, g%, b%)'``
    ========= =============================================================

    """
    def percent(value):
        value = float(value)
        if value < 0:
            value = 0
        if value > 100:
            value = 100
        return value

    if mode.upper() == 'RGB':
        return "rgb(%d,%d,%d)" % (int(r) & 255, int(g) & 255, int(b) & 255)
    elif mode == "%":
        # see http://www.w3.org/TR/SVG11/types.html#DataTypeColor
        # percentage is an 'number' value
        return "rgb(%d%%,%d%%,%d%%)" % (percent(r), percent(g), percent(b))
    else:
        raise ValueError("Invalid mode '%s'" % mode)


def iterflatlist(values):
    """
    Flatten nested *values*, returns an `iterator`.

    """
    for element in values:
        if hasattr(element, "__iter__") and not is_string(element):
            for item in iterflatlist(element):
                yield item
        else:
            yield element


def strlist(values, seperator=","):
    """
    Concatenate **values** with **sepertator**, `None` values will be excluded.

    :param values: `iterable` object
    :returns: `string`

    """
    if is_string(values):
        return values
    else:
        return seperator.join([str(value) for value in iterflatlist(values) if value is not None])


def get_unit(coordinate):
    """
    Get the `unit` identifier of **coordinate**, if **coordinate** has a valid
    `unit` identifier appended, else returns `None`.

    """
    if isinstance(coordinate, (int, float)):
        return None
    result = pattern.coordinate.match(coordinate)
    if result:
        return result.group(3)
    else:
        raise ValueError("Invalid format: '%s'" % coordinate)


def split_coordinate(coordinate):
    """
    Split coordinate into `<number>` and 'unit` identifier.

    :returns: <2-tuple> (number, unit-identifier) or (number, None) if no unit-identifier
      is present or coordinate is an int or float.

    """
    if isinstance(coordinate, (int, float)):
        return (float(coordinate), None)
    result = pattern.coordinate.match(coordinate)
    if result:
        return (float(result.group(1)), result.group(3))
    else:
        raise ValueError("Invalid format: '%s'" % coordinate)


def split_angle(angle):
    """
    Split angle into `<number>` and `<angle>` identifier.

    :returns: <2-tuple> (number, angle-identifier) or (number, None) if no angle-identifier
      is present or angle is an int or float.

    """

    if isinstance(angle, (int, float)):
        return (float(angle), None)
    result = pattern.angle.match(angle)
    if result:
        return (float(result.group(1)), result.group(3))
    else:
        raise ValueError("Invalid format: '%s'" % angle)


def rect_top_left_corner(insert, size, pos='top-left'):
    """
    Calculate top-left corner of a rectangle.

    **insert** and **size** must have the same units.

    :param 2-tuple insert: insert point
    :param 2-tuple size: (width, height)
    :param string pos: insert position ``'vert-horiz'``
    :return: ``'top-left'`` corner of the rect
    :rtype: 2-tuple

    ========== ==============================
    pos        valid values
    ========== ==============================
    **vert**   ``'top | middle | bottom'``
    **horiz**  ``'left'|'center'|'right'``
    ========== ==============================
    """
    vert, horiz = pos.lower().split('-')
    x, xunit = split_coordinate(insert[0])
    y, yunit = split_coordinate(insert[1])
    width, wunit = split_coordinate(size[0])
    height, hunit = split_coordinate(size[1])

    if xunit != wunit:
        raise ValueError("x-coordinate and width has to have the same unit")
    if yunit != hunit:
        raise ValueError("y-coordinate and height has to have the same unit")

    if horiz == 'center':
        x = x - width / 2.
    elif horiz == 'right':
        x = x - width
    elif horiz != 'left':
        raise ValueError("Invalid horizontal position: '%s'" % horiz)

    if vert == 'middle':
        y = y - height / 2.
    elif vert == 'bottom':
        y = y - height
    elif vert != 'top':
        raise ValueError("Invalid vertical position: '%s'" % vert)

    if xunit:
        x = "%s%s" %(x, xunit)
    if yunit:
        y = "%s%s" %(y, yunit)
    return (x, y)


class AutoID(object):
    _nextid = 1

    def __init__(self, value=None):
        self._set_value(value)

    @classmethod
    def _set_value(cls, value=None):
        if value is not None:
            cls._nextid = value

    @classmethod
    def next_id(cls, value=None):
        cls._set_value(value)
        retval = "id%d" % cls._nextid
        cls._nextid += 1
        return retval


def pretty_xml(xml_string, indent=2):
    """
    Create human readable XML string.

    :param xml_string: input xml string without line breaks and indentation
    :indent int: how much to indent, by default 2 spaces
    :return: xml_string with linebreaks and indentation

    """
    import xml.dom.minidom as minidom

    # check for empty string, len check avoids unnecessary string manipulation with large XML strings
    if len(xml_string) < 20 and xml_string.strip() == "":
        return ""
    if PYTHON3:
        xml_tree = minidom.parseString(xml_string)
    else:
        xml_tree = minidom.parseString(xml_string.encode('utf-8'))
    lines = xml_tree.toprettyxml(indent=' ' * indent).split('\n')
    # remove 1. line = xml declaration
    return '\n'.join(lines[1:])


FONT_MIMETYPES = {
    'ttf': "application/x-font-ttf",
    'otf': "application/x-font-opentype",
    'woff': "application/font-woff",
    'woff2': "application/font-woff2",
    'eot': "application/vnd.ms-fontobject",
    'sfnt': "application/font-sfnt",
}


def font_mimetype(name):
    _, ext = os.path.splitext(name.lower())
    return FONT_MIMETYPES[ext[1:]]


def base64_data(data, mimetype):
    data = base64.b64encode(data).decode()
    return "data:{mimetype};charset=utf-8;base64,{data}".format(mimetype=mimetype, data=data)


def find_first_url(text):
    import re
    result = re.findall(r"url\((.*?)\)", text)
    if result:
        return result[0]
    else:
        return None