1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
|
#!/usr/bin/env python
from __future__ import print_function, absolute_import
import sys, os
from os.path import dirname, basename, abspath, relpath, join as pjoin
sys.path.append(abspath(pjoin(dirname(__file__), 'tools')))
from common import BASEDIR, VENVDIR, getGitHash, getVersion
import argparse
import datetime
import glyphsLib
import logging
import re
import signal
import subprocess
from fontmake.font_project import FontProject
from fontTools import designspaceLib
from glyphsLib.interpolation import apply_instance_data
from mutatorMath.ufo.document import DesignSpaceDocumentReader
stripItalic_re = re.compile(r'(?:^|\b)italic(?:\b|$)', re.I | re.U)
def stripItalic(name):
return stripItalic_re.sub('', name.strip())
def sighandler(signum, frame):
sys.stdout.write('\n')
sys.stdout.flush()
sys.exit(1)
def mkdirs(path):
if not os.access(path, os.F_OK):
os.makedirs(path)
# setFontInfo patches font.info
#
def setFontInfo(font, weight, updateCreated=True):
#
# For UFO3 names, see
# https://github.com/unified-font-object/ufo-spec/blob/gh-pages/versions/
# ufo3/fontinfo.plist.md
# For OpenType NAME table IDs, see
# https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids
#
version = getVersion()
buildtag = getGitHash()
versionMajor, versionMinor = [int(num) for num in version.split(".")]
now = datetime.datetime.utcnow()
family = font.info.familyName # i.e. "Inter UI"
style = font.info.styleName # e.g. "Medium Italic"
isitalic = font.info.italicAngle != 0
# weight
font.info.openTypeOS2WeightClass = weight
# creation date & time (YYYY/MM/DD HH:MM:SS)
if updateCreated:
font.info.openTypeHeadCreated = now.strftime("%Y/%m/%d %H:%M:%S")
# version
font.info.version = version
font.info.versionMajor = versionMajor
font.info.versionMinor = versionMinor
font.info.woffMajorVersion = versionMajor
font.info.woffMinorVersion = versionMinor
font.info.year = now.year
font.info.openTypeNameVersion = "%s;%s" % (version, buildtag)
font.info.openTypeNameUniqueID = "%s %s:%d:%s" % (family, style, now.year, buildtag)
# Names
family_nosp = re.sub(r'\s', '', family)
style_nosp = re.sub(r'\s', '', style)
font.info.macintoshFONDName = "%s %s" % (family_nosp, style_nosp)
font.info.postscriptFontName = "%s-%s" % (family_nosp, style_nosp)
# name ID 16 "Typographic Family name"
font.info.openTypeNamePreferredFamilyName = family
# name ID 17 "Typographic Subfamily name"
font.info.openTypeNamePreferredSubfamilyName = style
# name ID 1 "Family name" (legacy, but required)
# Restriction:
# "shared among at most four fonts that differ only in weight or style"
# So we map as follows:
# - Regular => "Family", ("regular" | "italic" | "bold" | "bold italic")
# - Medium => "Family Medium", ("regular" | "italic")
# - Black => "Family Black", ("regular" | "italic")
# and so on.
subfamily = stripItalic(style) # "A Italic" => "A", "A" => "A"
if len(subfamily) == 0:
subfamily = "Regular"
subfamily_lc = subfamily.lower()
if subfamily_lc == "regular" or subfamily_lc == "bold":
font.info.styleMapFamilyName = family
# name ID 2 "Subfamily name" (legacy, but required)
# Value must be one of: "regular", "italic", "bold", "bold italic"
if subfamily_lc == "regular":
if isitalic:
font.info.styleMapStyleName = "italic"
else:
font.info.styleMapStyleName = "regular"
else: # bold
if isitalic:
font.info.styleMapStyleName = "bold italic"
else:
font.info.styleMapStyleName = "bold"
else:
font.info.styleMapFamilyName = family + ' ' + subfamily
# name ID 2 "Subfamily name" (legacy, but required)
if isitalic:
font.info.styleMapStyleName = "italic"
else:
font.info.styleMapStyleName = "regular"
class Main(object):
def __init__(self):
self.tmpdir = pjoin(BASEDIR,'build','tmp')
def main(self, argv):
# make ^C instantly exit program
signal.signal(signal.SIGINT, sighandler)
argparser = argparse.ArgumentParser(
description='',
usage='''
%(prog)s [options] <command> [<args>]
Commands:
compile Build font files
glyphsync Generate designspace and UFOs from Glyphs file
instancegen Generate instance UFOs for designspace
'''.strip().replace('\n ', '\n'))
argparser.add_argument('-v', '--verbose', action='store_true',
help='Print more details')
argparser.add_argument('command', metavar='<command>')
args = argparser.parse_args(argv[1:2])
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.ERROR)
cmd = 'cmd_' + args.command.replace('-', '_')
if not hasattr(self, cmd):
print('Unrecognized command %s. Try --help' % args.command,
file=sys.stderr)
exit(1)
getattr(self, cmd)(argv[2:])
def cmd_compile(self, argv):
argparser = argparse.ArgumentParser(
usage='%(prog)s compile [-h] [-o <file>] <ufo>',
description='Compile font files')
argparser.add_argument('ufo', metavar='<ufo>',
help='UFO source file')
argparser.add_argument('-o', '--output', metavar='<fontfile>',
help='Output font file (.otf, .ttf, .ufo or .gx)')
argparser.add_argument('--validate', action='store_true',
help='Enable ufoLib validation on reading/writing UFO files')
# argparser.add_argument('-f', '--formats', nargs='+', metavar='<format>',
# help='Output formats. Any of %(choices)s. Defaults to "otf".',
# choices=tuple(all_formats),
# default=('otf'))
args = argparser.parse_args(argv)
ext_to_format = {
'.ufo': 'ufo',
'.otf': 'otf',
'.ttf': 'ttf',
# 'ttf-interpolatable',
'.gx': 'variable',
}
formats = []
filename = args.output
if filename is None or filename == '':
ufoname = basename(args.ufo)
name, ext = os.path.splitext(ufoname)
filename = name + '.otf'
logging.info('setting --output %r' % filename)
# for filename in args.output:
ext = os.path.splitext(filename)[1]
ext_lc = ext.lower()
if ext_lc in ext_to_format:
formats.append(ext_to_format[ext_lc])
else:
print('Unsupported output format %s' % ext, file=sys.stderr)
exit(1)
mkdirs(self.tmpdir)
project = FontProject(
timing=None,
verbose='WARNING',
validate_ufo=args.validate
)
project.run_from_ufos(
[args.ufo],
output_dir=self.tmpdir,
output=formats,
subroutinize=True
)
# run through ots-sanitize
# for filename in args.output:
tmpfile = pjoin(self.tmpdir, basename(filename))
mkdirs(dirname(filename))
success = True
try:
otssan_res = subprocess.check_output(
['ots-sanitize', tmpfile, filename],
# ['cp', tmpfile, filename],
shell=False
).strip()
# Note: ots-sanitize does not exit with an error in many cases where
# it fails to sanitize the font.
success = otssan_res.find('Failed') == -1
except:
success = False
otssan_res = 'error'
if success:
os.unlink(tmpfile)
else:
print('ots-sanitize failed for %s: %s' % (
tmpfile, otssan_res), file=sys.stderr)
exit(1)
def cmd_glyphsync(self, argv):
argparser = argparse.ArgumentParser(
usage='%(prog)s glyphsync <glyphsfile> [options]',
description='Generates designspace and UFOs from Glyphs file')
argparser.add_argument('glyphsfile', metavar='<glyphsfile>',
help='Glyphs source file')
argparser.add_argument('-o', '--outdir', metavar='<dir>',
help='''Write output to <dir>. If omitted, designspace and UFOs are
written to the directory of the glyphs file.
'''.strip().replace('\n ', ''))
args = argparser.parse_args(argv)
outdir = args.outdir
if outdir is None:
outdir = dirname(args.glyphsfile)
# files
master_dir = outdir
glyphsfile = args.glyphsfile
designspace_file = pjoin(outdir, 'Inter-UI.designspace')
instance_dir = pjoin(BASEDIR, 'build', 'ufo')
# load glyphs project file
print("generating %s from %s" % (
relpath(designspace_file, os.getcwd()),
relpath(glyphsfile, os.getcwd())
))
font = glyphsLib.GSFont(glyphsfile)
# generate designspace from glyphs project
designspace = glyphsLib.to_designspace(
font,
propagate_anchors=False,
instance_dir=relpath(instance_dir, master_dir)
)
# strip lib data
designspace.lib.clear()
# fixup axes
for axis in designspace.axes:
if axis.tag == "wght":
axis.map = []
axis.minimum = 100
axis.maximum = 900
axis.default = 400
# patch and write UFO files
# TODO: Only write out-of-date UFOs
for source in designspace.sources:
# source : fontTools.designspaceLib.SourceDescriptor
# source.font : defcon.objects.font.Font
ufo_path = pjoin(master_dir, source.filename.replace('InterUI', 'Inter-UI'))
# no need to also set the relative 'filename' attribute as that
# will be auto-updated on writing the designspace document
# name "Inter UI Black" => "black"
source.name = source.styleName.lower().replace(' ', '')
# fixup font info
weight = int(source.location['Weight'])
setFontInfo(source.font, weight, updateCreated=False)
# cleanup lib
lib = dict()
for key, value in source.font.lib.iteritems():
if key.startswith('com.schriftgestaltung'):
continue
if key == 'public.postscriptNames':
continue
lib[key] = value
source.font.lib.clear()
source.font.lib.update(lib)
# write UFO file
source.path = ufo_path
print("write %s" % relpath(ufo_path, os.getcwd()))
source.font.save(ufo_path)
# patch instance names
for instance in designspace.instances:
# name "Inter UI Black Italic" => "blackitalic"
instance.name = instance.styleName.lower().replace(' ', '')
instance.filename = instance.filename.replace('InterUI', 'Inter-UI')
print("write %s" % relpath(designspace_file, os.getcwd()))
designspace.write(designspace_file)
def cmd_instancegen(self, argv):
argparser = argparse.ArgumentParser(
description='Generate UFO instances from designspace')
argparser.add_argument('designspacefile', metavar='<designspace>',
help='Designspace file')
argparser.add_argument('instances', metavar='<instance-name>', nargs='*',
help='Style instances to generate. Omit to generate all.')
args = argparser.parse_args(argv)
instances = set([s.lower() for s in args.instances])
all_instances = len(instances) == 0
# files
designspace_file = args.designspacefile
instance_dir = pjoin(BASEDIR, 'build', 'ufo')
# DesignSpaceDocumentReader generates UFOs
gen = DesignSpaceDocumentReader(
designspace_file,
ufoVersion=3,
roundGeometry=True,
verbose=True
)
designspace = designspaceLib.DesignSpaceDocument()
designspace.read(designspace_file)
# Generate UFOs for instances
instance_weight = dict()
instance_files = set()
for instance in designspace.instances:
if all_instances or instance.name in instances:
filebase = basename(instance.filename)
relname = relpath(
pjoin(dirname(designspace_file), instance.filename),
os.getcwd()
)
print('generating %s' % relname)
gen.readInstance(("name", instance.name))
instance_files.add(instance.filename)
instance_weight[filebase] = int(instance.location['Weight'])
if not all_instances:
instances.remove(instance.name)
if len(instances) > 0:
print('unknown style(s): %s' % ', '.join(list(instances)), file=sys.stderr)
sys.exit(1)
ufos = apply_instance_data(designspace_file, instance_files)
# patch ufos (list of defcon.Font instances)
italicAngleKey = 'com.schriftgestaltung.customParameter.' +\
'InstanceDescriptorAsGSInstance.italicAngle'
for font in ufos:
# move italicAngle from lib to info
italicAngle = font.lib.get(italicAngleKey)
if italicAngle != None:
italicAngle = float(italicAngle)
del font.lib[italicAngleKey]
font.info.italicAngle = italicAngle
# update font info
weight = instance_weight[basename(font.path)]
setFontInfo(font, weight)
font.save()
def checkfont(self, fontfile):
try:
res = subprocess.check_output(
['ots-idempotent', fontfile],
shell=False
).strip()
# Note: ots-idempotent does not exit with an error in many cases where
# it fails to sanitize the font.
if res.find('Failed') != -1:
logging.error('[checkfont] ots-idempotent failed for %r: %s' % (
fontfile, res))
return False
except:
logging.error('[checkfont] ots-idempotent failed for %r' % fontfile)
return False
return True
def cmd_checkfont(self, argv):
argparser = argparse.ArgumentParser(
usage='%(prog)s checkfont <file> ...',
description='Verify integrity of font files')
argparser.add_argument('files', metavar='<file>', nargs='+',
help='Font files')
args = argparser.parse_args(argv)
for fontfile in args.files:
if not self.checkfont(fontfile):
sys.exit(1)
# could use from multiprocessing import Pool
# p = Pool(8)
# p.map(self.checkfont, args.files)
# p.terminate()
if __name__ == '__main__':
Main().main(sys.argv)
|