36 lines
1.6 KiB
Python

"""Freeze a font's default variation and give it a unique preview/export family name."""
import sys
from fontTools.ttLib import TTFont, newTable
from fontTools.varLib.instancer import instantiateVariableFont
def prepare(source, destination, family):
font = TTFont(source, recalcTimestamp=False)
if 'fvar' in font:
axes = {axis.axisTag: axis.defaultValue for axis in font['fvar'].axes}
for axis in font['fvar'].axes:
if axis.axisTag == 'wght':
axes['wght'] = max(axis.minValue, min(axis.maxValue, 400))
font = instantiateVariableFont(font, axes, inplace=True)
for record in font['name'].names:
if record.nameID in (1, 2, 3, 4, 6, 16, 17):
value = 'Regular' if record.nameID in (2, 17) else family
if record.nameID == 6:
value = family.replace(' ', '-')[:63]
record.string = value.encode(record.getEncoding(), errors='replace')
# Two reference fonts declare OS/2 v5 but only contain the 96-byte v4 table.
# Correct the version tag without inventing missing metrics or changing outlines.
metrics = font.reader['OS/2']
if len(metrics) == 96 and int.from_bytes(metrics[:2], 'big') == 5:
table = newTable('OS/2')
table.decompile(b'\x00\x04' + metrics[2:], font)
font['OS/2'] = table
# A unique family per selected face prevents fontconfig confusing weight variants.
font['OS/2'].fsSelection &= ~((1 << 0) | (1 << 5))
font['OS/2'].fsSelection |= 1 << 6
font['OS/2'].usWeightClass = 400
font['head'].macStyle &= ~3
font.save(destination)
if __name__ == '__main__':
prepare(*sys.argv[1:4])