ParseSVG.py 25 KB

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