ParseSVG.py 24 KB

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