Debian Codegraph @

misc/fontbuild

raw symbols SCIP
1 #!/usr/bin/env python
2 from __future__ import print_function, absolute_import
3 import sys
4 import os
5 from os.path import dirname, basename, abspath, relpath, join as pjoin
6 sys.path.append(abspath(pjoin(dirname(__file__), 'tools')))
7 from common import BASEDIR, execproc
8 from collections import OrderedDict
9
10 import argparse
11 import glyphsLib
12 import logging
13 import re
14 import signal
15 import subprocess
16 import defcon
17
18 from fontTools.designspaceLib import DesignSpaceDocument
19 from mutatorMath.ufo.document import DesignSpaceDocumentReader
20 from multiprocessing import Process, Queue
21 from glyphsLib.interpolation import apply_instance_data
22
23 from fontbuildlib import FontBuilder
24 from fontbuildlib.util import mkdirs, loadTTFont
25 from fontbuildlib.info import setFontInfo
26 from fontbuildlib.name import setFamilyName, renameStylesGoogleFonts
27
28 log = logging.getLogger(__name__)
29
30 # set to true to exclude anchors from .glyphs when generating UFOs
31 EXCLUDE_ANCHORS = False
32
33
34 def sighandler(signum, frame):
35 sys.stdout.write('\n')
36 sys.stdout.flush()
37 sys.exit(1)
38
39
40 def fatal(msg):
41 print(sys.argv[0] + ': ' + msg, file=sys.stderr)
42 sys.exit(1)
43
44
45 def collapseFontStyleName(font):
46 # collapse whitespace in style name. i.e. "Semi Bold Italic" -> "SemiBoldItalic"
47 font.info.styleName = re.sub(r'\s', '', font.info.styleName)
48 # update info to have style changes "trickle down" to other metadata
49 setFontInfo(font, font.info.openTypeOS2WeightClass)
50
51
52 class Main(object):
53
54 def __init__(self):
55 self.tmpdir = pjoin(BASEDIR,'build','tmp')
56 self.quiet = False
57 self.logLevelName = 'WARNING'
58
59
60 def log(self, msg):
61 if not self.quiet:
62 print(msg)
63
64
65 def main(self, argv):
66 # make ^C instantly exit program
67 signal.signal(signal.SIGINT, sighandler)
68
69 argparser = argparse.ArgumentParser(
70 description='',
71 usage='''
72 %(prog)s [options] <command> [<args>]
73
74 Commands:
75 compile Build font files
76 compile-var Build variable font files
77 glyphsync Generate designspace and UFOs from Glyphs file
78 instancegen Generate instance UFOs for designspace
79 checkfont Verify integrity of font files
80 rename Rename fonts
81 '''.strip().replace('\n ', '\n'))
82
83 argparser.add_argument('-v', '--verbose', action='store_true',
84 help='Print more details')
85
86 argparser.add_argument('--debug', action='store_true',
87 help='Print lots of details')
88
89 argparser.add_argument('-q', '--quiet', action='store_true',
90 help='Only print errors')
91
92 argparser.add_argument('--profile', metavar='<file>',
93 help='Run in profiler for debugging, writing pstats data to <file>')
94
95 argparser.add_argument('-C', metavar='<dir>', dest='chdir',
96 help='Run as if %(prog)s started in <dir> instead of the '+\
97 'current working directory.')
98
99 argparser.add_argument('command', metavar='<command>')
100
101 # search past base arguments
102 i = 1
103 while i < len(argv) and argv[i][0] == '-':
104 i = i + 1
105 i = i + 1
106
107 # parse CLI arguments
108 args = argparser.parse_args(argv[1:i])
109
110 # log config
111 if args.quiet:
112 self.quiet = True
113 if args.debug:
114 fatal("--quiet and --debug are mutually exclusive arguments")
115 if args.verbose:
116 fatal("--quiet and --verbose are mutually exclusive arguments")
117 elif args.debug:
118 logging.basicConfig(level=logging.DEBUG, format='%(funcName)s: %(message)s')
119 self.logLevelName = 'DEBUG'
120 elif args.verbose:
121 logging.basicConfig(level=logging.INFO, format='%(funcName)s: %(message)s')
122 self.logLevelName = 'INFO'
123 else:
124 logging.basicConfig(level=logging.WARNING, format='%(message)s')
125 self.logLevelName = 'WARNING'
126
127 if args.chdir:
128 os.chdir(args.chdir)
129
130 cmd = 'cmd_' + args.command.replace('-', '_')
131 if not hasattr(self, cmd):
132 fatal('Unrecognized command %s. Try --help' % args.command)
133 cmdfn = getattr(self, cmd)
134 if args.profile:
135 try:
136 import cProfile as profile
137 except:
138 import profile
139 import __main__
140 __main__.__dict__["cmdfn"] = cmdfn
141 __main__.__dict__["argv"] = argv[i:]
142 profile.run('cmdfn(argv)', args.profile)
143 print("")
144 print("profile saved to %r. You can now inspect it with for example:" %
145 args.profile)
146 print("misc/tools/fmtprofile.py -n 20 %r" % args.profile)
147 print("python3 -m pstats %r" % args.profile)
148 print("")
149 else:
150 cmdfn(argv[i:])
151
152
153
154 def cmd_compile_var(self, argv):
155 argparser = argparse.ArgumentParser(
156 usage='%(prog)s compile-var [-h] [-o <file>] <designspace>',
157 description='Compile variable font file')
158
159 argparser.add_argument('srcfile', metavar='<designspace>',
160 help='Source file (.designspace file)')
161
162 argparser.add_argument('-o', '--output', metavar='<fontfile>',
163 help='Output font file')
164
165 args = argparser.parse_args(argv)
166
167 # decide output filename (or check user-provided name)
168 outfilename = args.output
169 if outfilename is None or outfilename == '':
170 outfilename = pjoin(
171 dirname(args.srcfile),
172 os.path.splitext(basename(args.srcfile))[0] + '.otf'
173 )
174 log.debug('setting --output %r' % outfilename)
175
176 mkdirs(dirname(outfilename))
177
178 FontBuilder().buildVariable(args.srcfile, outfilename)
179
180 self.log("write %s" % outfilename)
181 # Note: we can't run ots-sanitize on the generated file as OTS
182 # currently doesn't support variable fonts.
183
184
185
186 def cmd_compile(self, argv):
187 argparser = argparse.ArgumentParser(
188 usage='%(prog)s compile [-h] [-o <file>] <ufo>',
189 description='Compile font files')
190
191 argparser.add_argument('srcfile', metavar='<ufo>',
192 help='Source file (.ufo file)')
193
194 argparser.add_argument('-o', '--output', metavar='<fontfile>',
195 help='Output font file (.otf or .ttf)')
196
197 argparser.add_argument('--validate', action='store_true',
198 help='Enable ufoLib validation on reading/writing UFO files')
199
200 args = argparser.parse_args(argv)
201
202 # write an OTF/CFF (or a TTF if false)
203 cff = True
204
205 # decide output filename
206 outfilename = args.output
207 if outfilename is None or outfilename == '':
208 outfilename = pjoin(
209 dirname(args.srcfile),
210 os.path.splitext(basename(args.srcfile))[0] + '.otf'
211 )
212 log.debug('setting --output %r' % outfilename)
213 else:
214 fext = os.path.splitext(outfilename)[1].lower()
215 if fext == ".ttf":
216 cff = False
217 elif fext != ".otf":
218 raise Exception('invalid file format %r (expected ".otf" or ".ttf")' % fext)
219
220 # build OTF or TTF file from UFO
221 FontBuilder().buildStatic(args.srcfile, outfilename, cff)
222
223 # code to pipe font through ots-sanitize:
224 # # temp file to write to
225 # tmpfilename = pjoin(self.tmpdir, basename(outfilename))
226 # mkdirs(self.tmpdir)
227 #
228 # # build OTF or TTF file from UFO
229 # FontBuilder().buildStatic(args.srcfile, tmpfilename, cff)
230 #
231 # # Run ots-sanitize on produced OTF/TTF file and write sanitized version to outfilename
232 # self._ots_sanitize(tmpfilename, outfilename)
233
234
235 #def _ots_sanitize(self, tmpfilename, outfilename):
236 # # run through ots-sanitize
237 # # for filename in args.output:
238 # tmpfile = pjoin(self.tmpdir, tmpfilename)
239 # mkdirs(dirname(outfilename))
240 # success = True
241 # try:
242 # self.log("write %s" % outfilename)
243 # otssan_res = subprocess.check_output(
244 # ['ots-sanitize', tmpfile, outfilename],
245 # # ['cp', tmpfile, outfilename],
246 # shell=False
247 # ).strip()
248 # # Note: ots-sanitize does not exit with an error in many cases where
249 # # it fails to sanitize the font.
250 # success = str(otssan_res).find('Failed') == -1
251 # except:
252 # success = False
253 # if len(otssan_res) == 0:
254 # otssan_res = 'error'
255 #
256 # if success:
257 # os.unlink(tmpfile)
258 # else:
259 # fatal('ots-sanitize failed for %s: %s' % (tmpfile, otssan_res))
260
261
262
263 def _glyphsyncWriteUFO(self, font, weight, ufo_path):
264 # fixup font info
265 setFontInfo(font, weight)
266
267 # cleanup lib
268 lib = dict()
269 for key, value in font.lib.items():
270 if key.startswith('com.schriftgestaltung'):
271 continue
272 if key == 'public.postscriptNames':
273 continue
274 lib[key] = value
275 font.lib.clear()
276 font.lib.update(lib)
277
278 # remove all but the primary (default) layer
279 layers = font.layers
280 defaultLayer = layers.defaultLayer
281 delLayerNames = set()
282 for layer in layers:
283 if layer != defaultLayer:
284 delLayerNames.add(layer.name)
285 for layerName in delLayerNames:
286 del(layers[layerName])
287
288 # process glyphs
289 glyphOrder = OrderedDict([(k,None) for k in font.lib['public.glyphOrder']])
290 rmglyphs = []
291 for g in font:
292 if not g.lib.get('com.schriftgestaltung.Glyphs.Export', True):
293 if g.name in glyphOrder:
294 del(glyphOrder[g.name])
295 rmglyphs.append(g.name)
296 g.unicodes = []
297 continue
298 if EXCLUDE_ANCHORS:
299 g.clearAnchors()
300 if 'com.schriftgestaltung.Glyphs.lastChange' in g.lib:
301 del(g.lib['com.schriftgestaltung.Glyphs.lastChange'])
302
303 for gname in rmglyphs:
304 del(font[gname])
305
306 # update possibly modified glyphorder
307 font.lib['public.glyphOrder'] = list(glyphOrder)
308
309 # write UFO file
310 self.log("write %s" % relpath(ufo_path, os.getcwd()))
311 font.save(ufo_path, overwrite=True, validate=False)
312
313
314 def _genSubsetDesignSpace(self, designspace, tag, filename):
315 ds = designspace
316 italic = False
317 if tag == 'italic':
318 italic = True
319 elif tag != 'roman':
320 raise Exception('unexpected tag ' + tag)
321
322 for a in ds.axes:
323 if a.tag == "slnt":
324 ds.axes.remove(a)
325 break
326
327 rmlist = []
328 hasDefault = not italic
329 for source in designspace.sources:
330 isitalic = source.name.find('italic') != -1
331 if italic != isitalic:
332 rmlist.append(source)
333 elif italic and not hasDefault:
334 source.copyLib = True
335 source.copyInfo = True
336 source.copyGroups = True
337 source.copyFeatures = True
338 hasDefault = True
339 for source in rmlist:
340 designspace.sources.remove(source)
341
342 rmlist = []
343 for instance in designspace.instances:
344 isitalic = instance.name.find('italic') != -1
345 if italic != isitalic:
346 rmlist.append(instance)
347 for instance in rmlist:
348 designspace.instances.remove(instance)
349
350 self.log("write %s" % relpath(filename, os.getcwd()))
351 ds.write(filename)
352
353
354
355 def cmd_glyphsync(self, argv):
356 argparser = argparse.ArgumentParser(
357 usage='%(prog)s glyphsync <glyphsfile> [options]',
358 description='Generates designspace and UFOs from Glyphs file')
359
360 argparser.add_argument('glyphsfile', metavar='<glyphsfile>',
361 help='Glyphs source file')
362
363 argparser.add_argument('-o', '--outdir', metavar='<dir>',
364 help='''Write output to <dir>. If omitted, designspace and UFOs are
365 written to the directory of the glyphs file.
366 '''.strip().replace('\n ', ''))
367
368 args = argparser.parse_args(argv)
369
370 outdir = args.outdir
371 if outdir is None:
372 outdir = dirname(args.glyphsfile)
373
374 # TODO: Move into fontbuildlib
375
376 # files
377 master_dir = outdir
378 glyphsfile = args.glyphsfile
379 name = os.path.splitext(basename(glyphsfile))[0] # e.g. "Inter"
380 designspace_file = pjoin(outdir, name + '.designspace')
381 instance_dir = pjoin(BASEDIR, 'build', 'ufo')
382
383 # load glyphs project file
384 self.log("generating %s from %s" % (
385 relpath(designspace_file, os.getcwd()),
386 relpath(glyphsfile, os.getcwd())
387 ))
388 font = glyphsLib.GSFont(glyphsfile)
389
390 # remove archive layers and backgrounds
391 masterLayerIDs = set()
392 for master in font.masters:
393 masterLayerIDs.add(master.id)
394 for glyph in font.glyphs:
395 for layer in list(glyph.layers): # list to accumulate iterator since we del()
396 # remove background images from all layers
397 layer.backgroundImage = None
398 lname = layer.name
399 lid = layer.layerId
400 if lname[0] != '_' and (lid in masterLayerIDs or lname.find('{') != -1):
401 # Keep only layers which are masters or bracket layers.
402 # Next, clear background to speed up UFO generation.
403 layer.background.paths = []
404 layer.background.components = []
405 layer.background.anchors = []
406 layer.background.hints = []
407 layer.background.guides = []
408 else:
409 del(glyph.layers[lid])
410
411 # generate designspace from glyphs project
412 designspace = glyphsLib.to_designspace(
413 font,
414 propagate_anchors=(not EXCLUDE_ANCHORS),
415 instance_dir=relpath(instance_dir, master_dir),
416 store_editor_state=False, # do not store glyphs editor UI state in UFOs
417 )
418
419 # strip lib data
420 designspace.lib.clear()
421
422 # patch and write UFO files
423 # TODO: Only write out-of-date UFOs
424 procs = []
425 for source in designspace.sources:
426 # source : fontTools.designspaceLib.SourceDescriptor
427 # source.font : ufoLib2.objects.font.Font
428 ufo_path = pjoin(master_dir, source.filename)
429 # no need to also set the relative 'filename' attribute as that
430 # will be auto-updated on writing the designspace document
431 if source.styleName == "Italic Italic":
432 # Workaround for Glyphs limitation
433 # (Base italic master can't be called just Italic, so it's called
434 # "Italic Italic" which is converted here to just "Italic")
435 ufo_path = pjoin(master_dir, name + '-Italic.ufo')
436 source.styleName = "Italic"
437 source.name = "italic"
438 source.font.info.styleName = source.styleName
439 elif source.styleName == "Black Italic Italic":
440 ufo_path = pjoin(master_dir, name + '-BlackItalic.ufo')
441 source.styleName = "Black Italic"
442 source.name = "blackitalic"
443 source.font.info.styleName = source.styleName
444 elif source.styleName == "Thin Italic Italic":
445 ufo_path = pjoin(master_dir, name + '-ThinItalic.ufo')
446 source.styleName = "Thin Italic"
447 source.name = "thinitalic"
448 source.font.info.styleName = source.styleName
449 elif source.styleName:
450 # name "Black" => "black"
451 source.name = source.styleName.lower().replace(' ', '')
452
453 source.path = ufo_path
454 weight = int(source.location['Weight'])
455
456 # serial
457 # self._glyphsyncWriteUFO(source.font, weight, ufo_path)
458
459 # parallel
460 p = Process(
461 target=self._glyphsyncWriteUFO,
462 args=(source.font, weight, ufo_path)
463 )
464 p.start()
465 procs.append(p)
466
467 # patch instance names
468 for instance in designspace.instances:
469 # name "Black Italic" => "blackitalic"
470 instance.name = instance.styleName.lower().replace(' ', '')
471
472 self.log("write %s" % relpath(designspace_file, os.getcwd()))
473 designspace.write(designspace_file)
474
475 # roman designspace
476 roman_designspace_file = pjoin(outdir, name + '-roman.designspace')
477 p = Process(
478 target=self._genSubsetDesignSpace,
479 args=(designspace, 'roman', roman_designspace_file)
480 )
481 p.start()
482 procs.append(p)
483
484 # italic designspace
485 italic_designspace_file = pjoin(outdir, name + '-italic.designspace')
486 p = Process(
487 target=self._genSubsetDesignSpace,
488 args=(designspace, 'italic', italic_designspace_file)
489 )
490 p.start()
491 procs.append(p)
492
493 for p in procs:
494 p.join()
495
496
497
498 def cmd_instancegen(self, argv):
499 argparser = argparse.ArgumentParser(
500 description='Generate UFO instances from designspace')
501
502 argparser.add_argument('designspacefile', metavar='<designspace>',
503 help='Designspace file')
504
505 argparser.add_argument('instances', metavar='<instance-name>', nargs='*',
506 help='Style instances to generate. Omit to generate all.')
507
508 args = argparser.parse_args(argv)
509
510 instances = set([s.lower() for s in args.instances])
511 all_instances = len(instances) == 0
512
513 # files
514 designspace_file = args.designspacefile
515 instance_dir = pjoin(BASEDIR, 'build', 'ufo')
516
517 # DesignSpaceDocumentReader generates UFOs
518 gen = DesignSpaceDocumentReader(
519 designspace_file,
520 ufoVersion=3,
521 roundGeometry=True,
522 verbose=True
523 )
524
525 designspace = DesignSpaceDocument.fromfile(designspace_file)
526
527 master0_ufo = defcon.Font(designspace.sources[0].path)
528
529 # Generate UFOs for instances
530 instance_weight = dict()
531 instance_files = set()
532 for instance in designspace.instances:
533 if all_instances or instance.name in instances:
534 filebase = basename(instance.filename)
535 relname = relpath(
536 pjoin(dirname(designspace_file), instance.filename),
537 os.getcwd()
538 )
539 self.log('generating %s' % relname)
540 gen.readInstance(("name", instance.name))
541 instance_files.add(instance.filename)
542 instance_weight[filebase] = int(instance.location['Weight'])
543 if not all_instances:
544 instances.remove(instance.name)
545
546 if len(instances) > 0:
547 fatal('unknown style(s): %s' % ', '.join(list(instances)))
548
549 ufos = apply_instance_data(designspace, instance_files)
550
551 # patch ufos (list of defcon.Font instances)
552 italicAngleKey = 'com.schriftgestaltung.customParameter.' +\
553 'InstanceDescriptorAsGSInstance.italicAngle'
554 for ufo in ufos:
555 # set metrics
556 ufo.info.ascender = master0_ufo.info.ascender
557 ufo.info.capHeight = master0_ufo.info.capHeight
558 ufo.info.descender = master0_ufo.info.descender
559 ufo.info.xHeight = master0_ufo.info.xHeight
560
561 # move italicAngle from lib to info
562 italicAngle = ufo.lib.get(italicAngleKey)
563 if italicAngle != None:
564 italicAngle = float(italicAngle)
565 del(ufo.lib[italicAngleKey])
566 ufo.info.italicAngle = italicAngle
567
568 # clear anchors
569 if EXCLUDE_ANCHORS:
570 for g in ufo:
571 g.clearAnchors()
572
573 # update font info
574 weight = instance_weight[basename(ufo.path)]
575 setFontInfo(ufo, weight)
576
577 ufo.save()
578
579
580 def checkfont(self, fontfile, q):
581 res, ok = execproc('ots-idempotent', fontfile)
582 # Note: ots-idempotent does not exit with an error in many cases where
583 # it fails to sanitize the font, so we look at its output to determine
584 # success or failure.
585 if not ok or res.find('Failed') != -1:
586 log.error('%s: checkfont ots-idempotent: %s' % (fontfile, res))
587 q.put(False)
588 return
589
590 res, ok = execproc('ots-validator-checker', fontfile)
591 if not ok or res.find("didn't crash") == -1:
592 log.error('%s: checkfont ots-validator-checker: %s' % (fontfile, res))
593 q.put(False)
594 return
595
596 # ok
597 q.put(True)
598
599
600 def cmd_checkfont(self, argv):
601 argparser = argparse.ArgumentParser(
602 usage='%(prog)s checkfont <file> ...',
603 description='Verify integrity of font files')
604
605 argparser.add_argument('files', metavar='<file>', nargs='+',
606 help='Font files')
607
608 args = argparser.parse_args(argv)
609 q = Queue()
610
611 if len(args.files) < 2:
612 self.checkfont(args.files[0], q)
613 else:
614 procs = []
615 for fontfile in args.files:
616 p = Process(target=self.checkfont, args=(fontfile, q))
617 p.start()
618 procs.append(p)
619 for p in procs:
620 p.join()
621
622 for fontfile in args.files:
623 if not q.get():
624 sys.exit(1)
625
626
627 def cmd_rename(self, argv):
628 argparser = argparse.ArgumentParser(
629 usage='%(prog)s rename <options> <file>',
630 description='Rename family and/or styles of font'
631 )
632 a = lambda *args, **kwargs: argparser.add_argument(*args, **kwargs)
633
634 a('-o', '--output', metavar='<file>',
635 help='Output font file. Defaults to input file (overwrite.)')
636
637 a('--family', metavar='<name>',
638 help='Rename family to <name>')
639
640 a('--google-style', action='store_true',
641 help='Rename style names to Google Fonts standards.')
642
643 a('input', metavar='<file>',
644 help='Input font file')
645
646 args = argparser.parse_args(argv)
647
648 infile = args.input
649 outfile = args.output or infile
650
651 font = loadTTFont(infile)
652 editCount = 0
653 try:
654 if args.family:
655 editCount += 1
656 setFamilyName(font, args.family)
657
658 if args.google_style:
659 editCount += 1
660 renameStylesGoogleFonts(font)
661
662 if editCount == 0:
663 print("no rename options provided", file=sys.stderr)
664 argparser.print_help(sys.stderr)
665 sys.exit(1)
666 return
667
668 font.save(outfile)
669 finally:
670 font.close()
671
672
673
674 if __name__ == '__main__':
675 Main().main(sys.argv)