summaryrefslogtreecommitdiff
path: root/misc/tools/gen-glyphinfo.py
blob: 877bbbdd46dcafdb4b0b85a92107a3b64198647b (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
#!/usr/bin/env python
# encoding: utf8
#
# Grab http://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
#
import os, sys
from os.path import dirname, basename, abspath, relpath, join as pjoin
sys.path.append(abspath(pjoin(dirname(__file__), 'tools')))
from common import BASEDIR, getVersion, getLocalTimeZoneOffset

import json, re
import time
from argparse import ArgumentParser
from collections import OrderedDict
from configparser import RawConfigParser
from unicode_util import parseUnicodeDataFile
from defcon import Font


def rgbaToCSSColor(r=0, g=0, b=0, a=1):
  R,G,B = int(r * 255), int(g * 255), int(b * 255)
  if a == 1:
    return '#%02x%02x%02x' % (R,G,B)
  else:
    return 'rgba(%d,%d,%d,%g)' % (R,G,B,a)


def unicodeName(cp):
  if cp is not None and len(cp.name):
    if cp.name[0] == '<':
      return '[' + cp.categoryName + ']'
    elif len(cp.name):
      return cp.name
  return None


# YYYY/MM/DD HH:mm:ss => YYYY-MM-DDTHH:mm:ssZ  (local time -> UTC)
def localDateTimeToUTCStr(localstr, pattern='%Y/%m/%d %H:%M:%S'):
  t = time.strptime(localstr, pattern)
  ts = time.mktime(t) - getLocalTimeZoneOffset()
  return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.localtime(ts))


def include_glyph(g):
  if 'com.schriftgestaltung.Glyphs.Export' in g.lib:
    if not g.lib['com.schriftgestaltung.Glyphs.Export']:
      return False
  return True


NAME_TO_ID_RE = re.compile(r'([A-Z_])')


def processGlyph(g, ucd):
  name = g.name

  # color
  color = None
  if 'public.markColor' in g.lib:
    rgba = [float(c.strip()) for c in g.lib['public.markColor'].strip().split(',')]
    color = rgbaToCSSColor(*rgba)

  isEmpty = 0
  if not g.bounds or g.bounds[3] == 0:
    isEmpty = 1

  id = NAME_TO_ID_RE.sub(r'\1_', name).lower()

  # name, isEmpty, unicode, unicodeName, color
  glyph = None
  ucs = g.unicodes
  if len(ucs):
    for uc in ucs:
      ucName = unicodeName(ucd.get(uc))
      # if not ucName and uc >= 0xE000 and uc <= 0xF8FF:
      #   ucName = '[private use %04X]' % uc
      ucstr = '%04X' % uc
      if color:
        glyph = [id, name, isEmpty, ucstr, ucName, color]
      elif ucName:
        glyph = [id, name, isEmpty, ucstr, ucName]
      else:
        glyph = [id, name, isEmpty, ucstr]
      break
  else:
    if color:
      glyph = [id, name, isEmpty, None, None, color]
    else:
      glyph = [id, name, isEmpty]

  return glyph


def glyphSortFun(g):
  if len(g) > 3 and g[3] is not None:
    return g[3]
  elif len(g) > 0:
    return g[1]
  else:
    return ""


def main():
  argparser = ArgumentParser(
    description='Generate info on name, unicodes and color mark for all glyphs')

  argparser.add_argument(
    '-ucd', dest='ucdFile', metavar='<file>', type=str,
    help='UnicodeData.txt file from http://www.unicode.org/')

  argparser.add_argument(
    'fontPath', metavar='<ufofile>', type=str)

  args = argparser.parse_args()
  font = Font(args.fontPath)
  ucd = {}
  if args.ucdFile:
    ucd = parseUnicodeDataFile(args.ucdFile)

  glyphs = []  # contains final glyph data printed as JSON
  unorderedGlyphs = []
  seenGlyphs = set()
  for name in font.lib['public.glyphOrder']:
    if name not in font:
      print(f'warning: glyph "{name}" (in public.glyphOrder) does not exist',
        file=sys.stderr)
      continue
    g = font[name]
    seenGlyphs.add(g)
    if include_glyph(g):
      glyphs.append(processGlyph(g, ucd))
  for g in font:
    if include_glyph(g) and g not in seenGlyphs:
      unorderedGlyphs.append(processGlyph(g, ucd))

  # append unorderedGlyphs, sorted by unicode
  glyphs = glyphs + sorted(unorderedGlyphs, key=glyphSortFun)

  print('{"glyphs":[')
  prefix = '  '
  for g in glyphs:
    print(prefix + json.dumps(g))
    if prefix == '  ':
      prefix = ', '
  print(']}')


if __name__ == '__main__':
  main()