#!/usr/bin/env python3 """Build internal/fonts/files/ from internal/fonts/fonts.json and sources.json. For every family and style it writes one static TrueType file (what the PDF exporter embeds and the Mac app bundles), one woff2 of exactly that file (what the browser loads), and one tiny name-only woff2 for the font picker. The woff2 is a lossless wrapper, so the screen and the PDF use the same font program. Run it with fontTools and brotli, outside the repo's own Python (3.14): python3 -m venv /tmp/fontvenv /tmp/fontvenv/bin/pip install fonttools==4.67.0 brotli==1.2.1 /tmp/fontvenv/bin/python -I scripts/vendor-fonts.py /tmp/fontvenv/bin/python -I scripts/vendor-fonts.py --check --check rebuilds everything into a scratch copy and fails unless every file is byte-identical to the committed one. Run it after any change here, to fonts.json or to sources.json. The output is byte-reproducible. One trap: when uharfbuzz is importable (scripts/harfbuzz-golden.py needs it, and it may share this venv), fontTools serialises GSUB and GPOS with HarfBuzz's repacker instead of its own, and every instanced font and preview comes out different. This script always uses fontTools' own serialiser. Downloads are cached under $DOCS_FONT_CACHE (default /tmp/docs-font-cache), one directory per URL, and checked against internal/fonts/files/SOURCES.lock. A URL that is not in the lock yet is added to it; one whose bytes changed is refused. Licences: a family whose licence reserves its name ("reserved" in the manifest) is vendored from the authors' own static files, unchanged. The woff2 beside it is the same font in a lossless wrapper. Families without a reserved name may be cut from the variable font ("axes"), which the OFL allows. The picker's preview subsets are modified fonts, so they are renamed "Docs Preview NN" and carry no family's name inside them. """ import hashlib import io import json import os import shutil import sys import urllib.request import zipfile from fontTools import subset from fontTools.ttLib import TTFont from fontTools.ttLib.tables import otBase from fontTools.varLib import instancer # fontTools' own GSUB/GPOS serialiser, whether or not uharfbuzz happens to # be installed: the repacker's layout differs, and the output must not # depend on what else is in the venv. otBase.have_uharfbuzz = False ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MANIFEST = os.path.join(ROOT, "internal", "fonts", "fonts.json") SOURCES = os.path.join(ROOT, "internal", "fonts", "sources.json") COMMITTED = os.path.join(ROOT, "internal", "fonts", "files") FILES = COMMITTED LOCK = os.path.join(FILES, "SOURCES.lock") CACHE = os.environ.get("DOCS_FONT_CACHE", "/tmp/docs-font-cache") STYLES = { "regular": (400, False), "bold": (700, False), "italic": (400, True), "boldItalic": (700, True), } def load_lock(): lock = {} if os.path.exists(LOCK): for line in open(LOCK, encoding="utf-8"): line = line.strip() if line and not line.startswith("#"): digest, url = line.split(None, 1) lock[url] = digest return lock def save_lock(lock): with open(LOCK, "w", encoding="utf-8") as f: f.write("# sha256 of every upstream download scripts/vendor-fonts.py uses.\n") for url in sorted(lock): f.write(f"{lock[url]} {url}\n") def fetch(url, lock): key = hashlib.sha256(url.encode()).hexdigest()[:16] d = os.path.join(CACHE, key) path = os.path.join(d, "download") if not os.path.exists(path): os.makedirs(d, exist_ok=True) print(f"fetch {url}", file=sys.stderr) with urllib.request.urlopen(url) as r, open(path + ".part", "wb") as out: shutil.copyfileobj(r, out) os.replace(path + ".part", path) data = open(path, "rb").read() digest = hashlib.sha256(data).hexdigest() if url in lock and lock[url] != digest: sys.exit(f"vendor-fonts: {url} changed upstream ({digest}, locked {lock[url]})") lock[url] = digest return data def source_bytes(src, lock, family_dir): if src.get("inRepo"): return None data = fetch(src["url"], lock) if "member" in src: with zipfile.ZipFile(io.BytesIO(data)) as z: data = z.read(src["member"]) return data def instance(data, axes, italic): font = TTFont(io.BytesIO(data), recalcBBoxes=False, recalcTimestamp=False) if "fvar" not in font: return font pins = {a.axisTag: a.defaultValue for a in font["fvar"].axes} pins.update({k: v for k, v in axes.items() if k in pins}) try: font = instancer.instantiateVariableFont(font, pins, updateFontNames=True) except Exception: font = instancer.instantiateVariableFont(font, pins) weight = axes.get("wght", 400) os2 = font["OS/2"] os2.usWeightClass = weight bold = weight >= 700 sel = os2.fsSelection & ~(0b1100001) # clear ITALIC, BOLD, REGULAR if italic: sel |= 1 if bold: sel |= 1 << 5 if not italic and not bold: sel |= 1 << 6 os2.fsSelection = sel font["head"].macStyle = (1 if bold else 0) | (2 if italic else 0) return font def save(font, path, flavor=None): font.flavor = flavor buf = io.BytesIO() font.save(buf) with open(path, "wb") as f: f.write(buf.getvalue()) return len(buf.getvalue()) def preview(ttf_path, text, index, out): """A name-only subset: the glyphs of the family's own name, kerned.""" font = TTFont(ttf_path, recalcBBoxes=False, recalcTimestamp=False) opts = subset.Options() opts.layout_features = ["kern", "liga", "calt", "ccmp", "locl"] opts.name_IDs = [0, 13, 14] # copyright and licence travel; names are replaced below opts.notdef_outline = True opts.hinting = False s = subset.Subsetter(opts) s.populate(text=text) s.subset(font) name = f"Docs Preview {index:02d}" ps = f"DocsPreview{index:02d}-Regular" table = font["name"] for nid, value in [(1, name), (2, "Regular"), (3, ps), (4, name), (6, ps)]: table.setName(value, nid, 3, 1, 0x409) table.setName(value, nid, 1, 0, 0) save(font, out, "woff2") def main(): manifest = json.load(open(MANIFEST, encoding="utf-8")) sources = json.load(open(SOURCES, encoding="utf-8")) lock = load_lock() total = {"ttf": 0, "woff2": 0, "preview": 0} for index, fam in enumerate(manifest["families"], 1): d = os.path.join(FILES, fam["dir"]) os.makedirs(d, exist_ok=True) src_of = sources[fam["key"]] data = source_bytes(src_of["licence"], lock, d) if data is not None: open(os.path.join(d, fam["licence"]), "wb").write(data) reserved = fam.get("reserved") for style, base in fam["styles"].items(): src = src_of[style] weight, italic = STYLES[style] ttf = os.path.join(d, base + ".ttf") if not src.get("inRepo"): data = source_bytes(src, lock, d) if "axes" in src: if reserved: sys.exit(f"vendor-fonts: {fam['name']} reserves its name; vendor the authors' statics, not an instance") save(instance(data, src["axes"], italic), ttf) else: open(ttf, "wb").write(data) # the authors' file, byte for byte font = TTFont(ttf, recalcBBoxes=False, recalcTimestamp=False) if "glyf" not in font or "fvar" in font: sys.exit(f"vendor-fonts: {ttf} must be a static glyf font") total["ttf"] += os.path.getsize(ttf) total["woff2"] += save(font, os.path.join(d, base + ".woff2"), "woff2") regular = os.path.join(d, fam["styles"]["regular"] + ".ttf") out = os.path.join(d, f"preview-{fam['key']}.woff2") preview(regular, fam["name"], index, out) total["preview"] += os.path.getsize(out) save_lock(lock) for k, v in total.items(): print(f"{k}: {v / 1e6:.2f} MB", file=sys.stderr) def check(): """Rebuild into a scratch copy of files/ and compare byte for byte.""" import filecmp import tempfile global FILES, LOCK with tempfile.TemporaryDirectory() as scratch: FILES = os.path.join(scratch, "files") shutil.copytree(COMMITTED, FILES) LOCK = os.path.join(FILES, "SOURCES.lock") main() differ = [] for dirpath, _, names in os.walk(FILES): for n in names: built = os.path.join(dirpath, n) rel = os.path.relpath(built, FILES) if not filecmp.cmp(built, os.path.join(COMMITTED, rel), shallow=False): differ.append(rel) if differ: sys.exit("vendor-fonts: these differ from the committed files:\n " + "\n ".join(sorted(differ))) print("vendor-fonts: every file matches", file=sys.stderr) if __name__ == "__main__": check() if "--check" in sys.argv[1:] else main()