Debian Codegraph @

tools/import-svg-to-ufo.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """
3 Convert SVG paths to UFO glyphs and that to a UFO font
4 Author: Santhosh Thottingal <[email protected]>
5 Copyright 2018, MIT License
6 """
7
8 from __future__ import print_function, absolute_import
9
10 __requires__ = ["FontTools"]
11
12 from fontTools.misc.py23 import SimpleNamespace
13 from fontTools.svgLib import SVGPath
14 from fontTools.ufoLib import UFOLibError, UFOReader, UFOWriter
15 from fontTools.ufoLib.pointPen import SegmentToPointPen
16 from fontTools.ufoLib.glifLib import writeGlyphToString
17 from fontTools.ufoLib.plistlib import load, writePlist
18
19 import argparse
20 import os
21 import re
22 import xml.etree.ElementTree as etree
23
24 class InfoObject(object):
25 pass
26
27
28 def parseSvg(path):
29 return etree.parse(path).getroot()
30
31 def getConfig(configFile):
32 import yaml
33 with open(configFile, 'r') as ymlfile:
34 cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)
35 return cfg
36
37
38 def split(arg):
39 return arg.replace(",", " ").split()
40
41
42 def svg2glif(svg_file, name, width=0, height=0, unicodes=None, transform=None,
43 version=2):
44 """ Convert an SVG outline to a UFO glyph with given 'name', advance
45 'width' and 'height' (int), and 'unicodes' (list of int).
46 Return the resulting string in GLIF format (default: version 2).
47 If 'transform' is provided, apply a transformation matrix before the
48 conversion (must be tuple of 6 floats, or a FontTools Transform object).
49 """
50 glyph = SimpleNamespace(width=width, height=height, unicodes=unicodes)
51 outline = SVGPath(svg_file, transform)
52
53 # writeGlyphToString takes a callable (usually a glyph's drawPoints
54 # method) that accepts a PointPen, however SVGPath currently only has
55 # a draw method that accepts a segment pen. We need to wrap the call
56 # with a converter pen.
57 def drawPoints(pointPen):
58 pen = SegmentToPointPen(pointPen)
59 outline.draw(pen)
60
61 return writeGlyphToString(name,
62 glyphObject=glyph,
63 drawPointsFunc=drawPoints,
64 formatVersion=version)
65
66
67 def transform_list(arg):
68 try:
69 return [float(n) for n in split(arg)]
70 except ValueError:
71 msg = "Invalid transformation matrix: %r" % arg
72 raise argparse.ArgumentTypeError(msg)
73
74
75 def unicode_hex_list(arg):
76 try:
77 return [int(unihex, 16) for unihex in split(arg)]
78 except ValueError:
79 msg = "Invalid unicode hexadecimal value: %r" % arg
80 raise argparse.ArgumentTypeError(msg)
81
82
83 def parse_args(args):
84 parser = argparse.ArgumentParser(
85 description="Convert SVG outlines to UFO glyphs (.glif)")
86 parser.add_argument(
87 "infile", metavar="INPUT.svg", help="Input SVG file containing "
88 '<path> elements with "d" attributes.')
89 parser.add_argument(
90 "outfile", metavar="OUTPUT.glif", help="Output GLIF file (default: "
91 "print to stdout)", nargs='?')
92 parser.add_argument(
93 "-c", "--config", help="The yaml configuration file containing the svg "
94 "to glif mapping", type=str, default="sources/svg-glif-mapping.yaml")
95 return parser.parse_args(args)
96
97
98 def main(args=None):
99 from io import open
100
101 options = parse_args(args)
102 config = getConfig(options.config)
103 svg_file = options.infile
104
105 # Parse SVG to read the width, height attributes defined in it
106 svgObj = parseSvg(svg_file)
107 width = float(svgObj.attrib['width'].replace("px", " "))
108 height = float(svgObj.attrib['height'].replace("px", " "))
109 name = os.path.splitext(os.path.basename(svg_file))[0]
110 ufo_font_path = config['font']['ufo']
111 # Get the font metadata from UFO
112 reader = UFOReader(ufo_font_path)
113 writer = UFOWriter(ufo_font_path)
114
115 infoObject = InfoObject()
116 reader.readInfo(infoObject)
117 fontName = config['font']['name']
118
119 # Get the configuration for this svg
120 try:
121 svg_config = config['svgs'][name]
122 except KeyError:
123 print("\033[93mSkip: Configuration not found for svg : %r\033[0m" % name)
124 return
125 if 'unicode' in svg_config:
126 unicodeVal = unicode_hex_list(svg_config['unicode'])
127 else:
128 unicodeVal = None
129 glyphWidth = width + int(svg_config['left']) + int(svg_config['right'])
130 if glyphWidth < 0 :
131 raise UFOLibError("Glyph %s has negative width." % name)
132
133 contentsPlistPath = ufo_font_path + '/glyphs/contents.plist'
134 try:
135 with open(contentsPlistPath, "rb") as f:
136 contentsPlist = load(f)
137 except:
138 raise UFOLibError("The file %s could not be read." % contentsPlistPath)
139
140 glyph_name = svg_config['glyph_name']
141 # Replace all capital letters with a following '_' to avoid file name clash in Windows
142 glyph_file_name = re.sub(r'([A-Z]){1}', lambda pat: pat.group(1) + '_', glyph_name) + '.glif'
143 if glyph_name in contentsPlist:
144 existing_glyph = True
145 else:
146 existing_glyph = False
147
148 # Calculate the transformation to do
149 transform = transform_list(config['font']['transform'])
150 base = 0
151 if 'base' in svg_config:
152 base=int(svg_config['base'])
153 transform[4] += int(svg_config['left']) # X offset = left bearing
154 transform[5] += height + base # Y offset
155
156 glif = svg2glif(svg_file,
157 name=svg_config['glyph_name'],
158 width=glyphWidth,
159 height=getattr(infoObject, 'unitsPerEm'),
160 unicodes=unicodeVal,
161 transform=transform,
162 version=config['font']['version'])
163
164 if options.outfile is None:
165 output_file = ufo_font_path + '/glyphs/' + glyph_file_name
166 else:
167 output_file = options.outfile
168 with open(output_file, 'w', encoding='utf-8') as f:
169 f.write(glif)
170
171 print("\033[94m[%s]\033[0m \033[92mConvert\033[0m %s -> %s \033[92m✔️\033[0m" %
172 (fontName, name, output_file))
173
174 # If this is a new glyph, add it to the UFO/glyphs/contents.plist
175 if not existing_glyph:
176 contentsPlist[glyph_name] = glyph_file_name
177 writePlistAtomically(contentsPlist, contentsPlistPath)
178 print("\033[94m[%s]\033[0m \033[92mAdd\033[0m %s -> %s \033[92m✔️\033[0m" %
179 (fontName, glyph_name, glyph_file_name))
180 lib_obj = reader.readLib()
181 lib_obj['public.glyphOrder'].append(glyph_name)
182 writer.writeLib(lib_obj)
183
184 if __name__ == "__main__":
185 import sys
186 sys.exit(main())