Debian Codegraph @

tools/clean_svg.py

raw
1 #! /usr/bin/env python3
2 #
3 # Copyright (c) 2013 Red Hat, Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # Author: Joaquim Rocha <[email protected]>
19 #
20
21 import logging
22 import sys
23 from pathlib import Path
24 from argparse import ArgumentParser
25 from xml.etree import ElementTree as ET
26
27 logging.basicConfig(level=logging.INFO)
28 logger = logging.getLogger("clean-svg")
29 logger.setLevel(logging.INFO)
30
31 NAMESPACE = "http://www.w3.org/2000/svg"
32 BRACKETS_NAMESPACE = "{" + NAMESPACE + "}"
33
34
35 def human_round(number):
36 """
37 Round to closest .5, keep integer values
38 """
39 v = round(number * 2) / 2.0
40 return int(v) if v == int(v) else v
41
42
43 def traverse_and_clean(node):
44 """
45 Clean the tree recursively
46 """
47 # Remove any non-SVG namespace attributes
48 for key in list(node.attrib.keys()):
49 if key.startswith("{"):
50 del node.attrib[key]
51 if "style" in node.attrib:
52 if node.tag == "text":
53 node.attrib["style"] = "text-anchor:start;"
54 elif node.tag != "svg":
55 del node.attrib["style"]
56
57 remove_transform_if_exists(node)
58
59 round_attrib(node, "d", "x", "y", "rx", "ry", "width", "height", "cx", "cy", "r")
60
61 for child in node:
62 traverse_and_clean(child)
63
64
65 def round_attrib(node, *attrs):
66 for attr_name in attrs:
67 attr_value = node.attrib.get(attr_name)
68 if attr_value is None:
69 continue
70 if attr_name == "d":
71 d = attr_value.replace(",", " ")
72 values = [round_if_number(value) for value in d.split()]
73 node.attrib[attr_name] = " ".join(values)
74 else:
75 node.attrib[attr_name] = round_if_number(attr_value)
76
77
78 def round_if_number(value):
79 try:
80 value = human_round(float(value.strip()))
81 except ValueError:
82 pass
83 return str(value)
84
85
86 def remove_non_svg_nodes_and_strip_namespace(root):
87 if root.tag.startswith(BRACKETS_NAMESPACE):
88 root.tag = root.tag[len(BRACKETS_NAMESPACE) :]
89 for elem in list(root):
90 if (
91 not elem.tag.startswith(BRACKETS_NAMESPACE)
92 or elem.tag == BRACKETS_NAMESPACE + "metadata"
93 ):
94 root.remove(elem)
95 else:
96 remove_non_svg_nodes_and_strip_namespace(elem)
97
98
99 def remove_transform_if_exists(node):
100 TRANSLATE = "translate"
101 MATRIX = "matrix"
102
103 transform = node.attrib.get("transform")
104 if transform is None:
105 return
106 transform = transform.strip()
107
108 if transform.startswith(TRANSLATE):
109 values = transform[len(TRANSLATE) + 1 : -1].split(",")
110 try:
111 x, y = float(values[0]), float(values[1])
112 except Exception:
113 return
114
115 apply_translation(node, 1, 0, 0, 1, x, y)
116 elif transform.startswith(MATRIX):
117 values = transform[len(MATRIX) + 1 : -1].split(",")
118 try:
119 a, b, c, d, e, f = [float(value.strip()) for value in values]
120 except Exception:
121 return
122 apply_translation(node, a, b, c, d, e, f)
123 apply_scaling(node, a, d)
124 del node.attrib["transform"]
125
126
127 def apply_translation(node, a, b, c, d, e, f):
128 x_attr, y_attr = "x", "y"
129 if node.tag == "circle":
130 x_attr, y_attr = "cx", "cy"
131 elif node.tag == "path":
132 apply_translation_to_path(node, e, f)
133 return
134 try:
135 x, y = float(node.attrib[x_attr]), float(node.attrib[y_attr])
136 new_x = x * a + y * c + 1 * e
137 new_y = x * b + y * d + 1 * f
138 node.attrib[x_attr] = str(new_x)
139 node.attrib[y_attr] = str(new_y)
140 except Exception:
141 pass
142
143
144 def apply_translation_to_path(node, x, y):
145 d = node.attrib.get("d")
146 if d is None:
147 return
148 d = d.replace(",", " ").split()
149 m_init_index = 0
150 length = len(d)
151 m_end_index = length
152 operation = "M"
153 i = 0
154 while i < length:
155 value = d[i]
156 if value.lower() == "m":
157 operation = value
158 m_init_index = i + 1
159 elif len(value) == 1 and value.isalpha():
160 m_end_index = i
161 break
162 i += 1
163 for i in range(m_init_index, m_end_index, 2):
164 d[i] = str(float(d[i]) + x)
165 d[i + 1] = str(float(d[i + 1]) + y)
166 if operation == "m":
167 break
168 node.attrib["d"] = (
169 " ".join(d[:m_init_index])
170 + " "
171 + " ".join(d[m_init_index:m_end_index])
172 + " ".join(d[m_end_index:])
173 )
174
175
176 def apply_scaling(node, x, y):
177 w_attr, h_attr = "width", "height"
178 if node.tag == "circle":
179 r = float(node.attrib.get("r", 1.0))
180 node.attrib["r"] = str(r * x)
181 try:
182 w = float(node.attrib[w_attr])
183 h = float(node.attrib[h_attr])
184 node.attrib[w_attr] = str(w * x)
185 node.attrib[h_attr] = str(h * y)
186 except Exception:
187 pass
188
189
190 def to_string_rec(node, level=0):
191 indent = "\n" + level * " "
192
193 tag_name = node.tag
194
195 # Remove 'defs' element. This cannot be done in the traverse_and_clean
196 # because somehow it is never found
197 if tag_name == "defs":
198 return ""
199
200 # use a list to put id and class as the first arguments
201 attribs = []
202 for attr in get_node_attrs_sorted(node):
203 attr_value = node.attrib.get(attr)
204 if attr_value is not None:
205 attribs.append(indent + ' %s="%s"' % (attr, attr_value))
206
207 string = indent + "<" + tag_name + "".join(attribs)
208 if len(node) or node.text:
209 string += ">"
210 if not node.text or not node.text.strip():
211 node.text = indent + " "
212 else:
213 string += node.text
214 if list(node):
215 for child in get_node_children_sorted(node):
216 string += to_string_rec(child, level + 1)
217 string += indent
218 string += "</%s>" % tag_name
219 else:
220 string += " />"
221 return string
222
223
224 def custom_tag_sort(arg):
225 """
226 Use as key functon in sorted().
227
228 Pre-fix arg tag name by a number in the sort order we want. Anything
229 unspecified defaults to 9. i.e. circle -> 1circle, thus sorts lower
230 than
231 other tags.
232 """
233 tag_order = {"title": 0, "rect": 1, "circle": 2, "path": 3}
234 return str(tag_order.get(arg.tag, 9)) + arg.tag
235
236
237 def get_node_children_sorted(node):
238 return sorted(node, key=custom_tag_sort)
239
240
241 def custom_attr_sort(arg):
242 """
243 Same as custom_tag_sort but for a node's attributes
244 """
245 attr_order = {
246 "id": 0,
247 "class": 1,
248 "x": 2,
249 "y": 3,
250 "cx": 4,
251 "cy": 5,
252 "width": 6,
253 "height": 7,
254 }
255 return str(attr_order.get(arg, 9)) + arg
256
257
258 def get_node_attrs_sorted(node):
259 attrs = node.attrib.keys()
260 return sorted(attrs, key=custom_attr_sort)
261
262
263 def apply_id_and_class_from_group(group_node):
264 button_assigned = label_assigned = path_assigned = False
265 _id = group_node.attrib.get("id")
266 if _id is None:
267 return
268 for child in group_node:
269 if child.tag == "rect" or child.tag == "circle":
270 if button_assigned:
271 continue
272 child.attrib["id"] = "Button%s" % _id
273 child.attrib["class"] = "%s Button" % _id
274 button_assigned = True
275 elif child.tag == "path":
276 if path_assigned:
277 continue
278 child.attrib["id"] = "Leader%s" % _id
279 child.attrib["class"] = "%s Leader" % _id
280 path_assigned = True
281 elif child.tag == "text":
282 if label_assigned:
283 continue
284 child.attrib["id"] = "Label%s" % _id
285 child.attrib["class"] = "%s Label" % _id
286 child.text = _id
287 label_assigned = True
288
289
290 def to_string(root):
291 header = """<?xml version="1.0" standalone="no"?>
292 <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
293 "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">"""
294 return header + to_string_rec(root)
295
296
297 def clean_svg(root, tabletname):
298 remove_non_svg_nodes_and_strip_namespace(root)
299 title = root.find("title")
300 if title is not None:
301 title.text = tabletname
302 root.attrib["xmlns"] = "http://www.w3.org/2000/svg"
303 traverse_and_clean(root)
304
305
306 if __name__ == "__main__":
307 parser = ArgumentParser(description="Clean SVG files for libwacom")
308 parser.add_argument(
309 "--debug",
310 action="store_true",
311 default=False,
312 help="Print debug logging output",
313 )
314 parser.add_argument(
315 "--ignore-missing",
316 action="store_true",
317 default=False,
318 help="Ignore .tablet files without a Layout",
319 )
320 parser.add_argument(
321 "filename",
322 type=str,
323 help="SVG file to clean or .tablet file with a Layout=xyz.svg line",
324 metavar="FILE",
325 )
326 parser.add_argument(
327 "tabletname",
328 type=str,
329 nargs="?",
330 help="The name of the tablet, can be omitted if FILE is a .tablet file",
331 metavar="TABLET_NAME",
332 )
333 args = parser.parse_args()
334
335 if args.debug:
336 logger.setLevel(logging.DEBUG)
337
338 svgfile = args.filename
339 tabletname = args.tabletname
340 if args.filename.endswith(".tablet"):
341 import configparser
342
343 config = configparser.ConfigParser()
344 config.read(args.filename)
345 try:
346 svgname = config["Device"]["Layout"]
347 if not svgname:
348 raise KeyError("Empty layout line")
349 except KeyError:
350 print(
351 f"{args.filename} does not specify a layout, skipping", file=sys.stderr
352 )
353 sys.exit(0 if args.ignore_missing else 77)
354 svgfile = Path(args.filename).parent / "layouts" / svgname
355 tabletname = config["Device"]["Name"]
356 else:
357 assert tabletname, "Argument TABLET_NAME must be provided for SVG files"
358
359 ET.register_namespace("", NAMESPACE)
360 try:
361 tree = ET.parse(svgfile)
362 except Exception as e:
363 sys.stderr.write(str(e) + "\n")
364 sys.exit(1)
365 root = tree.getroot()
366 clean_svg(root, tabletname)
367 print(to_string(root))