summaryrefslogtreecommitdiff
path: root/misc/fontinfo.py
blob: 17ee4f521e17cb5e8affb0ca1107eb6f800997c8 (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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
#!/usr/bin/env python
# encoding: utf8
#
# Generates JSON-encoded information about fonts
#
import os
import sys
import argparse
import json
from base64 import b64encode

from fontTools import ttLib
from fontTools.misc import sstruct
from fontTools.ttLib.tables._h_e_a_d import headFormat
from fontTools.ttLib.tables._h_h_e_a import hheaFormat
from fontTools.ttLib.tables._m_a_x_p import maxpFormat_0_5, maxpFormat_1_0_add
from fontTools.ttLib.tables._p_o_s_t import postFormat
from fontTools.ttLib.tables.O_S_2f_2 import OS2_format_1, OS2_format_2, OS2_format_5, panoseFormat
from fontTools.ttLib.tables._m_e_t_a import table__m_e_t_a
# from robofab.world import world, RFont, RGlyph, OpenFont, NewFont
# from robofab.objects.objectsRF import RFont, RGlyph, OpenFont, NewFont, RContour

_NAME_IDS = {}


panoseWeights = [
  'Any', # 0
  'No Fit', # 1
  'Very Light', # 2
  'Light', # 3
  'Thin', # 4
  'Book', # 5
  'Medium', # 6
  'Demi', # 7
  'Bold', # 8
  'Heavy', # 9
  'Black', # 10
  'Extra Black', # 11
]

panoseProportion = [
  'Any', # 0
  'No fit', # 1
  'Old Style/Regular', # 2
  'Modern', # 3
  'Even Width', # 4
  'Extended', # 5
  'Condensed', # 6
  'Very Extended', # 7
  'Very Condensed', # 8
  'Monospaced', # 9
]

os2WidthClass = [
  None,
  'Ultra-condensed', # 1
  'Extra-condensed', # 2
  'Condensed', # 3
  'Semi-condensed', # 4
  'Medium (normal)', # 5
  'Semi-expanded', # 6
  'Expanded', # 7
  'Extra-expanded', # 8
  'Ultra-expanded', # 9
]

os2WeightClass = {
  100: 'Thin',
  200: 'Extra-light (Ultra-light)',
  300: 'Light',
  400: 'Normal (Regular)',
  500: 'Medium',
  600: 'Semi-bold (Demi-bold)',
  700: 'Bold',
  800: 'Extra-bold (Ultra-bold)',
  900: 'Black (Heavy)',
}


def num(s):
  return int(s) if s.find('.') == -1 else float(s)


def tableNamesToDict(table, names):
  t = {}
  for name in names:
    if name.find('reserved') == 0:
      continue
    t[name] = getattr(table, name)
  return t


def sstructTableToDict(table, format):
  _, names, _ = sstruct.getformat(format)
  return tableNamesToDict(table, names)


OUTPUT_TYPE_COMPLETE = 'complete'
OUTPUT_TYPE_GLYPHLIST = 'glyphlist'


GLYPHS_TYPE_UNKNOWN = '?'
GLYPHS_TYPE_TT = 'tt'
GLYPHS_TYPE_CFF = 'cff'

def getGlyphsType(tt):
  if 'CFF ' in tt:
    return GLYPHS_TYPE_CFF
  elif 'glyf' in tt:
    return GLYPHS_TYPE_TT
  return GLYPHS_TYPE_UNKNOWN


class GlyphInfo:
  def __init__(self, g, name, unicodes, type, glyphTable):
    self._type = type # GLYPHS_TYPE_*
    self._glyphTable = glyphTable

    self.name     = name
    self.width    = g.width
    self.lsb      = g.lsb
    self.unicodes = unicodes

    if g.height is not None:
      self.tsb    = g.tsb
      self.height = g.height
    else:
      self.tsb    = 0
      self.height = 0

    self.numContours = 0
    self.contoursBBox = (0,0,0,0) # xMin, yMin, xMax, yMax
    self.hasHints = False

    if self._type is GLYPHS_TYPE_CFF:
      self._addCFFInfo()
    elif self._type is GLYPHS_TYPE_TT:
      self._addTTInfo()

  def _addTTInfo(self):
    g = self._glyphTable[self.name]
    self.numContours = g.numberOfContours
    if g.numberOfContours:
      self.contoursBBox = (g.xMin,g.xMin,g.xMax,g.yMax)
    self.hasHints = hasattr(g, "program")

  def _addCFFInfo(self):
    # TODO: parse CFF dict tree
    pass

  @classmethod
  def structKeys(cls, type):
    v = [
      'name',
      'unicodes',
      'width',
      'lsb',
      'height',
      'tsb',
      'hasHints',
    ]
    if type is GLYPHS_TYPE_TT:
      v += (
        'numContours',
        'contoursBBox',
      )
    return v

  def structValues(self):
    v = [
      self.name,
      self.unicodes,
      self.width,
      self.lsb,
      self.height,
      self.tsb,
      self.hasHints,
    ]
    if self._type is GLYPHS_TYPE_TT:
      v += (
        self.numContours,
        self.contoursBBox,
      )
    return v


# exported convenience function
def GenGlyphList(font, withGlyphs=None):
  if isinstance(font, str):
    font = ttLib.TTFont(font)
  return genGlyphsInfo(font, OUTPUT_TYPE_GLYPHLIST)


def genGlyphsInfo(tt, outputType, glyphsType=GLYPHS_TYPE_UNKNOWN, glyphsTable=None, withGlyphs=None):
  unicodeMap = {}

  glyphnameFilter = None
  if isinstance(withGlyphs, str):
    glyphnameFilter = withGlyphs.split(',')

  if 'cmap' in tt:
    # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
    bestCodeSubTable = None
    bestCodeSubTableFormat = 0
    for st in tt['cmap'].tables:
      if st.platformID == 0: # 0=unicode, 1=mac, 2=(reserved), 3=microsoft
        if st.format > bestCodeSubTableFormat:
          bestCodeSubTable = st
          bestCodeSubTableFormat = st.format
    for cp, glyphname in bestCodeSubTable.cmap.items():
      if glyphname in unicodeMap:
        unicodeMap[glyphname].append(cp)
      else:
        unicodeMap[glyphname] = [cp]

  glyphValues = []
  glyphset = tt.getGlyphSet(preferCFF=glyphsType is GLYPHS_TYPE_CFF)

  glyphnames = tt.getGlyphOrder() if glyphnameFilter is None else glyphnameFilter

  if outputType is OUTPUT_TYPE_GLYPHLIST:
    glyphValues = []
    for glyphname in glyphnames:
      v = [glyphname]
      if glyphname in unicodeMap:
        v += unicodeMap[glyphname]
      glyphValues.append(v)
    return glyphValues
  
  for glyphname in glyphnames:
    unicodes = unicodeMap[glyphname] if glyphname in unicodeMap else []
    try:
      g = glyphset[glyphname]
    except KeyError:
      raise Exception('no such glyph "'+glyphname+'"')
    gi = GlyphInfo(g, glyphname, unicodes, glyphsType, glyphsTable)
    glyphValues.append(gi.structValues())

  return {
    'keys': GlyphInfo.structKeys(glyphsType),
    'values': glyphValues,
  }


def copyDictEntry(srcD, srcName, dstD, dstName):
  try:
    dstD[dstName] = srcD[srcName]
  except:
    pass


def addCFFFontInfo(tt, info, cffTable):
  d = cffTable.rawDict

  nameDict = None
  if 'name' not in info:
    nameDict = {}
    info['name'] = nameDict
  else:
    nameDict = info['name']

  copyDictEntry(d, 'Weight', nameDict, 'weight')
  copyDictEntry(d, 'version', nameDict, 'version')


def genFontInfo(fontpath, outputType, withGlyphs=True):
  tt = ttLib.TTFont(fontpath) # lazy=True
  info = {
    'id': fontpath,
  }

  # for tableName in tt.keys():
  #   print 'table', tableName

  nameDict = {}
  if 'name' in tt:
    nameDict = {}
    for rec in tt['name'].names:
      k = _NAME_IDS[rec.nameID] if rec.nameID in _NAME_IDS else ('#%d' % rec.nameID)
      nameDict[k] = rec.toUnicode()
    if 'fontId' in nameDict:
      info['id'] = nameDict['fontId']

  if 'postscriptName' in nameDict:
    info['name'] = nameDict['postscriptName']
  elif 'familyName' in nameDict:
    info['name'] = nameDict['familyName'].replace(' ', '')
    if 'subfamilyName' in nameDict:
      info['name'] += '-' + nameDict['subfamilyName'].replace(' ', '')

  if outputType is not OUTPUT_TYPE_GLYPHLIST:
    if len(nameDict):
      info['names'] = nameDict

    if 'head' in tt:
      head = sstructTableToDict(tt['head'], headFormat)
      if 'macStyle' in head:
        s = []
        v = head['macStyle']
        if isinstance(v, int):
          if v & 0b00000001: s.append('Bold')
          if v & 0b00000010: s.append('Italic')
          if v & 0b00000100: s.append('Underline')
          if v & 0b00001000: s.append('Outline')
          if v & 0b00010000: s.append('Shadow')
          if v & 0b00100000: s.append('Condensed')
          if v & 0b01000000: s.append('Extended')
          head['macStyle_raw'] = head['macStyle']
          head['macStyle'] = s
      info['head'] = head

    if 'hhea' in tt:
      info['hhea'] = sstructTableToDict(tt['hhea'], hheaFormat)

    if 'post' in tt:
      info['post'] = sstructTableToDict(tt['post'], postFormat)

    if 'OS/2' in tt:
      t = tt['OS/2']
      os2 = None
      if t.version == 1:
        os2 = sstructTableToDict(t, OS2_format_1)
      elif t.version in (2, 3, 4):
        os2 = sstructTableToDict(t, OS2_format_2)
      elif t.version == 5:
        os2 = sstructTableToDict(t, OS2_format_5)
        os2['usLowerOpticalPointSize'] /= 20
        os2['usUpperOpticalPointSize'] /= 20

      if 'panose' in os2:
        panose = {}
        for k,v in sstructTableToDict(os2['panose'], panoseFormat).iteritems():
          if k[0:1] == 'b' and k[1].isupper():
            k = k[1].lower() + k[2:]
            # bFooBar => fooBar
          if k == 'weight' and isinstance(v, int) and v < len(panoseWeights):
            panose['weightName'] = panoseWeights[v]
          elif k == 'proportion' and isinstance(v, int) and v < len(panoseProportion):
            panose['proportionName'] = panoseProportion[v]
          panose[k] = v
        os2['panose'] = panose

      if 'usWidthClass' in os2:
        v = os2['usWidthClass']
        if isinstance(v, int) and v > 0 and v < len(os2WidthClass):
          os2['usWidthClassName'] = os2WidthClass[v]

      if 'usWeightClass' in os2:
        v = os2['usWeightClass']
        name = os2WeightClass.get(os2['usWeightClass'])
        if name:
          os2['usWeightClassName'] = name

      info['os/2'] = os2

    if 'meta' in tt:
      meta = {}
      for k,v in tt['meta'].data.iteritems():
        try:
          v.decode('utf8')
          meta[k] = v
        except:
          meta[k] = 'data:;base64,' + b64encode(v)
      info['meta'] = meta

    # if 'maxp' in tt:
    #   table = tt['maxp']
    #   _, names, _ = sstruct.getformat(maxpFormat_0_5)
    #   if table.tableVersion != 0x00005000:
    #     _, names_1_0, _ = sstruct.getformat(maxpFormat_1_0_add)
    #     names += names_1_0
    #   info['maxp'] = tableNamesToDict(table, names)

  glyphsType = getGlyphsType(tt)
  glyphsTable = None
  if glyphsType is GLYPHS_TYPE_CFF:
    cff = tt["CFF "].cff
    cffDictIndex = cff.topDictIndex
    if len(cffDictIndex) > 1:
      sys.stderr.write(
        'warning: multi-font CFF table is unsupported. Only reporting first table.\n'
      )
    cffTable = cffDictIndex[0]
    if outputType is not OUTPUT_TYPE_GLYPHLIST:
      addCFFFontInfo(tt, info, cffTable)
  elif glyphsType is GLYPHS_TYPE_TT:
    glyphsTable = tt["glyf"]
  # print 'glyphs type:', glyphsType, 'flavor:', tt.flavor, 'sfntVersion:', tt.sfntVersion

  if (withGlyphs is not False or outputType is OUTPUT_TYPE_GLYPHLIST) and withGlyphs is not '':
    info['glyphs'] = genGlyphsInfo(tt, outputType, glyphsType, glyphsTable, withGlyphs)

  # sys.exit(1)

  return info


# ————————————————————————————————————————————————————————————————————————
# main

def main():
  argparser = argparse.ArgumentParser(description='Generate JSON describing fonts')

  argparser.add_argument('-out', dest='outfile', metavar='<file>', type=str,
                         help='Write JSON to <file>. Writes to stdout if not specified')

  argparser.add_argument('-pretty', dest='prettyJson', action='store_const',
                         const=True, default=False,
                         help='Generate pretty JSON with linebreaks and indentation')

  argparser.add_argument('-with-all-glyphs', dest='withGlyphs', action='store_const',
                         const=True, default=False,
                         help='Include glyph information on all glyphs.')

  argparser.add_argument('-with-glyphs', dest='withGlyphs', metavar='glyphname[,glyphname ...]',
                         type=str,
                         help='Include glyph information on specific glyphs')

  argparser.add_argument('-as-glyphlist', dest='asGlyphList',
                         action='store_const', const=True, default=False,
                         help='Only generate a list of glyphs and their unicode mappings.')

  argparser.add_argument('fontpaths', metavar='<path>', type=str, nargs='+',
                         help='TrueType or OpenType font files')

  args = argparser.parse_args()

  fonts = {}
  outputType = OUTPUT_TYPE_COMPLETE
  if args.asGlyphList:
    outputType = OUTPUT_TYPE_GLYPHLIST

  n = 0
  for fontpath in args.fontpaths:
    if n > 0:
      # workaround for a bug in fontTools.misc.sstruct where it keeps a global
      # internal cache that mixes up values for different fonts.
      reload(sstruct)
    font = genFontInfo(fontpath, outputType=outputType, withGlyphs=args.withGlyphs)
    fonts[font['id']] = font
    n += 1

  ostream = sys.stdout
  if args.outfile is not None:
    ostream = open(args.outfile, 'w')


  if args.prettyJson:
    json.dump(fonts, ostream, sort_keys=True, indent=2, separators=(',', ': '))
  else:
    json.dump(fonts, ostream, separators=(',', ':'))


  if ostream is not sys.stdout:
    ostream.close()



# "name" table name identifiers
_NAME_IDS = {
  # TrueType & OpenType
   0: 'copyright',
   1: 'familyName',
   2: 'subfamilyName',
   3: 'fontId',
   4: 'fullName',
   5: 'version', # e.g. 'Version <number>.<number>'
   6: 'postscriptName',
   7: 'trademark',
   8: 'manufacturerName',
   9: 'designer',
  10: 'description',
  11: 'vendorURL',
  12: 'designerURL',
  13: 'licenseDescription',
  14: 'licenseURL',
  15: 'RESERVED',
  16: 'typoFamilyName',
  17: 'typoSubfamilyName',
  18: 'macCompatibleFullName', # Mac only (FOND)
  19: 'sampleText',

  # OpenType
  20: 'postScriptCIDName',
  21: 'wwsFamilyName',
  22: 'wwsSubfamilyName',
  23: 'lightBackgoundPalette',
  24: 'darkBackgoundPalette',
  25: 'variationsPostScriptNamePrefix',

  # 26-255: Reserved for future expansion
  # 256-32767: Font-specific names (layout features and settings, variations, track names, etc.)
}

if __name__ == '__main__':
  main()