summaryrefslogtreecommitdiff
path: root/misc/fixup-kerning.py
blob: fc4ce8071313db37572bb4787ef254d6a6e8769e (plain)
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
#!/usr/bin/env python
# encoding: utf8
from __future__ import print_function
import os, sys, plistlib, json
from collections import OrderedDict
from ConfigParser import RawConfigParser
from argparse import ArgumentParser
from fontTools import ttLib
from robofab.objects.objectsRF import OpenFont


def getTTCharMap(font): # -> { 2126: 'Omegagreek', ...}
  if isinstance(font, str):
    font = ttLib.TTFont(font)

  if not 'cmap' in font:
    raise Exception('missing cmap table')
  
  gl = {}
  bestCodeSubTable = None
  bestCodeSubTableFormat = 0

  for st in font['cmap'].tables:
    if st.platformID == 0: # 0=unicode, 1=mac, 2=(reserved), 3=microsoft
      if st.format > bestCodeSubTableFormat:
        bestCodeSubTable = st
        bestCodeSubTableFormat = st.format

  if bestCodeSubTable is not None:
    for cp, glyphname in bestCodeSubTable.cmap.items():
      if cp in gl:
        raise Exception('duplicate unicode-to-glyphname mapping: U+%04X => %r and %r' % (
          cp, glyphname, gl[cp]))
      gl[cp] = glyphname

  return gl


def revCharMap(ucToNames):
  # {2126:['Omega','Omegagr']} -> {'Omega':2126, 'Omegagr':2126}
  # {2126:'Omega'} -> {'Omega':2126}
  m = {}
  if len(ucToNames) == 0:
    return m

  lists = True
  for v in ucToNames.itervalues():
    lists = not isinstance(v, str)
    break

  if lists:
    for uc, names in ucToNames.iteritems():
      for name in names:
        m[name] = uc
  else:
    for uc, name in ucToNames.iteritems():
      m[name] = uc
    
  return m


def getGlyphNameDifferenceMap(srcCharMap, dstCharMap, dstRevCharMap):
  m = {} # { 'Omegagreek': 'Omega', ... }
  for uc, srcName in srcCharMap.iteritems():
    dstNames = dstCharMap.get(uc)
    if dstNames is not None and len(dstNames) > 0:
      if len(dstNames) != 1:
        print('warning: ignoring multi-glyph map for U+%04X in source font' % uc)
      dstName = dstNames[0]
      if srcName != dstName and srcName not in dstRevCharMap:
        # Only include names that differ. also, The `srcName not in dstRevCharMap` condition
        # makes sure that we don't rename glyphs that are already valid.
        m[srcName] = dstName
  return m


def fixupGroups(fontPath, dstGlyphNames, srcToDstMap, dryRun, stats):
  filename = os.path.join(fontPath, 'groups.plist')
  groups = plistlib.readPlist(filename)
  groups2 = {}
  glyphToGroups = {}

  for groupName, glyphNames in groups.iteritems():
    glyphNames2 = []
    for glyphName in glyphNames:
      if glyphName in srcToDstMap:
        gn2 = srcToDstMap[glyphName]
        stats.renamedGlyphs[glyphName] = gn2
        glyphName = gn2
      if glyphName in dstGlyphNames:
        glyphNames2.append(glyphName)
        glyphToGroups[glyphName] = glyphToGroups.get(glyphName, []) + [groupName]
      else:
        stats.removedGlyphs.add(glyphName)
    if len(glyphNames2) > 0:
      groups2[groupName] = glyphNames2
    else:
      stats.removedGroups.add(groupName)

  print('Writing', filename)
  if not dryRun:
    plistlib.writePlist(groups2, filename)

  return groups2, glyphToGroups


def fixupKerning(fontPath, dstGlyphNames, srcToDstMap, groups, glyphToGroups, dryRun, stats):
  filename = os.path.join(fontPath, 'kerning.plist')
  kerning = plistlib.readPlist(filename)
  kerning2 = {}
  groupPairs = {}  # { "lglyphname+lglyphname": ("lgroupname"|"", "rgroupname"|"", 123) }
  # pairs = {} # { "name+name" => 123 }

  for leftName, right in kerning.items():
    leftIsGroup = leftName[0] == '@'
    leftGroupNames = None

    if leftIsGroup:
      # left is a group
      if leftName not in groups:
        # dead group -- skip
        stats.removedGroups.add(leftName)
        continue
      leftGroupNames = groups[leftName]
    else:
      if leftName in srcToDstMap:
        leftName2 = srcToDstMap[leftName]
        stats.renamedGlyphs[leftName] = leftName2
        leftName = leftName2
      if leftName not in dstGlyphNames:
        # dead glyphname -- skip
        stats.removedGlyphs.add(leftName)
        continue

    right2 = {}
    rightGroupNamesAndValues = []
    for rightName, kerningValue in right.iteritems():
      rightIsGroup = rightName[0] == '@'
      if rightIsGroup:
        if leftIsGroup and leftGroupNames is None:
          leftGroupNames = [leftName]
        if rightName in groups:
          right2[rightName] = kerningValue
          rightGroupNamesAndValues.append((groups[rightName], rightName, kerningValue))
        else:
          stats.removedGroups.add(rightName)
      else:
        if rightName in srcToDstMap:
          rightName2 = srcToDstMap[rightName]
          stats.renamedGlyphs[rightName] = rightName2
          rightName = rightName2
        if rightName in dstGlyphNames:
          right2[rightName] = kerningValue
          if leftIsGroup:
            rightGroupNamesAndValues.append(([rightName], '', kerningValue))
        else:
          stats.removedGlyphs.add(rightName)

    if len(right2):
      kerning2[leftName] = right2

      # update groupPairs 
      lgroupname = leftName if rightIsGroup else ''
      if leftIsGroup:
        for lname in leftGroupNames:
          kPrefix = lname + '+'
          for rnames, rgroupname, kernv in rightGroupNamesAndValues:
            for rname in rnames:
              k = kPrefix + rname
              v = (lgroupname, rgroupname, kernv)
              if k in groupPairs:
                raise Exception('duplicate group pair %s: %r and %r' % (k, groupPairs[k], v))
              groupPairs[k] = v

    elif leftIsGroup:
      stats.removedGroups.add(leftName)
    else:
      stats.removedGlyphs.add(leftName)

  # print('groupPairs:', groupPairs)

  # remove individual pairs that are already represented through groups
  kerning = kerning2
  kerning2 = {}
  for leftName, right in kerning.items():
    leftIsGroup = leftName[0] == '@'
    # leftNames = groups[leftName] if leftIsGroup else [leftName]

    if not leftIsGroup:
      right2 = {}
      for rightName, kernVal in right.iteritems():
        rightIsGroup = rightName[0] == '@'
        if not rightIsGroup:
          k = leftName + '+' + rightName
          if k in groupPairs:
            groupPair = groupPairs[k]
            print(('simplify individual pair %r: kern %r (individual) -> %r (group)') % (
                  k, kernVal, groupPair[2]))
            stats.simplifiedKerningPairs.add(k)
          else:
            right2[rightName] = kernVal
        else:
          right2[rightName] = kernVal
    else:
      # TODO, probably
      right2 = right

    kerning2[leftName] = right2

  print('Writing', filename)
  if not dryRun:
    plistlib.writePlist(kerning2, filename)

  return kerning2


def loadJSONCharMap(filename):
  m = None
  if filename == '-':
    m = json.load(sys.stdin)
  else:
    with open(filename, 'r') as f:
      m = json.load(f)
  if not isinstance(m, dict):
    raise Exception('json root is not a dict')
  if len(m) > 0:
    for k, v in m.iteritems():
      if not isinstance(k, int) and not isinstance(k, float):
        raise Exception('json dict key is not a number')
      if not isinstance(v, str):
        raise Exception('json dict value is not a string')
      break
  return m


class Stats:
  def __init__(self):
    self.removedGroups = set()
    self.removedGlyphs = set()
    self.simplifiedKerningPairs = set()
    self.renamedGlyphs = {}


def configFindResFile(config, basedir, name):
  fn = os.path.join(basedir, config.get("res", name))
  if not os.path.isfile(fn):
    basedir = os.path.dirname(basedir)
    fn = os.path.join(basedir, config.get("res", name))
    if not os.path.isfile(fn):
      fn = None
  return fn


def main():
  jsonSchemaDescr = '{[unicode:int]: glyphname:string, ...}'

  argparser = ArgumentParser(
    description='Rename glyphnames in UFO kerning and remove unused groups and glyphnames.')

  argparser.add_argument(
    '-dry', dest='dryRun', action='store_const', const=True, default=False,
    help='Do not modify anything, but instead just print what would happen.')

  argparser.add_argument(
    '-no-stats', dest='noStats', action='store_const', const=True, default=False,
    help='Do not print statistics at the end.')

  argparser.add_argument(
    '-save-stats', dest='saveStatsPath', metavar='<file>', type=str,
    help='Write detailed statistics to JSON file.')

  argparser.add_argument(
    '-src-json', dest='srcJSONFile', metavar='<file>', type=str,
    help='JSON file to read glyph names from.'+
         ' Expected schema: ' + jsonSchemaDescr + ' (e.g. {2126: "Omega"})')

  argparser.add_argument(
    '-src-font', dest='srcFontFile', metavar='<file>', type=str,
    help='TrueType or OpenType font to read glyph names from.')

  argparser.add_argument(
    'dstFontsPaths', metavar='<ufofile>', type=str, nargs='+', help='UFO fonts to update')

  args = argparser.parse_args()
  dryRun = args.dryRun

  if args.srcJSONFile and args.srcFontFile:
    argparser.error('Both -src-json and -src-font specified -- please provide only one.')

  # Strip trailing slashes from font paths
  args.dstFontsPaths = [s.rstrip('/ ') for s in args.dstFontsPaths]

  # Load source char map
  srcCharMap = None
  if args.srcJSONFile:
    try:
      srcCharMap = loadJSONCharMap(args.srcJSONFile)
    except Exception as err:
      argparser.error('Invalid JSON: Expected schema %s (%s)' % (jsonSchemaDescr, err))
  elif args.srcFontFile:
    srcCharMap = getTTCharMap(args.srcFontFile.rstrip('/ '))  # -> { 2126: 'Omegagreek', ...}
  else:
    argparser.error('No source provided (-src-* argument missing)')
  if len(srcCharMap) == 0:
    print('Empty character map', file=sys.stderr)
    sys.exit(1)

  # Find project source dir
  srcDir = ''
  for dstFontPath in args.dstFontsPaths:
    s = os.path.dirname(dstFontPath)
    if not srcDir:
      srcDir = s
    elif srcDir != s:
      raise Exception('All <ufofile>s must be rooted in the same directory')

  # Load font project config
  # load fontbuild configuration
  config = RawConfigParser(dict_type=OrderedDict)
  configFilename = os.path.join(srcDir, 'fontbuild.cfg')
  config.read(configFilename)
  diacriticsFile = configFindResFile(config, srcDir, 'diacriticfile')

  for dstFontPath in args.dstFontsPaths:
    dstFont = OpenFont(dstFontPath)
    dstCharMap = dstFont.getCharacterMapping() # -> { 2126: [ 'Omega', ...], ...}
    dstRevCharMap = revCharMap(dstCharMap) # { 'Omega': 2126, ...}
    srcToDstMap = getGlyphNameDifferenceMap(srcCharMap, dstCharMap, dstRevCharMap)

    stats = Stats()

    groups, glyphToGroups = fixupGroups(dstFontPath, dstRevCharMap, srcToDstMap, dryRun, stats)
    fixupKerning(dstFontPath, dstRevCharMap, srcToDstMap, groups, glyphToGroups, dryRun, stats)

    # stats
    if args.saveStatsPath or not args.noStats:
      if not args.noStats:
        print('stats for %s:' % dstFontPath)
        print('  Deleted %d groups and %d glyphs.' % (
          len(stats.removedGroups), len(stats.removedGlyphs)))
        print('  Renamed %d glyphs.' % len(stats.renamedGlyphs))
        print('  Simplified %d kerning pairs.' % len(stats.simplifiedKerningPairs))
      if args.saveStatsPath:
        statsObj = {
          'deletedGroups': stats.removedGroups,
          'deletedGlyphs': stats.removedGlyphs,
          'simplifiedKerningPairs': stats.simplifiedKerningPairs,
          'renamedGlyphs': stats.renamedGlyphs,
        }
        f = sys.stdout
        try:
          if args.saveStatsPath != '-':
            f = open(args.saveStatsPath, 'w')
          print('Writing stats to', args.saveStatsPath)
          json.dump(statsObj, sys.stdout, indent=2, separators=(',', ': '))
        finally:
          if f is not sys.stdout:
            f.close()


if __name__ == '__main__':
  main()