ParseSVG.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 12/18/2015 #
  6. # MIT Licence #
  7. # #
  8. # SVG Features supported: #
  9. # * Groups #
  10. # * Rectangles (w/ rounded corners) #
  11. # * Circles #
  12. # * Ellipses #
  13. # * Polygons #
  14. # * Polylines #
  15. # * Lines #
  16. # * Paths #
  17. # * All transformations #
  18. # #
  19. # Reference: www.w3.org/TR/SVG/Overview.html #
  20. # ##########################################################
  21. # import xml.etree.ElementTree as ET
  22. from svg.path import Line, Arc, CubicBezier, QuadraticBezier, parse_path
  23. # from svg.path.path import Move
  24. # from svg.path.path import Close
  25. import svg.path
  26. from shapely.geometry import LineString, MultiLineString
  27. from shapely.affinity import skew, affine_transform, rotate
  28. import numpy as np
  29. from appParsers.ParseFont import *
  30. log = logging.getLogger('base2')
  31. def svgparselength(lengthstr):
  32. """
  33. Parse an SVG length string into a float and a units
  34. string, if any.
  35. :param lengthstr: SVG length string.
  36. :return: Number and units pair.
  37. :rtype: tuple(float, str|None)
  38. """
  39. integer_re_str = r'[+-]?[0-9]+'
  40. number_re_str = r'(?:[+-]?[0-9]*\.[0-9]+(?:[Ee]' + integer_re_str + ')?' + r')|' + \
  41. r'(?:' + integer_re_str + r'(?:[Ee]' + integer_re_str + r')?)'
  42. length_re_str = r'(' + number_re_str + r')(em|ex|px|in|cm|mm|pt|pc|%)?'
  43. match = re.search(length_re_str, lengthstr)
  44. if match:
  45. return float(match.group(1)), match.group(2)
  46. return
  47. def path2shapely(path, object_type, res=1.0):
  48. """
  49. Converts an svg.path.Path into a Shapely
  50. Polygon or LinearString.
  51. :param path: svg.path.Path instance
  52. :param object_type:
  53. :param res: Resolution (minimum step along path)
  54. :return: Shapely geometry object
  55. :rtype : Polygon
  56. :rtype : LineString
  57. """
  58. points = []
  59. geometry = []
  60. rings = []
  61. closed = False
  62. for component in path:
  63. # Line
  64. if isinstance(component, Line):
  65. start = component.start
  66. x, y = start.real, start.imag
  67. if len(points) == 0 or points[-1] != (x, y):
  68. points.append((x, y))
  69. end = component.end
  70. points.append((end.real, end.imag))
  71. continue
  72. # Arc, CubicBezier or QuadraticBezier
  73. if isinstance(component, Arc) or \
  74. isinstance(component, CubicBezier) or \
  75. isinstance(component, QuadraticBezier):
  76. # How many points to use in the discrete representation.
  77. length = component.length(res / 10.0)
  78. # steps = int(length / res + 0.5)
  79. steps = int(length) * 2
  80. # solve error when step is below 1,
  81. # it may cause other problems, but LineString needs at least two points
  82. if steps == 0:
  83. steps = 1
  84. frac = 1.0 / steps
  85. # print length, steps, frac
  86. for i in range(steps):
  87. point = component.point(i * frac)
  88. x, y = point.real, point.imag
  89. if len(points) == 0 or points[-1] != (x, y):
  90. points.append((x, y))
  91. end = component.point(1.0)
  92. points.append((end.real, end.imag))
  93. continue
  94. # Move
  95. if isinstance(component, svg.path.Move):
  96. if not points:
  97. continue
  98. else:
  99. rings.append(points)
  100. if closed is False:
  101. points = []
  102. else:
  103. closed = False
  104. start = component.start
  105. x, y = start.real, start.imag
  106. points = [(x, y)]
  107. continue
  108. closed = False
  109. # Close
  110. if isinstance(component, svg.path.Close):
  111. if not points:
  112. continue
  113. else:
  114. rings.append(points)
  115. points = []
  116. closed = True
  117. continue
  118. log.warning("I don't know what this is: %s" % str(component))
  119. continue
  120. # if there are still points in points then add them to the last ring
  121. if points:
  122. rings.append(points)
  123. try:
  124. rings = MultiLineString(rings)
  125. except Exception as e:
  126. log.debug("ParseSVG.path2shapely() MString --> %s" % str(e))
  127. return None
  128. if len(rings) > 0:
  129. if len(rings) == 1 and not isinstance(rings, MultiLineString):
  130. # Polygons are closed and require more than 2 points
  131. if Point(rings[0][0]).almost_equals(Point(rings[0][-1])) and len(rings[0]) > 2:
  132. geo_element = Polygon(rings[0])
  133. else:
  134. geo_element = LineString(rings[0])
  135. else:
  136. try:
  137. geo_element = Polygon(rings[0], rings[1:])
  138. except Exception:
  139. coords = []
  140. for line in rings:
  141. coords.append(line.coords[0])
  142. coords.append(line.coords[1])
  143. try:
  144. geo_element = Polygon(coords)
  145. except Exception:
  146. geo_element = LineString(coords)
  147. geometry.append(geo_element)
  148. return geometry
  149. def svgrect2shapely(rect, n_points=32):
  150. """
  151. Converts an SVG rect into Shapely geometry.
  152. :param rect: Rect Element
  153. :type rect: xml.etree.ElementTree.Element
  154. :param n_points: number of points to approximate circles
  155. :type n_points: int
  156. :return: shapely.geometry.polygon.LinearRing
  157. """
  158. w = svgparselength(rect.get('width'))[0]
  159. h = svgparselength(rect.get('height'))[0]
  160. x_obj = rect.get('x')
  161. if x_obj is not None:
  162. x = svgparselength(x_obj)[0]
  163. else:
  164. x = 0
  165. y_obj = rect.get('y')
  166. if y_obj is not None:
  167. y = svgparselength(y_obj)[0]
  168. else:
  169. y = 0
  170. rxstr = rect.get('rx')
  171. rystr = rect.get('ry')
  172. if rxstr is None and rystr is None: # Sharp corners
  173. pts = [
  174. (x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)
  175. ]
  176. else: # Rounded corners
  177. rx = 0.0 if rxstr is None else svgparselength(rxstr)[0]
  178. ry = 0.0 if rystr is None else svgparselength(rystr)[0]
  179. n_points = int(n_points / 4 + 0.5)
  180. t = np.arange(n_points, dtype=float) / n_points / 4
  181. x_ = (x + w - rx) + rx * np.cos(2 * np.pi * (t + 0.75))
  182. y_ = (y + ry) + ry * np.sin(2 * np.pi * (t + 0.75))
  183. lower_right = [(x_[i], y_[i]) for i in range(n_points)]
  184. x_ = (x + w - rx) + rx * np.cos(2 * np.pi * t)
  185. y_ = (y + h - ry) + ry * np.sin(2 * np.pi * t)
  186. upper_right = [(x_[i], y_[i]) for i in range(n_points)]
  187. x_ = (x + rx) + rx * np.cos(2 * np.pi * (t + 0.25))
  188. y_ = (y + h - ry) + ry * np.sin(2 * np.pi * (t + 0.25))
  189. upper_left = [(x_[i], y_[i]) for i in range(n_points)]
  190. x_ = (x + rx) + rx * np.cos(2 * np.pi * (t + 0.5))
  191. y_ = (y + ry) + ry * np.sin(2 * np.pi * (t + 0.5))
  192. lower_left = [(x_[i], y_[i]) for i in range(n_points)]
  193. pts = [(x + rx, y), (x - rx + w, y)] + \
  194. lower_right + \
  195. [(x + w, y + ry), (x + w, y + h - ry)] + \
  196. upper_right + \
  197. [(x + w - rx, y + h), (x + rx, y + h)] + \
  198. upper_left + \
  199. [(x, y + h - ry), (x, y + ry)] + \
  200. lower_left
  201. return Polygon(pts).buffer(0)
  202. # return LinearRing(pts)
  203. def svgcircle2shapely(circle):
  204. """
  205. Converts an SVG circle into Shapely geometry.
  206. :param circle: Circle Element
  207. :type circle: xml.etree.ElementTree.Element
  208. :return: Shapely representation of the circle.
  209. :rtype: shapely.geometry.polygon.LinearRing
  210. """
  211. # cx = float(circle.get('cx'))
  212. # cy = float(circle.get('cy'))
  213. # r = float(circle.get('r'))
  214. cx = svgparselength(circle.get('cx'))[0] # TODO: No units support yet
  215. cy = svgparselength(circle.get('cy'))[0] # TODO: No units support yet
  216. r = svgparselength(circle.get('r'))[0] # TODO: No units support yet
  217. # TODO: No resolution specified.
  218. return Point(cx, cy).buffer(r)
  219. def svgellipse2shapely(ellipse, n_points=64):
  220. """
  221. Converts an SVG ellipse into Shapely geometry
  222. :param ellipse: Ellipse Element
  223. :type ellipse: xml.etree.ElementTree.Element
  224. :param n_points: Number of discrete points in output.
  225. :return: Shapely representation of the ellipse.
  226. :rtype: shapely.geometry.polygon.LinearRing
  227. """
  228. cx = svgparselength(ellipse.get('cx'))[0] # TODO: No units support yet
  229. cy = svgparselength(ellipse.get('cy'))[0] # TODO: No units support yet
  230. rx = svgparselength(ellipse.get('rx'))[0] # TODO: No units support yet
  231. ry = svgparselength(ellipse.get('ry'))[0] # TODO: No units support yet
  232. t = np.arange(n_points, dtype=float) / n_points
  233. x = cx + rx * np.cos(2 * np.pi * t)
  234. y = cy + ry * np.sin(2 * np.pi * t)
  235. pts = [(x[i], y[i]) for i in range(n_points)]
  236. return Polygon(pts).buffer(0)
  237. # return LinearRing(pts)
  238. def svgline2shapely(line):
  239. """
  240. :param line: Line element
  241. :type line: xml.etree.ElementTree.Element
  242. :return: Shapely representation on the line.
  243. :rtype: shapely.geometry.polygon.LinearRing
  244. """
  245. x1 = svgparselength(line.get('x1'))[0]
  246. y1 = svgparselength(line.get('y1'))[0]
  247. x2 = svgparselength(line.get('x2'))[0]
  248. y2 = svgparselength(line.get('y2'))[0]
  249. return LineString([(x1, y1), (x2, y2)])
  250. def svgpolyline2shapely(polyline):
  251. ptliststr = polyline.get('points')
  252. points = parse_svg_point_list(ptliststr)
  253. return LineString(points)
  254. def svgpolygon2shapely(polygon):
  255. ptliststr = polygon.get('points')
  256. points = parse_svg_point_list(ptliststr)
  257. return Polygon(points).buffer(0)
  258. # return LinearRing(points)
  259. def getsvggeo(node, object_type, root=None):
  260. """
  261. Extracts and flattens all geometry from an SVG node
  262. into a list of Shapely geometry.
  263. :param node: xml.etree.ElementTree.Element
  264. :param object_type:
  265. :return: List of Shapely geometry
  266. :rtype: list
  267. """
  268. if root is None:
  269. root = node
  270. kind = re.search('(?:\{.*\})?(.*)$', node.tag).group(1)
  271. geo = []
  272. # Recurse
  273. if len(node) > 0:
  274. for child in node:
  275. subgeo = getsvggeo(child, object_type, root)
  276. if subgeo is not None:
  277. geo += subgeo
  278. # Parse
  279. elif kind == 'path':
  280. log.debug("***PATH***")
  281. P = parse_path(node.get('d'))
  282. P = path2shapely(P, object_type)
  283. # for path, the resulting geometry is already a list so no need to create a new one
  284. geo = P
  285. elif kind == 'rect':
  286. log.debug("***RECT***")
  287. R = svgrect2shapely(node)
  288. geo = [R]
  289. elif kind == 'circle':
  290. log.debug("***CIRCLE***")
  291. C = svgcircle2shapely(node)
  292. geo = [C]
  293. elif kind == 'ellipse':
  294. log.debug("***ELLIPSE***")
  295. E = svgellipse2shapely(node)
  296. geo = [E]
  297. elif kind == 'polygon':
  298. log.debug("***POLYGON***")
  299. poly = svgpolygon2shapely(node)
  300. geo = [poly]
  301. elif kind == 'line':
  302. log.debug("***LINE***")
  303. line = svgline2shapely(node)
  304. geo = [line]
  305. elif kind == 'polyline':
  306. log.debug("***POLYLINE***")
  307. pline = svgpolyline2shapely(node)
  308. geo = [pline]
  309. elif kind == 'use':
  310. log.debug('***USE***')
  311. # href= is the preferred name for this[1], but inkscape still generates xlink:href=.
  312. # [1] https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use#Attributes
  313. href = node.attrib['href'] if 'href' in node.attrib else node.attrib['{http://www.w3.org/1999/xlink}href']
  314. ref = root.find(".//*[@id='%s']" % href.replace('#', ''))
  315. if ref is not None:
  316. geo = getsvggeo(ref, object_type, root)
  317. else:
  318. log.warning("Unknown kind: " + kind)
  319. geo = None
  320. # ignore transformation for unknown kind
  321. if geo is not None:
  322. # Transformations
  323. if 'transform' in node.attrib:
  324. trstr = node.get('transform')
  325. trlist = parse_svg_transform(trstr)
  326. # log.debug(trlist)
  327. # Transformations are applied in reverse order
  328. for tr in trlist[::-1]:
  329. if tr[0] == 'translate':
  330. geo = [translate(geoi, tr[1], tr[2]) for geoi in geo]
  331. elif tr[0] == 'scale':
  332. geo = [scale(geoi, tr[1], tr[2], origin=(0, 0))
  333. for geoi in geo]
  334. elif tr[0] == 'rotate':
  335. geo = [rotate(geoi, tr[1], origin=(tr[2], tr[3]))
  336. for geoi in geo]
  337. elif tr[0] == 'skew':
  338. geo = [skew(geoi, tr[1], tr[2], origin=(0, 0))
  339. for geoi in geo]
  340. elif tr[0] == 'matrix':
  341. geo = [affine_transform(geoi, tr[1:]) for geoi in geo]
  342. else:
  343. raise Exception('Unknown transformation: %s', tr)
  344. return geo
  345. def getsvgtext(node, object_type, units='MM'):
  346. """
  347. Extracts and flattens all geometry from an SVG node
  348. into a list of Shapely geometry.
  349. :param node: xml.etree.ElementTree.Element
  350. :param object_type:
  351. :return: List of Shapely geometry
  352. :rtype: list
  353. """
  354. kind = re.search('(?:\{.*\})?(.*)$', node.tag).group(1)
  355. geo = []
  356. # Recurse
  357. if len(node) > 0:
  358. for child in node:
  359. subgeo = getsvgtext(child, object_type, units=units)
  360. if subgeo is not None:
  361. geo += subgeo
  362. # Parse
  363. elif kind == 'tspan':
  364. current_attrib = node.attrib
  365. txt = node.text
  366. style_dict = {}
  367. parrent_attrib = node.getparent().attrib
  368. style = parrent_attrib['style']
  369. try:
  370. style_list = style.split(';')
  371. for css in style_list:
  372. style_dict[css.rpartition(':')[0]] = css.rpartition(':')[-1]
  373. pos_x = float(current_attrib['x'])
  374. pos_y = float(current_attrib['y'])
  375. # should have used the instance from FlatCAMApp.App but how? without reworking everything ...
  376. pf = ParseFont()
  377. pf.get_fonts_by_types()
  378. font_name = style_dict['font-family'].replace("'", '')
  379. if style_dict['font-style'] == 'italic' and style_dict['font-weight'] == 'bold':
  380. font_type = 'bi'
  381. elif style_dict['font-weight'] == 'bold':
  382. font_type = 'bold'
  383. elif style_dict['font-style'] == 'italic':
  384. font_type = 'italic'
  385. else:
  386. font_type = 'regular'
  387. # value of 2.2 should have been 2.83 (conversion value from pixels to points)
  388. # but the dimensions from Inkscape did not corelate with the ones after importing in FlatCAM
  389. # so I adjusted this
  390. font_size = svgparselength(style_dict['font-size'])[0] * 2.2
  391. geo = [pf.font_to_geometry(txt,
  392. font_name=font_name,
  393. font_size=font_size,
  394. font_type=font_type,
  395. units=units,
  396. coordx=pos_x,
  397. coordy=pos_y)
  398. ]
  399. geo = [(scale(g, 1.0, -1.0)) for g in geo]
  400. except Exception as e:
  401. log.debug(str(e))
  402. else:
  403. geo = None
  404. # ignore transformation for unknown kind
  405. if geo is not None:
  406. # Transformations
  407. if 'transform' in node.attrib:
  408. trstr = node.get('transform')
  409. trlist = parse_svg_transform(trstr)
  410. # log.debug(trlist)
  411. # Transformations are applied in reverse order
  412. for tr in trlist[::-1]:
  413. if tr[0] == 'translate':
  414. geo = [translate(geoi, tr[1], tr[2]) for geoi in geo]
  415. elif tr[0] == 'scale':
  416. geo = [scale(geoi, tr[1], tr[2], origin=(0, 0))
  417. for geoi in geo]
  418. elif tr[0] == 'rotate':
  419. geo = [rotate(geoi, tr[1], origin=(tr[2], tr[3]))
  420. for geoi in geo]
  421. elif tr[0] == 'skew':
  422. geo = [skew(geoi, tr[1], tr[2], origin=(0, 0))
  423. for geoi in geo]
  424. elif tr[0] == 'matrix':
  425. geo = [affine_transform(geoi, tr[1:]) for geoi in geo]
  426. else:
  427. raise Exception('Unknown transformation: %s', tr)
  428. return geo
  429. def parse_svg_point_list(ptliststr):
  430. """
  431. Returns a list of coordinate pairs extracted from the "points"
  432. attribute in SVG polygons and polyline's.
  433. :param ptliststr: "points" attribute string in polygon or polyline.
  434. :return: List of tuples with coordinates.
  435. """
  436. pairs = []
  437. last = None
  438. pos = 0
  439. i = 0
  440. for match in re.finditer(r'(\s*,\s*)|(\s+)', ptliststr.strip(' ')):
  441. val = float(ptliststr[pos:match.start()])
  442. if i % 2 == 1:
  443. pairs.append((last, val))
  444. else:
  445. last = val
  446. pos = match.end()
  447. i += 1
  448. # Check for last element
  449. val = float(ptliststr[pos:])
  450. if i % 2 == 1:
  451. pairs.append((last, val))
  452. else:
  453. log.warning("Incomplete coordinates.")
  454. return pairs
  455. def parse_svg_transform(trstr):
  456. """
  457. Parses an SVG transform string into a list
  458. of transform names and their parameters.
  459. Possible transformations are:
  460. * Translate: translate(<tx> [<ty>]), which specifies
  461. a translation by tx and ty. If <ty> is not provided,
  462. it is assumed to be zero. Result is
  463. ['translate', tx, ty]
  464. * Scale: scale(<sx> [<sy>]), which specifies a scale operation
  465. by sx and sy. If <sy> is not provided, it is assumed to be
  466. equal to <sx>. Result is: ['scale', sx, sy]
  467. * Rotate: rotate(<rotate-angle> [<cx> <cy>]), which specifies
  468. a rotation by <rotate-angle> degrees about a given point.
  469. If optional parameters <cx> and <cy> are not supplied,
  470. the rotate is about the origin of the current user coordinate
  471. system. Result is: ['rotate', rotate-angle, cx, cy]
  472. * Skew: skewX(<skew-angle>), which specifies a skew
  473. transformation along the x-axis. skewY(<skew-angle>), which
  474. specifies a skew transformation along the y-axis.
  475. Result is ['skew', angle-x, angle-y]
  476. * Matrix: matrix(<a> <b> <c> <d> <e> <f>), which specifies a
  477. transformation in the form of a transformation matrix of six
  478. values. matrix(a,b,c,d,e,f) is equivalent to applying the
  479. transformation matrix [a b c d e f]. Result is
  480. ['matrix', a, b, c, d, e, f]
  481. Note: All parameters to the transformations are "numbers",
  482. i.e. no units present.
  483. :param trstr: SVG transform string.
  484. :type trstr: str
  485. :return: List of transforms.
  486. :rtype: list
  487. """
  488. trlist = []
  489. assert isinstance(trstr, str)
  490. trstr = trstr.strip(' ')
  491. integer_re_str = r'[+-]?[0-9]+'
  492. number_re_str = r'(?:[+-]?[0-9]*\.[0-9]+(?:[Ee]' + integer_re_str + ')?' + r')|' + \
  493. r'(?:' + integer_re_str + r'(?:[Ee]' + integer_re_str + r')?)'
  494. # num_re_str = r'[\+\-]?[0-9\.e]+' # TODO: Negative exponents missing
  495. comma_or_space_re_str = r'(?:(?:\s+)|(?:\s*,\s*))'
  496. translate_re_str = r'translate\s*\(\s*(' + \
  497. number_re_str + r')(?:' + \
  498. comma_or_space_re_str + \
  499. r'(' + number_re_str + r'))?\s*\)'
  500. scale_re_str = r'scale\s*\(\s*(' + \
  501. number_re_str + r')' + \
  502. r'(?:' + comma_or_space_re_str + \
  503. r'(' + number_re_str + r'))?\s*\)'
  504. skew_re_str = r'skew([XY])\s*\(\s*(' + \
  505. number_re_str + r')\s*\)'
  506. rotate_re_str = r'rotate\s*\(\s*(' + \
  507. number_re_str + r')' + \
  508. r'(?:' + comma_or_space_re_str + \
  509. r'(' + number_re_str + r')' + \
  510. comma_or_space_re_str + \
  511. r'(' + number_re_str + r'))?\s*\)'
  512. matrix_re_str = r'matrix\s*\(\s*' + \
  513. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  514. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  515. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  516. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  517. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  518. r'(' + number_re_str + r')\s*\)'
  519. while len(trstr) > 0:
  520. match = re.search(r'^' + translate_re_str, trstr)
  521. if match:
  522. trlist.append([
  523. 'translate',
  524. float(match.group(1)),
  525. float(match.group(2)) if (match.group(2) is not None) else 0.0
  526. ])
  527. trstr = trstr[len(match.group(0)):].strip(' ')
  528. continue
  529. match = re.search(r'^' + scale_re_str, trstr)
  530. if match:
  531. trlist.append([
  532. 'scale',
  533. float(match.group(1)),
  534. float(match.group(2)) if (match.group(2) is not None) else float(match.group(1))
  535. ])
  536. trstr = trstr[len(match.group(0)):].strip(' ')
  537. continue
  538. match = re.search(r'^' + skew_re_str, trstr)
  539. if match:
  540. trlist.append([
  541. 'skew',
  542. float(match.group(2)) if match.group(1) == 'X' else 0.0,
  543. float(match.group(2)) if match.group(1) == 'Y' else 0.0
  544. ])
  545. trstr = trstr[len(match.group(0)):].strip(' ')
  546. continue
  547. match = re.search(r'^' + rotate_re_str, trstr)
  548. if match:
  549. trlist.append([
  550. 'rotate',
  551. float(match.group(1)),
  552. float(match.group(2)) if match.group(2) else 0.0,
  553. float(match.group(3)) if match.group(3) else 0.0
  554. ])
  555. trstr = trstr[len(match.group(0)):].strip(' ')
  556. continue
  557. match = re.search(r'^' + matrix_re_str, trstr)
  558. if match:
  559. trlist.append(['matrix'] + [float(x) for x in match.groups()])
  560. trstr = trstr[len(match.group(0)):].strip(' ')
  561. continue
  562. # raise Exception("Don't know how to parse: %s" % trstr)
  563. log.error("[ERROR] Don't know how to parse: %s" % trstr)
  564. return trlist
  565. # if __name__ == "__main__":
  566. # tree = ET.parse('tests/svg/drawing.svg')
  567. # root = tree.getroot()
  568. # ns = re.search(r'\{(.*)\}', root.tag).group(1)
  569. # print(ns)
  570. # for geo in getsvggeo(root):
  571. # print(geo)