| 1 |
#!/usr/bin/python |
| 2 |
# coding=utf-8 |
| 3 |
# |
| 4 |
# Font build utility |
| 5 |
# |
| 6 |
|
| 7 |
import sys |
| 8 |
import time |
| 9 |
import os |
| 10 |
import fontforge |
| 11 |
import psMat |
| 12 |
from tempfile import mkstemp |
| 13 |
from fontTools.ttLib import TTFont |
| 14 |
from fontTools.ttx import makeOutputFileName |
| 15 |
import argparse |
| 16 |
|
| 17 |
|
| 18 |
def flattenNestedReferences(font, ref, new_transform=(1, 0, 0, 1, 0, 0)): |
| 19 |
"""Flattens nested references by replacing them with the ultimate reference |
| 20 |
and applying any transformation matrices involved, so that the final font |
| 21 |
has only simple composite glyphs. This to work around what seems to be an |
| 22 |
Apple bug that results in ignoring transformation matrix of nested |
| 23 |
references.""" |
| 24 |
|
| 25 |
name = ref[0] |
| 26 |
transform = ref[1] |
| 27 |
glyph = font[name] |
| 28 |
new_ref = [] |
| 29 |
if glyph.references and glyph.foreground.isEmpty(): |
| 30 |
for nested_ref in glyph.references: |
| 31 |
for i in flattenNestedReferences(font, nested_ref, transform): |
| 32 |
matrix = psMat.compose(i[1], new_transform) |
| 33 |
new_ref.append((i[0], matrix)) |
| 34 |
else: |
| 35 |
matrix = psMat.compose(transform, new_transform) |
| 36 |
new_ref.append((name, matrix)) |
| 37 |
|
| 38 |
return new_ref |
| 39 |
|
| 40 |
|
| 41 |
def validateGlyphs(font): |
| 42 |
"""Fixes some common FontForge validation warnings, currently handles: |
| 43 |
* wrong direction |
| 44 |
* flipped references |
| 45 |
In addition to flattening nested references.""" |
| 46 |
|
| 47 |
wrong_dir = 0x8 |
| 48 |
flipped_ref = 0x10 |
| 49 |
for glyph in font.glyphs(): |
| 50 |
state = glyph.validate(True) |
| 51 |
refs = [] |
| 52 |
|
| 53 |
if state & flipped_ref: |
| 54 |
glyph.unlinkRef() |
| 55 |
glyph.correctDirection() |
| 56 |
if state & wrong_dir: |
| 57 |
glyph.correctDirection() |
| 58 |
|
| 59 |
for ref in glyph.references: |
| 60 |
for i in flattenNestedReferences(font, ref): |
| 61 |
refs.append(i) |
| 62 |
if refs: |
| 63 |
glyph.references = refs |
| 64 |
|
| 65 |
glyph.round() |
| 66 |
|
| 67 |
# Hack, OTS rejects ligature carets! |
| 68 |
glyph.lcarets = () |
| 69 |
|
| 70 |
|
| 71 |
def fixGasp(font, value=15): |
| 72 |
try: |
| 73 |
table = font.get('gasp') |
| 74 |
table.gaspRange[65535] = value |
| 75 |
except: |
| 76 |
print('ER: {}: no table gasp') |
| 77 |
|
| 78 |
|
| 79 |
def fixXAvgCharWidth(font): |
| 80 |
"""xAvgCharWidth should be the average of all glyph widths in the font""" |
| 81 |
width_sum = 0 |
| 82 |
count = 0 |
| 83 |
for glyph_id in font['glyf'].glyphs: |
| 84 |
width = font['hmtx'].metrics[glyph_id][0] |
| 85 |
if width > 0: |
| 86 |
count += 1 |
| 87 |
width_sum += width |
| 88 |
if count == 0: |
| 89 |
fb.error("CRITICAL: Found no glyph width data!") |
| 90 |
else: |
| 91 |
expected_value = int(round(width_sum) / count) |
| 92 |
font['OS/2'].xAvgCharWidth = int(round(width_sum) / count) |
| 93 |
|
| 94 |
|
| 95 |
def opentype(infont, outdir, type, feature, version): |
| 96 |
font = fontforge.open(infont) |
| 97 |
if args.type == 'otf': |
| 98 |
outfont = infont.replace(".sfd", ".otf") |
| 99 |
flags = ("opentype", "round", "omit-instructions", "dummy-dsig") |
| 100 |
else: |
| 101 |
outfont = infont.replace(".sfd", ".ttf") |
| 102 |
flags = ("opentype", "round", "omit-instructions", "dummy-dsig") |
| 103 |
outfont = os.path.join(outdir, outfont) |
| 104 |
print("Generating %s => %s" % (infont, outfont)) |
| 105 |
tmpfont = mkstemp(suffix=os.path.basename(outfont))[1] |
| 106 |
|
| 107 |
# Remove all GSUB lookups |
| 108 |
for lookup in font.gsub_lookups: |
| 109 |
font.removeLookup(lookup) |
| 110 |
|
| 111 |
# Remove all GPOS lookups |
| 112 |
for lookup in font.gpos_lookups: |
| 113 |
font.removeLookup(lookup) |
| 114 |
|
| 115 |
# Merge the new featurefile |
| 116 |
font.mergeFeature(feature) |
| 117 |
font.version = version |
| 118 |
font.appendSFNTName('English (US)', 'Version', |
| 119 |
'Version ' + version + '.0+' + time.strftime('%Y%m%d')) |
| 120 |
font.selection.all() |
| 121 |
font.correctReferences() |
| 122 |
font.simplify() |
| 123 |
font.selection.none() |
| 124 |
# fix some common font issues |
| 125 |
validateGlyphs(font) |
| 126 |
font.generate(tmpfont, flags=flags) |
| 127 |
font.close() |
| 128 |
# now open in fontTools |
| 129 |
font = TTFont(tmpfont, recalcBBoxes=0) |
| 130 |
|
| 131 |
# our 'name' table is a bit bulky, and of almost no use in for web fonts, |
| 132 |
# so we strip all unnecessary entries. |
| 133 |
name = font['name'] |
| 134 |
names = [] |
| 135 |
for record in name.names: |
| 136 |
platID = record.platformID |
| 137 |
langID = record.langID |
| 138 |
nameID = record.nameID |
| 139 |
|
| 140 |
# we keep only en_US entries in Windows and Mac platform id, every |
| 141 |
# thing else is dropped |
| 142 |
if (platID == 1 and langID == 0) or (platID == 3 and langID == 1033): |
| 143 |
if nameID == 13: |
| 144 |
# the full OFL text is too much, replace it with a simple |
| 145 |
# string |
| 146 |
if platID == 3: |
| 147 |
# MS strings are UTF-16 encoded |
| 148 |
text = 'OFL v1.1'.encode('utf_16_be') |
| 149 |
else: |
| 150 |
text = 'OFL v1.1' |
| 151 |
record.string = text |
| 152 |
names.append(record) |
| 153 |
# keep every thing else except Descriptor, Sample Text |
| 154 |
elif nameID not in (10, 19): |
| 155 |
names.append(record) |
| 156 |
|
| 157 |
name.names = names |
| 158 |
font['OS/2'].version = 4 |
| 159 |
# https://www.microsoft.com/typography/otspec/os2.htm#fst |
| 160 |
font['OS/2'].fsType = 0 |
| 161 |
if args.type == 'ttf': |
| 162 |
fixGasp(font) |
| 163 |
fixXAvgCharWidth(font) |
| 164 |
# FFTM is FontForge specific, remove it |
| 165 |
del(font['FFTM']) |
| 166 |
# force compiling GPOS/GSUB tables by fontTools, saves few tens of KBs |
| 167 |
for tag in ('GPOS', 'GSUB'): |
| 168 |
font[tag].compile(font) |
| 169 |
|
| 170 |
font.save(outfont) |
| 171 |
font.close() |
| 172 |
os.remove(tmpfont) |
| 173 |
|
| 174 |
|
| 175 |
def webfonts(infont, type): |
| 176 |
font = TTFont(infont, recalcBBoxes=0) |
| 177 |
# Generate WOFF2 |
| 178 |
woffFileName = makeOutputFileName(infont, outputDir=None, extension='.' + type) |
| 179 |
print("Processing %s => %s" % (infont, woffFileName)) |
| 180 |
font.flavor = type |
| 181 |
font.save(woffFileName, reorderTables=False) |
| 182 |
font.close() |
| 183 |
|
| 184 |
|
| 185 |
if __name__ == "__main__": |
| 186 |
parser = argparse.ArgumentParser(description='Build fonts') |
| 187 |
parser.add_argument('-i', '--input', help='Input font', required=True) |
| 188 |
parser.add_argument('-v', '--version', help='Version') |
| 189 |
parser.add_argument('-f', '--feature', help='Feature file') |
| 190 |
parser.add_argument('-t', '--type', help='Output type', default='otf') |
| 191 |
parser.add_argument('-o', '--outdir', help='Output directory', default='build') |
| 192 |
args = parser.parse_args() |
| 193 |
if not os.path.exists(args.outdir): |
| 194 |
os.mkdir(args.outdir) |
| 195 |
if args.type == 'otf' or args.type == 'ttf': |
| 196 |
opentype(args.input, args.outdir, args.type, args.feature, args.version) |
| 197 |
if args.type == 'woff' or args.type == 'woff2': |
| 198 |
webfonts(args.input, args.type) |