Debian Codegraph @

pycontrib/svg2sfd.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright 2013 Google Inc. All rights reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # A simple script to convert svg files (generated by Illustrator plugin)
18 # to sfd, from which Fontforge can then create a font file.
19 #
20 # Contributors: Raph Levien ([email protected])
21
22 import sys
23 import os.path
24 import glob
25 import xml.dom.minidom
26 import re
27 import math
28
29 lastglyphnum = 0
30 char_num = 0x40
31 font_name = 'Untitled'
32 header_printed = False
33
34 def num_args_cmd(cmd):
35 if cmd.upper() == 'C': return 6
36 elif cmd.upper() in 'HV': return 1
37 elif cmd.upper() == 'S': return 4
38 elif cmd == 'z': return 0
39 return 2
40
41 def print_one_cmd(cmd, args):
42 scale = 40
43 yoff = 720
44 result = []
45 for i in range(len(args)):
46 if i & 1:
47 result.append('%f' % (yoff - scale * args[i]))
48 else:
49 result.append('%f' % (scale * args[i]))
50 result.append(cmd)
51 result.append('0') # TODO: should mark corner points
52 print ' '.join(result)
53
54 def apply_rel_xy(xy, args):
55 x0, y0 = xy
56 result = []
57 for i in range(0, len(args), 2):
58 x = x0 + args[i]
59 result.append(x)
60 y = y0 + args[i + 1]
61 result.append(y)
62 return result
63
64 def path_to_sfd(path):
65 # convert svg path syntax into sfd
66 # written for conciseness, not efficiency
67 x0, y0 = 0, 0
68 fre = re.compile(r'(\-?[0-9\.]+)\s*,?\s*')
69 while path.strip() != '':
70 path = path.strip()
71 if path[0].isalpha():
72 cmd = path[0]
73 path = path[1:].lstrip()
74 args = []
75 for i in range(num_args_cmd(cmd)):
76 m = fre.match(path)
77 if m is None:
78 print 'no float match:', path
79 args.append(float(m.group(1)))
80 path = path[m.end():]
81 #print cmd, args
82 if cmd.upper() == 'M':
83 if cmd.islower(): (x, y), args = apply_rel_xy([x, y], args)
84 x0, y0 = args
85 print_one_cmd('m', args)
86 x, y = args[-2:]
87 if cmd == 'm': cmd = 'l'
88 elif cmd == 'M': cmd = 'L'
89 elif cmd.upper() in 'CLVHS':
90 if cmd == 'H':
91 args = args + [y]
92 cmd = 'L'
93 elif cmd == 'h':
94 args = args + [0]
95 cmd = 'l'
96 if cmd == 'V':
97 args = [x] + args
98 cmd = 'L'
99 elif cmd == 'v':
100 args = [0] + args
101 cmd = 'l'
102 if cmd.islower(): args = apply_rel_xy([x, y], args)
103 if cmd.upper() == 'S':
104 # smooth curveto; reflect
105 args = [2 * x - xs, 2 * y - ys] + args
106 cmd = 'c'
107 print_one_cmd(cmd.lower(), args)
108 x, y = args[-2:]
109 if len(args) > 2:
110 xs, ys = args[-4:-2]
111 elif cmd.upper() == 'Z':
112 if x != x0 or y != y0:
113 print_one_cmd('l', [x0, y0])
114
115 def circle_to_sfd(cx, cy, r):
116 k = 4 * (math.sqrt(2) - 1) / 3
117 print_one_cmd('m', [cx, cy - r])
118 print_one_cmd('c', [cx + k * r, cy - r, cx + r, cy - k * r, cx + r, cy])
119 print_one_cmd('c', [cx + r, cy + k * r, cx + k * r, cy + r, cx, cy + r])
120 print_one_cmd('c', [cx - k * r, cy + r, cx - r, cy + k * r, cx - r, cy])
121 print_one_cmd('c', [cx - r, cy - k * r, cx - k * r, cy - r, cx, cy - r])
122
123 def conv_svg(fn, char, glyphnum = None):
124 global lastglyphnum
125 global header_printed
126 if not header_printed:
127 print_header()
128 if glyphnum == None:
129 glyphnum = lastglyphnum + 1
130 lastglyphnum = glyphnum
131 print 'StartChar:', os.path.basename(fn)[:-4]
132 print 'Encoding: %d %d %d' % (char, glyphnum, char)
133 print 'Width: %d' % (21 * 40)
134 print 'Flags: W'
135 print 'LayerCount: 2'
136 print 'Fore'
137 print 'SplineSet'
138 doc = xml.dom.minidom.parse(fn)
139 # TODO: reverse paths if fill color is white-ish (this is more code,
140 # and in the meantime, we'll rely on correct path direction in FF)
141 for path in doc.getElementsByTagName('path'):
142 path_to_sfd(path.getAttribute('d'))
143 for polygon in doc.getElementsByTagName('polygon'):
144 path_to_sfd('M' + polygon.getAttribute('points') + 'z')
145 for circle in doc.getElementsByTagName('circle'):
146 cx = float(circle.getAttribute('cx'))
147 cy = float(circle.getAttribute('cy'))
148 r = float(circle.getAttribute('r'))
149 circle_to_sfd(cx, cy, r)
150 print 'EndSplineSet'
151 print 'EndChar'
152
153 def print_header():
154 global header_printed
155 print '''SplineFontDB: 3.0
156 FontName: %s
157 FullName: %s
158 FamilyName: %s''' % (font_name, font_name, font_name)
159 print '''Weight: Medium
160 Copyright: Copyright (C) 2011 Google Inc.
161 Version: 001.000
162 UnderlinePosition: -120
163 UnderlineWidth: 40
164 Ascent: 800
165 Descent: 200
166 LayerCount: 2
167 Layer: 0 0 "Back" 1
168 Layer: 1 0 "Fore" 0
169 Encoding: unicode
170 OS2TypoAscent: 800
171 OS2TypeAOffset: 0
172 OS2TypoDescent: -200
173 OS2TypoDOffset: 0
174 OS2WinAscent: 800
175 OS2WinAOffset: 0
176 OS2WinDescent: 200
177 OS2WinDOffset: 0
178 HheadAscent: 800
179 HheadAOffset: 0
180 HheadDescent: 200
181 HheadDOffset: 0
182 BeginChars: 57600 57600
183 '''
184 header_printed = True
185
186 def print_footer():
187 print '''EndChars
188 EndSplineFont'''
189
190 def parse_int(x):
191 if x.startswith('0x'):
192 return int(x[2:], 16)
193 else:
194 return int(x)
195
196 def run_file(fn):
197 global char_num
198 global font_name
199 directory = ''
200 for l in file(fn).xreadlines():
201 if l.startswith('#'):
202 continue
203 s = l.strip().split()
204 if len(s) == 0:
205 continue
206 if s[0] == 'dir':
207 directory = s[1]
208 elif s[0] == 'fontname':
209 font_name = s[1]
210 elif s[0] == 'unicode':
211 char_num = parse_int(s[1])
212 elif s[0] == 'icon':
213 icon_fn = s[1]
214 if not icon_fn.endswith('.svg'):
215 icon_fn += '.svg'
216 if len(s) > 2:
217 char_num = parse_int(s[2])
218 conv_svg(os.path.join(directory, icon_fn), char_num)
219 char_num += 1
220
221 def main(args):
222 global char_num
223 for arg in args:
224 if os.path.isdir(arg):
225 for fn in glob.glob(arg + '/*.svg'):
226 conv_svg(fn, char_num)
227 char_num += 1
228 elif arg.endswith('.svg'):
229 conv_svg(arg, char_num)
230 char_num += 1
231 else:
232 run_file(arg)
233 print_footer()
234
235 if __name__ == '__main__':
236 main(sys.argv[1:])