1 # This software is OSI Certified Open Source Software.
2 # OSI Certified is a certification mark of the Open Source Initiative.
3 #
4 # Copyright (c) 2006, Enthought, Inc.
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are met:
9 #
10 # * Redistributions of source code must retain the above copyright notice, this
11 # list of conditions and the following disclaimer.
12 # * Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 # * Neither the name of Enthought, Inc. nor the names of its contributors may
16 # be used to endorse or promote products derived from this software without
17 # specific prior written permission.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
23 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
26 # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 """ Small hand-written recursive descent parser for SVG <path> data.
33 In [1]: from svg_regex import svg_parser
35 In [3]: svg_parser.parse('M 10,20 30,40V50 60 70')
36 Out[3]: [('M', [(10.0, 20.0), (30.0, 40.0)]), ('V', [50.0, 60.0, 70.0])]
38 In [4]: svg_parser.parse('M 0.6051.5') # An edge case
39 Out[4]: [('M', [(0.60509999999999997, 0.5)])]
41 In [5]: svg_parser.parse('M 100-200') # Another edge case
42 Out[5]: [('M', [(100.0, -200.0)])]
43 """
45 import re
48 # Sentinel.
49 class _EOF(object):
50 def __repr__(self):
51 return 'EOF'
52 EOF = _EOF()
54 lexicon = [
55 ('float', r'[-\+]?(?:(?:[0-9]*\.[0-9]+)|(?:[0-9]+\.?))(?:[Ee][-\+]?[0-9]+)?'),
56 ('int', r'[-\+]?[0-9]+'),
57 ('command', r'[AaCcHhLlMmQqSsTtVvZz]'),
58 ]
61 class Lexer(object):
62 """ Break SVG path data into tokens.
64 The SVG spec requires that tokens are greedy. This lexer relies on Python's
65 regexes defaulting to greediness.
67 This style of implementation was inspired by this article:
69 http://www.gooli.org/blog/a-simple-lexer-in-python/
70 """
71 def __init__(self, lexicon):
72 self.lexicon = lexicon
73 parts = []
74 for name, regex in lexicon:
75 parts.append('(?P<%s>%s)' % (name, regex))
76 self.regex_string = '|'.join(parts)
77 self.regex = re.compile(self.regex_string)
79 def lex(self, text):
80 """ Yield (token_type, str_data) tokens.
82 The last token will be (EOF, None) where EOF is the singleton object
83 defined in this module.
84 """
85 for match in self.regex.finditer(text):
86 for name, _ in self.lexicon:
87 m = match.group(name)
88 if m is not None:
89 yield (name, m)
90 break
91 yield (EOF, None)
93 svg_lexer = Lexer(lexicon)
96 class SVGPathParser(object):
97 """ Parse SVG <path> data into a list of commands.
99 Each distinct command will take the form of a tuple (command, data). The
100 `command` is just the character string that starts the command group in the
101 <path> data, so 'M' for absolute moveto, 'm' for relative moveto, 'Z' for
102 closepath, etc. The kind of data it carries with it depends on the command.
103 For 'Z' (closepath), it's just None. The others are lists of individual
104 argument groups. Multiple elements in these lists usually mean to repeat the
105 command. The notable exception is 'M' (moveto) where only the first element
106 is truly a moveto. The remainder are implicit linetos.
108 See the SVG documentation for the interpretation of the individual elements
109 for each command.
111 The main method is `parse(text)`. It can only consume actual strings, not
112 filelike objects or iterators.
113 """
115 def __init__(self, lexer=svg_lexer):
116 self.lexer = lexer
118 self.command_dispatch = {
119 'Z': self.rule_closepath,
120 'z': self.rule_closepath,
121 'M': self.rule_moveto_or_lineto,
122 'm': self.rule_moveto_or_lineto,
123 'L': self.rule_moveto_or_lineto,
124 'l': self.rule_moveto_or_lineto,
125 'H': self.rule_orthogonal_lineto,
126 'h': self.rule_orthogonal_lineto,
127 'V': self.rule_orthogonal_lineto,
128 'v': self.rule_orthogonal_lineto,
129 'C': self.rule_curveto3,
130 'c': self.rule_curveto3,
131 'S': self.rule_curveto2,
132 's': self.rule_curveto2,
133 'Q': self.rule_curveto2,
134 'q': self.rule_curveto2,
135 'T': self.rule_curveto1,
136 't': self.rule_curveto1,
137 'A': self.rule_elliptical_arc,
138 'a': self.rule_elliptical_arc,
139 }
141 # self.number_tokens = set(['int', 'float'])
142 self.number_tokens = list(['int', 'float'])
144 def parse(self, text):
145 """ Parse a string of SVG <path> data.
146 """
147 next = self.lexer.lex(text).next
148 token = next()
149 return self.rule_svg_path(next, token)
151 def rule_svg_path(self, next, token):
152 commands = []
153 while token[0] is not EOF:
154 if token[0] != 'command':
155 raise SyntaxError("expecting a command; got %r" % (token,))
156 rule = self.command_dispatch[token[1]]
157 command_group, token = rule(next, token)
158 commands.append(command_group)
159 return commands
161 def rule_closepath(self, next, token):
162 command = token[1]
163 token = next()
164 return (command, None), token
166 def rule_moveto_or_lineto(self, next, token):
167 command = token[1]
168 token = next()
169 coordinates = []
170 while token[0] in self.number_tokens:
171 pair, token = self.rule_coordinate_pair(next, token)
172 coordinates.append(pair)
173 return (command, coordinates), token
175 def rule_orthogonal_lineto(self, next, token):
176 command = token[1]
177 token = next()
178 coordinates = []
179 while token[0] in self.number_tokens:
180 coord, token = self.rule_coordinate(next, token)
181 coordinates.append(coord)
182 return (command, coordinates), token
184 def rule_curveto3(self, next, token):
185 command = token[1]
186 token = next()
187 coordinates = []
188 while token[0] in self.number_tokens:
189 pair1, token = self.rule_coordinate_pair(next, token)
190 pair2, token = self.rule_coordinate_pair(next, token)
191 pair3, token = self.rule_coordinate_pair(next, token)
192 coordinates.append((pair1, pair2, pair3))
193 return (command, coordinates), token
195 def rule_curveto2(self, next, token):
196 command = token[1]
197 token = next()
198 coordinates = []
199 while token[0] in self.number_tokens:
200 pair1, token = self.rule_coordinate_pair(next, token)
201 pair2, token = self.rule_coordinate_pair(next, token)
202 coordinates.append((pair1, pair2))
203 return (command, coordinates), token
205 def rule_curveto1(self, next, token):
206 command = token[1]
207 token = next()
208 coordinates = []
209 while token[0] in self.number_tokens:
210 pair1, token = self.rule_coordinate_pair(next, token)
211 coordinates.append(pair1)
212 return (command, coordinates), token
214 def rule_elliptical_arc(self, next, token):
215 command = token[1]
216 token = next()
217 arguments = []
218 while token[0] in self.number_tokens:
219 rx = float(token[1])
220 if rx < 0.0:
221 raise SyntaxError("expecting a nonnegative number; got %r" % (token,))
223 token = next()
224 if token[0] not in self.number_tokens:
225 raise SyntaxError("expecting a number; got %r" % (token,))
226 ry = float(token[1])
227 if ry < 0.0:
228 raise SyntaxError("expecting a nonnegative number; got %r" % (token,))
230 token = next()
231 if token[0] not in self.number_tokens:
232 raise SyntaxError("expecting a number; got %r" % (token,))
233 axis_rotation = float(token[1])
235 token = next()
236 if token[1] not in ('0', '1'):
237 raise SyntaxError("expecting a boolean flag; got %r" % (token,))
238 large_arc_flag = bool(int(token[1]))
240 token = next()
241 if token[1] not in ('0', '1'):
242 raise SyntaxError("expecting a boolean flag; got %r" % (token,))
243 sweep_flag = bool(int(token[1]))
245 token = next()
246 if token[0] not in self.number_tokens:
247 raise SyntaxError("expecting a number; got %r" % (token,))
248 x = float(token[1])
250 token = next()
251 if token[0] not in self.number_tokens:
252 raise SyntaxError("expecting a number; got %r" % (token,))
253 y = float(token[1])
255 token = next()
256 arguments.append(((rx,ry), axis_rotation, large_arc_flag, sweep_flag, (x,y)))
258 return (command, arguments), token
260 def rule_coordinate(self, next, token):
261 if token[0] not in self.number_tokens:
262 raise SyntaxError("expecting a number; got %r" % (token,))
263 x = float(token[1])
264 token = next()
265 return x, token
268 def rule_coordinate_pair(self, next, token):
269 # Inline these since this rule is so common.
270 if token[0] not in self.number_tokens:
271 raise SyntaxError("expecting a number; got %r" % (token,))
272 x = float(token[1])
273 token = next()
274 if token[0] not in self.number_tokens:
275 raise SyntaxError("expecting a number; got %r" % (token,))
276 y = float(token[1])
277 token = next()
278 return (x,y), token
281 svg_parser = SVGPathParser()