Debian Codegraph @

misc/tools/enrich-glypnames.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # encoding: utf8
3 from __future__ import print_function
4 import os
5 import sys
6 import argparse
7 import json
8 import plistlib
9 import re
10 from collections import OrderedDict
11 from textwrap import TextWrapper
12 from StringIO import StringIO
13 from ConfigParser import RawConfigParser
14 from fontTools import ttLib
15 from robofab.objects.objectsRF import RFont, OpenFont
16
17 # from feaTools import parser as feaParser
18 # from feaTools.parser import parseFeatures
19 # from feaTools import FDKSyntaxFeatureWriter
20 # from fontbuild.features import updateFeature, compileFeatureRE
21
22 # Regex matching "default" glyph names, like "uni2043" and "u01C5"
23 uniNameRe = re.compile(r'^u(?:ni)[0-9A-F]{4,8}$')
24
25
26 def defaultGlyphName(uc):
27 return 'uni%04X' % uc
28
29 def defaultGlyphName2(uc):
30 return 'u%04X' % uc
31
32
33 def isDefaultGlyphName(name):
34 return True if uniNameRe.match(name) else False
35
36
37 def isDefaultGlyphNameForUnicode(name, uc):
38 return name == defaultGlyphName(uc) or name == defaultGlyphName2(uc)
39
40
41 def getFirstNonDefaultGlyphName(uc, names):
42 for name in names:
43 if not isDefaultGlyphNameForUnicode(name, uc):
44 return name
45 return None
46
47
48 def getTTGlyphList(font): # -> { 'Omega': [2126, ...], ... }
49 if isinstance(font, str):
50 font = ttLib.TTFont(font)
51
52 if not 'cmap' in font:
53 raise Exception('missing cmap table')
54
55 gl = {}
56 bestCodeSubTable = None
57 bestCodeSubTableFormat = 0
58
59 for st in font['cmap'].tables:
60 if st.platformID == 0: # 0=unicode, 1=mac, 2=(reserved), 3=microsoft
61 if st.format > bestCodeSubTableFormat:
62 bestCodeSubTable = st
63 bestCodeSubTableFormat = st.format
64
65 if bestCodeSubTable is not None:
66 for cp, glyphname in bestCodeSubTable.cmap.items():
67 if glyphname in gl:
68 gl[glyphname].append(cp)
69 else:
70 gl[glyphname] = [cp]
71
72 return gl, font
73
74
75 def getUFOGlyphList(font): # -> { 'Omega': [2126, ...], ... }
76 # Note: font.getCharacterMapping() returns {2126:['Omega', ...], ...}
77 gl = {}
78 for g in font:
79 ucv = g.unicodes
80 if len(ucv) > 0:
81 gl[g.name] = ucv
82 return gl
83
84
85 def appendNames(uc2names, extraUc2names, uc, name, isDestination):
86 if uc in uc2names:
87 names = uc2names[uc]
88 if name not in names:
89 names.append(name)
90 elif isDestination:
91 uc2names[uc] = [name]
92 else:
93 if uc in extraUc2names:
94 names = extraUc2names[uc]
95 if name not in names:
96 names.append(name)
97 else:
98 extraUc2names[uc] = [name]
99
100
101 def buildGlyphNames(dstFonts, srcFonts, glyphOrder, fallbackGlyphNames):
102 # fallbackGlyphNames: { 2126: 'Omega', ...}
103 uc2names = {} # { 2126: ['Omega', 'Omegagreek', ...], ...}
104 extraUc2names = {} # { 2126: ['Omega', 'Omegagreek', ...], ...}
105 # -- codepoints in Nth fonts, not found in first font
106 name2ucsv = [] # [ { 'Omega': [2126, ...] }, ... ] -- same order as fonts
107
108 fontIndex = 0
109 for font in dstFonts + srcFonts:
110 gl = None
111 if isinstance(font, RFont):
112 print('Inspecting', font.info.familyName, font.info.styleName)
113 gl = getUFOGlyphList(font)
114 else:
115 print('Inspecting', font)
116 gl, font = getTTGlyphList(font)
117
118 name2ucsv.append(gl)
119
120 isDestination = fontIndex < len(dstFonts)
121
122 for name, unicodes in gl.iteritems():
123 # if len(uc2names) > 100: break
124 for uc in unicodes:
125 appendNames(uc2names, extraUc2names, uc, name, isDestination)
126 if isDestination:
127 fallbackName = fallbackGlyphNames.get(uc)
128 if fallbackName is not None:
129 appendNames(uc2names, extraUc2names, uc, fallbackName, isDestination)
130
131 fontIndex += 1
132
133 # for name in glyphOrder:
134 # if len(name) > 7 and name.startswith('uni') and name.find('.') == -1 and name.find('_') == -1:
135 # try:
136 # print('name: %r, %r' % (name, name[3:]))
137 # uc = int(name[3:], 16)
138 # appendNames(uc2names, extraUc2names, uc, name, isDestination=True)
139 # except:
140 # print()
141 # pass
142
143 return uc2names, extraUc2names, name2ucsv
144
145
146 def renameStrings(listofstrs, newNames):
147 v = []
148 for s in listofstrs:
149 s2 = newNames.get(s)
150 if s2 is not None:
151 s = s2
152 v.append(s)
153 return v
154
155
156 def renameUFOLib(ufoPath, newNames, dryRun=False, print=print):
157 filename = os.path.join(ufoPath, 'lib.plist')
158 plist = plistlib.readPlist(filename)
159
160 glyphOrder = plist.get('public.glyphOrder')
161 if glyphOrder is not None:
162 plist['public.glyphOrder'] = renameStrings(glyphOrder, newNames)
163
164 roboSort = plist.get('com.typemytype.robofont.sort')
165 if roboSort is not None:
166 for entry in roboSort:
167 if isinstance(entry, dict) and entry.get('type') == 'glyphList':
168 asc = entry.get('ascending')
169 desc = entry.get('descending')
170 if asc is not None:
171 entry['ascending'] = renameStrings(asc, newNames)
172 if desc is not None:
173 entry['descending'] = renameStrings(desc, newNames)
174
175 print('Writing', filename)
176 if not dryRun:
177 plistlib.writePlist(plist, filename)
178
179
180 def renameUFOGroups(ufoPath, newNames, dryRun=False, print=print):
181 filename = os.path.join(ufoPath, 'groups.plist')
182
183 plist = None
184 try:
185 plist = plistlib.readPlist(filename)
186 except:
187 return
188
189 didChange = False
190
191 for groupName, glyphNames in plist.items():
192 for i in range(len(glyphNames)):
193 name = glyphNames[i]
194 if name in newNames:
195 didChange = True
196 glyphNames[i] = newNames[name]
197
198 if didChange:
199 print('Writing', filename)
200 if not dryRun:
201 plistlib.writePlist(plist, filename)
202
203
204 def renameUFOKerning(ufoPath, newNames, dryRun=False, print=print):
205 filename = os.path.join(ufoPath, 'kerning.plist')
206
207 plist = None
208 try:
209 plist = plistlib.readPlist(filename)
210 except:
211 return
212
213 didChange = False
214
215 newPlist = {}
216 for leftName, right in plist.items():
217 if leftName in newNames:
218 didChange = True
219 leftName = newNames[leftName]
220 newRight = {}
221 for rightName, kernValue in plist.items():
222 if rightName in newNames:
223 didChange = True
224 rightName = newNames[rightName]
225 newRight[rightName] = kernValue
226 newPlist[leftName] = right
227
228 if didChange:
229 print('Writing', filename)
230 if not dryRun:
231 plistlib.writePlist(newPlist, filename)
232
233
234 def subFeaName(m, newNames, state):
235 try:
236 int(m[3], 16)
237 except:
238 return m[0]
239
240 name = m[2]
241
242 if name in newNames:
243 # print('sub %r => %r' % (m[0], m[1] + newNames[name] + m[4]))
244 if name == 'uni0402':
245 print('sub %r => %r' % (m[0], m[1] + newNames[name] + m[4]))
246 state['didChange'] = True
247 return m[1] + newNames[name] + m[4]
248
249 return m[0]
250
251
252 FEA_TOK = 'tok'
253 FEA_SEP = 'sep'
254 FEA_END = 'end'
255
256 def feaTokenizer(feaText):
257 separators = set('; \t\r\n,[]\'"')
258 tokStartIndex = -1
259 sepStartIndex = -1
260
261 for i in xrange(len(feaText)):
262 ch = feaText[i]
263 if ch in separators:
264 if tokStartIndex != -1:
265 yield (FEA_TOK, feaText[tokStartIndex:i])
266 tokStartIndex = -1
267 if sepStartIndex == -1:
268 sepStartIndex = i
269 else:
270 if sepStartIndex != -1:
271 yield (FEA_SEP, feaText[sepStartIndex:i])
272 sepStartIndex = -1
273 if tokStartIndex == -1:
274 tokStartIndex = i
275
276 if sepStartIndex != -1 and tokStartIndex != -1:
277 yield (FEA_END, feaText[min(sepStartIndex, tokStartIndex):])
278 elif sepStartIndex != -1:
279 yield (FEA_END, feaText[sepStartIndex:])
280 elif tokStartIndex != -1:
281 yield (FEA_END, feaText[tokStartIndex:])
282 else:
283 yield (FEA_END, '')
284
285
286 def renameUFOFeatures(font, ufoPath, newNames, dryRun=False, print=print):
287 filename = os.path.join(ufoPath, 'features.fea')
288
289 feaText = ''
290 try:
291 with open(filename, 'r') as f:
292 feaText = f.read()
293 except:
294 return
295
296 didChange = False
297 feaText2 = ''
298
299 for t, v in feaTokenizer(feaText):
300 if t is FEA_TOK and len(v) > 6 and v.startswith('uni'):
301 if v in newNames:
302 # print('sub', v, newNames[v])
303 didChange = True
304 v = newNames[v]
305 feaText2 += v
306
307 feaText = feaText2
308
309 if didChange:
310 print('Writing', filename)
311 if not dryRun:
312 with open(filename, 'w') as f:
313 f.write(feaText)
314 print(
315 'Important: you need to manually verify that', filename, 'looks okay.',
316 'We did an optimistic update which is not perfect.'
317 )
318
319 # classes = feaParser.classDefinitionRE.findall(feaText)
320 # for precedingMark, className, classContent in classes:
321 # content = feaParser.classContentRE.findall(classContent)
322 # print('class', className, content)
323
324 # didChange = False
325 # content2 = []
326 # for name in content:
327 # if name in newNames:
328 # didChange = True
329 # content2.append(newNames[name])
330 # if didChange:
331 # print('content2', content2)
332 # feaText = feaParser.classDefinitionRE.sub('', feaText)
333
334 # featureTags = feaParser.feature_findAll_RE.findall(feaText)
335 # for precedingMark, featureTag in featureTags:
336 # print('feat', featureTag)
337
338
339 def renameUFODetails(font, ufoPath, newNames, dryRun=False, print=print):
340 renameUFOLib(ufoPath, newNames, dryRun, print)
341 renameUFOGroups(ufoPath, newNames, dryRun, print)
342 renameUFOKerning(ufoPath, newNames, dryRun, print)
343 renameUFOFeatures(font, ufoPath, newNames, dryRun, print)
344
345
346 def readLines(filename):
347 with open(filename, 'r') as f:
348 return f.read().strip().splitlines()
349
350
351 def readGlyphOrderFile(filename):
352 names = []
353 for line in readLines(filename):
354 line = line.lstrip()
355 if len(line) > 0 and line[0] != '#':
356 names.append(line)
357 return names
358
359
360 def renameGlyphOrderFile(filename, newNames, dryRun=False, print=print):
361 lines = []
362 didRename = False
363 for line in readLines(filename):
364 line = line.lstrip()
365 if len(line) > 0 and line[0] != '#':
366 newName = newNames.get(line)
367 if newName is not None:
368 didRename = True
369 line = newName
370 lines.append(line)
371 if didRename:
372 print('Writing', filename)
373 if not dryRun:
374 with open(filename, 'w') as f:
375 f.write('\n'.join(lines))
376
377
378 def parseGlyphComposition(composite):
379 c = composite.split("=")
380 d = c[1].split("/")
381 glyphName = d[0]
382 if len(d) == 1:
383 offset = [0, 0]
384 else:
385 offset = [int(i) for i in d[1].split(",")]
386 accentString = c[0]
387 accents = accentString.split("+")
388 baseName = accents.pop(0)
389 accentNames = [i.split(":") for i in accents]
390 return (glyphName, baseName, accentNames, offset)
391
392
393 def fmtGlyphComposition(glyphName, baseName, accentNames, offset):
394 # glyphName = 'uni03D3'
395 # baseName = 'uni03D2'
396 # accentNames = [['tonos', 'top'], ['acute', 'top']]
397 # offset = [100, 0]
398 # => "uni03D2+tonos:top+acute:top=uni03D3/100,0"
399 s = baseName
400 for accentNameTuple in accentNames:
401 s += '+' + accentNameTuple[0]
402 if len(accentNameTuple) > 1:
403 s += ':' + accentNameTuple[1]
404 s += '=' + glyphName
405 if offset[0] != 0 or offset[1] != 0:
406 s += '/%d,%d' % tuple(offset)
407 return s
408
409
410 def renameDiacriticsFile(filename, newNames, dryRun=False, print=print):
411 lines = []
412 didRename = False
413 for line in readLines(filename):
414 line = line.strip()
415 if len(line) > 0 and line[0] != '#':
416 glyphName, baseName, accentNames, offset = parseGlyphComposition(line)
417
418 # rename
419 glyphName = newNames.get(glyphName, glyphName)
420 baseName = newNames.get(baseName, baseName)
421 for accentTuple in accentNames:
422 accentTuple[0] = newNames.get(accentTuple[0], accentTuple[0])
423
424 line2 = fmtGlyphComposition(glyphName, baseName, accentNames, offset)
425
426 if line != line2:
427 line = line2
428 didRename = True
429 # print(line, '=>', line2)
430
431 lines.append(line)
432
433 if didRename:
434 print('Writing', filename)
435 if not dryRun:
436 with open(filename, 'w') as f:
437 f.write('\n'.join(lines))
438
439
440 def configFindResFile(config, basedir, name):
441 fn = os.path.join(basedir, config.get("res", name))
442 if not os.path.isfile(fn):
443 basedir = os.path.dirname(basedir)
444 fn = os.path.join(basedir, config.get("res", name))
445 if not os.path.isfile(fn):
446 fn = None
447 return fn
448
449
450 def renameConfigFile(config, filename, newNames, dryRun=False, print=print):
451 wrapper = TextWrapper()
452 wrapper.width = 80
453 wrapper.break_long_words = False
454 wrapper.break_on_hyphens = False
455
456 wrap = lambda names: '\n'.join(wrapper.wrap(' '.join(names)))
457
458 didRename = False
459 for propertyName, values in config.items('glyphs'):
460 glyphNames = values.split()
461 # print(propertyName, glyphNames)
462 propChanged = False
463 for name in glyphNames:
464 if name in newNames:
465 sectionChanged = True
466 if sectionChanged:
467 config.set('glyphs', propertyName, wrap(glyphNames)+'\n')
468 didRename = True
469
470 # config.set(section, option, value)
471 if didRename:
472 s = StringIO()
473 config.write(s)
474 s = s.getvalue()
475 s = re.sub(r'\n(\w+)\s+=\s*', '\n\\1: ', s, flags=re.M)
476 s = re.sub(r'((?:^|\n)\[[^\]]*\])', '\\1\n', s, flags=re.M)
477 s = re.sub(r'\n\t\n', '\n\n', s, flags=re.M)
478 s = s.strip() + '\n'
479 print('Writing', filename)
480 if not dryRun:
481 with open(filename, 'w') as f:
482 f.write(s)
483
484
485 def parseAGL(filename): # -> { 2126: 'Omega', ... }
486 m = {}
487 for line in readLines(filename):
488 # Omega;2126
489 # dalethatafpatah;05D3 05B2 # higher-level combinations; ignored
490 line = line.strip()
491 if len(line) > 0 and line[0] != '#':
492 name, uc = tuple([c.strip() for c in line.split(';')])
493 if uc.find(' ') == -1:
494 # it's a 1:1 mapping
495 m[int(uc, 16)] = name
496 return m
497
498
499 def main():
500 argparser = argparse.ArgumentParser(description='Enrich UFO glyphnames')
501
502 argparser.add_argument(
503 '-dry', dest='dryRun', action='store_const', const=True, default=False,
504 help='Do not modify anything, but instead just print what would happen.')
505
506 argparser.add_argument(
507 '-list-missing', dest='listMissing', action='store_const', const=True, default=False,
508 help='List glyphs with unicodes found in source files but missing in any of the target UFOs.')
509
510 argparser.add_argument(
511 '-list-unnamed', dest='listUnnamed', action='store_const', const=True, default=False,
512 help="List glyphs with unicodes in target UFOs that don't have symbolic names.")
513
514 argparser.add_argument(
515 '-backfill-agl', dest='backfillWithAgl', action='store_const', const=True, default=False,
516 help="Use glyphnames from Adobe Glyph List for any glyphs that no names in any of"+
517 " the input font files")
518
519 argparser.add_argument(
520 '-src', dest='srcFonts', metavar='<fontfile>', type=str, nargs='*',
521 help='TrueType, OpenType or UFO fonts to gather glyph info from. '+
522 'Names found in earlier-listed fonts are prioritized over later listings.')
523
524 argparser.add_argument(
525 'dstFonts', metavar='<ufofile>', type=str, nargs='+', help='UFO fonts to update')
526
527 args = argparser.parse_args()
528
529 # Load UFO fonts
530 dstFonts = []
531 dstFontPaths = {} # keyed by RFont object
532 srcDir = None
533 for fn in args.dstFonts:
534 fn = fn.rstrip('/')
535 font = OpenFont(fn)
536 dstFonts.append(font)
537 dstFontPaths[font] = fn
538 srcDir2 = os.path.dirname(fn)
539 if srcDir is None:
540 srcDir = srcDir2
541 elif srcDir != srcDir2:
542 raise Exception('All <ufofile>s must be rooted in same directory')
543
544 # load fontbuild configuration
545 config = RawConfigParser(dict_type=OrderedDict)
546 configFilename = os.path.join(srcDir, 'fontbuild.cfg')
547 config.read(configFilename)
548 glyphOrderFile = configFindResFile(config, srcDir, 'glyphorder')
549 diacriticsFile = configFindResFile(config, srcDir, 'diacriticfile')
550 glyphOrder = readGlyphOrderFile(glyphOrderFile)
551
552 fallbackGlyphNames = {} # { 2126: 'Omega', ... }
553 if args.backfillWithAgl:
554 fallbackGlyphNames = parseAGL(configFindResFile(config, srcDir, 'agl_glyphlistfile'))
555
556 # find glyph names
557 uc2names, extraUc2names, name2ucsv = buildGlyphNames(
558 dstFonts,
559 args.srcFonts,
560 glyphOrder,
561 fallbackGlyphNames
562 )
563 # Note: name2ucsv has same order as parameters to buildGlyphNames
564
565 if args.listMissing:
566 print('# Missing glyphs: (found in -src but not in any <ufofile>)')
567 for uc, names in extraUc2names.iteritems():
568 print('U+%04X\t%s' % (uc, ', '.join(names)))
569 return
570
571 elif args.listUnnamed:
572 print('# Unnamed glyphs:')
573 unnamed = set()
574 for name in glyphOrder:
575 if len(name) > 7 and name.startswith('uni'):
576 unnamed.add(name)
577 for gl in name2ucsv[:len(dstFonts)]:
578 for name, ucs in gl.iteritems():
579 for uc in ucs:
580 if isDefaultGlyphNameForUnicode(name, uc):
581 unnamed.add(name)
582 break
583 for name in unnamed:
584 print(name)
585 return
586
587 printDry = lambda *args: print(*args)
588 if args.dryRun:
589 printDry = lambda *args: print('[dry-run]', *args)
590
591 newNames = {}
592 renameGlyphsQueue = {} # keyed by RFont object
593
594 for font in dstFonts:
595 renameGlyphsQueue[font] = {}
596
597 for uc, names in uc2names.iteritems():
598 if len(names) < 2:
599 continue
600 dstGlyphName = names[0]
601 if isDefaultGlyphNameForUnicode(dstGlyphName, uc):
602 newGlyphName = getFirstNonDefaultGlyphName(uc, names[1:])
603 # if newGlyphName is None:
604 # # if we found no symbolic name, check in fallback list
605 # newGlyphName = fallbackGlyphNames.get(uc)
606 # if newGlyphName is not None:
607 # printDry('Using fallback %s' % newGlyphName)
608 if newGlyphName is not None:
609 printDry('Rename %s -> %s' % (dstGlyphName, newGlyphName))
610 for font in dstFonts:
611 if dstGlyphName in font:
612 renameGlyphsQueue[font][dstGlyphName] = newGlyphName
613 newNames[dstGlyphName] = newGlyphName
614
615 if len(newNames) == 0:
616 printDry('No changes')
617 return
618
619 # rename component instances
620 for font in dstFonts:
621 componentMap = font.getReverseComponentMapping()
622 for currName, newName in renameGlyphsQueue[font].iteritems():
623 for depName in componentMap.get(currName, []):
624 depG = font[depName]
625 for c in depG.components:
626 if c.baseGlyph == currName:
627 c.baseGlyph = newName
628 c.setChanged()
629
630 # rename glyphs
631 for font in dstFonts:
632 for currName, newName in renameGlyphsQueue[font].iteritems():
633 font[currName].name = newName
634
635 # save fonts and update font data
636 for font in dstFonts:
637 fontPath = dstFontPaths[font]
638 printDry('Saving %d glyphs in %s' % (len(newNames), fontPath))
639 if not args.dryRun:
640 font.save()
641 renameUFODetails(font, fontPath, newNames, dryRun=args.dryRun, print=printDry)
642
643 # update resource files
644 renameGlyphOrderFile(glyphOrderFile, newNames, dryRun=args.dryRun, print=printDry)
645 renameDiacriticsFile(diacriticsFile, newNames, dryRun=args.dryRun, print=printDry)
646 renameConfigFile(config, configFilename, newNames, dryRun=args.dryRun, print=printDry)
647
648
649 if __name__ == '__main__':
650 main()