summaryrefslogtreecommitdiff
path: root/misc/ufocompile
blob: b7747a18b5d29a7c8bbf5f030d7a57f2cae227c7 (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
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
import logging
import subprocess

from shutil import copyfile
from robofab.objects.objectsRF import RPoint
from robofab.world import OpenFont
from fontbuild.Build import FontProject
from fontbuild.mix import Master
from fontbuild.mix import Mix


FAMILYNAME = "Inter UI"
BASEDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))

def extractSpecializedGlyphs(masterFont):
  glyphSpecializations = {}
  specializationSuffix = '.specz.'

  specializedGlyphNames = []
  font = masterFont.font
  for g in font:
    p = g.name.find(specializationSuffix)
    if p == -1:
      continue
    name = g.name[:p]
    category = g.name[p + len(specializationSuffix):]
    g2 = g.copy()
    g2.name = name
    if name in font:
      # copy unicodes
      masterGlyph = font[name]
      g2.unicodes = masterGlyph.unicodes
    if not category in glyphSpecializations:
      glyphSpecializations[category] = { name: g2 }
    else:
      glyphSpecializations[category][name] = g2
    specializedGlyphNames.append(g.name)

  ffont = masterFont.ffont
  for name in specializedGlyphNames:
    del ffont.glyphs[name]
    font.removeGlyph(name)

  return glyphSpecializations


def readVersionControlTag(dir):
  try:
    return subprocess.check_output(
      ['git', '-C', dir, 'rev-parse', '--short', 'HEAD'],
      shell=False).strip()
  except:
    return ''


def main():
  # silence warnings from fontTools.misc.fixedTools that is harmless and caused
  # by the ufo2ft module.
  logging.getLogger('fontTools.misc.fixedTools').setLevel(logging.ERROR)

  default_out_dir = os.path.join(BASEDIR,'build','tmp')
  srcDir = os.path.join(BASEDIR, 'src')

  argparser = argparse.ArgumentParser(
    description='Build TTF and OTF font files from UFO sources.')

  argparser.add_argument(
    'styles', metavar='<style>', type=str, nargs='*',
    help='Build specific styles. Omit to build all.')

  argparser.add_argument(
    '--otf', dest='otf', action='store_const',
    const=True, default=False, help='Build OTF files')

  argparser.add_argument(
    '--no-ttf', dest='no_ttf', action='store_const',
    const=True, default=False, help='Do not build TTF files')

  argparser.add_argument(
    '--out', dest='out', metavar='<dir>', type=str, default=default_out_dir,
    help='Write output to <dir> instead of the default (%r)' % default_out_dir)

  args = argparser.parse_args()
  styles = [s.lower() for s in args.styles]
  handledStyles = []
  ALL = len(styles) == 0

  # version control tag, if any
  buildTag = readVersionControlTag(BASEDIR)

  # Since we reference a shared feature file, copy it to build dir so includes
  # works
  ufoTmpDir = os.path.join(args.out, 'InterUIUFO')
  try:
    os.makedirs(ufoTmpDir)
  except:
    pass
  copyfile(
    os.path.join(srcDir, 'features.fea'),
    os.path.join(ufoTmpDir, 'features.fea'))

  # Load masters
  print('loading master: Regular')
  rg = Master("%s/src/Inter-UI-Regular.ufo" % BASEDIR)

  bl = None
  if ALL \
  or 'black' in styles or 'blackitalic' in styles \
  or 'bold' in styles or 'bolditalic' in styles \
  or 'medium' in styles or 'mediumitalic' in styles:
    print('loading master: Black')
    bl = Master("%s/src/Inter-UI-Black.ufo" % BASEDIR)


  glyphSpecializations = extractSpecializedGlyphs(rg)


  class Mix2(Mix):
    def __init__(self, masters, v, glyphSpecializations=None):
      Mix.__init__(self, masters, v)
      self.glyphSpecializations = glyphSpecializations

    def mixGlyphs(self, gname):
      if self.glyphSpecializations is not None:
        specializedGlyph = self.glyphSpecializations.get(gname)
        if specializedGlyph is not None:
          print('mixglyph using specialized', gname)
          return specializedGlyph
      return Mix.mixGlyphs(self, gname)

  proj = FontProject(
    rg.font, BASEDIR, os.path.join(srcDir,'fontbuild.cfg'), buildTag=buildTag)
  proj.builddir = args.out

  # panose for entire family
  panose = {
    'bFamilyType': 2,  # Latin Text
    'bSerifStyle': 11, # Normal Sans
    'bProportion': 2,  # Old Style
    'bContrast': 3,    # Very Low (thickest vs thinnest stem of "O")
    'bXHeight': 4,     # Constant/Large
    # bWeight: see http://monotype.de/services/pan2#_Toc380547249
  }

  def mkpanose(weight):
    return dict(panose.items() + {
      'bWeight': weight
    }.items())


  if args.otf:
    proj.buildOTF = True

  # name syntax: family/styleName/styleCode/subfamilyAbbrev
  #
  # styleCode should be one of:
  #   Regular, Italic, Bold, Bold Italic
  #
  # italicNarrowAmount controls scale on the x axis. 1.0 means no scaling.
  # italicMeanYCenter controls how far on the x axis the glyph should slide
  #   to compensate for the slant.

  if ALL or 'regular' in styles:
    handledStyles.append('regular')
    proj.generateFont(rg.font, "%s/Regular/Regular/Rg" % FAMILYNAME,
    panose=mkpanose(5))

  if ALL or 'italic' in styles:
    handledStyles.append('italic')
    proj.generateFont(
      rg.font, "%s/Italic/Italic/Rg" % FAMILYNAME,
      italic=True, stemWidth=232, italicMeanYCenter=-825, italicNarrowAmount=1,
      panose=mkpanose(5))


  if ALL or 'medium' in styles:
    handledStyles.append('medium')
    proj.generateFont(
      Mix2([rg, bl], 0.35, glyphSpecializations.get('medium', {})),
      "%s/Medium/Regular/Me" % FAMILYNAME,
      panose=mkpanose(6))

  if ALL or 'mediumitalic' in styles:
    handledStyles.append('mediumitalic')
    proj.generateFont(
      Mix2([rg, bl], 0.35, glyphSpecializations.get('medium', {})),
      "%s/Medium Italic/Italic/Me" % FAMILYNAME,
      italic=True, stemWidth=300, italicMeanYCenter=-825, italicNarrowAmount=1,
      panose=mkpanose(6))


  if ALL or 'bold' in styles:
    handledStyles.append('bold')
    proj.generateFont(
      Mix2([rg, bl], 0.65, glyphSpecializations.get('bold', {})),
      "%s/Bold/Bold/Rg" % FAMILYNAME,
      panose=mkpanose(8))

  if ALL or 'bolditalic' in styles:
    handledStyles.append('bolditalic')
    proj.generateFont(
      Mix2([rg, bl], 0.65, glyphSpecializations.get('bold', {})),
      "%s/Bold Italic/Bold Italic/Rg" % FAMILYNAME,
      italic=True, stemWidth=350, italicMeanYCenter=-825, italicNarrowAmount=1,
      panose=mkpanose(8))


  if ALL or 'black' in styles:
    handledStyles.append('black')
    proj.generateFont(bl.font, "%s/Black/Regular/Bl" % FAMILYNAME,
      panose=mkpanose(9))

  if ALL or 'blackitalic' in styles:
    handledStyles.append('blackitalic')
    proj.generateFont(
      bl.font, "%s/Black Italic/Italic/Bl" % FAMILYNAME,
      italic=True, stemWidth=400, italicMeanYCenter=-825, italicNarrowAmount=1,
      panose=mkpanose(9))

  # generate TTFs
  if args.no_ttf == False:
    proj.generateTTFs()

  if not ALL:
    diff = set(styles).difference(set(handledStyles))
    if len(diff) != 0:
      print('Unknown styles %r' % diff, file=sys.stderr)
      sys.exit(1)

main()

# import hotshot, hotshot.stats, test.pystone
# prof = hotshot.Profile("ufocompile.prof")
# benchtime = prof.runcall(main)
# prof.close()
# stats = hotshot.stats.load("ufocompile.prof")
# # stats.strip_dirs()
# stats.sort_stats('time', 'calls')
# stats.print_stats(40)