oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Build internal/fonts/files/ from internal/fonts/fonts.json and sources.json.
3
4For every family and style it writes one static TrueType file (what the
5PDF exporter embeds and the Mac app bundles), one woff2 of exactly that
6file (what the browser loads), and one tiny name-only woff2 for the font
7picker. The woff2 is a lossless wrapper, so the screen and the PDF use
8the same font program.
9
10Run it with fontTools and brotli, outside the repo's own Python (3.14):
11
12 python3 -m venv /tmp/fontvenv
13 /tmp/fontvenv/bin/pip install fonttools==4.67.0 brotli==1.2.1
14 /tmp/fontvenv/bin/python -I scripts/vendor-fonts.py
15 /tmp/fontvenv/bin/python -I scripts/vendor-fonts.py --check
16
17--check rebuilds everything into a scratch copy and fails unless every
18file is byte-identical to the committed one. Run it after any change
19here, to fonts.json or to sources.json.
20
21The output is byte-reproducible. One trap: when uharfbuzz is importable
22(scripts/harfbuzz-golden.py needs it, and it may share this venv),
23fontTools serialises GSUB and GPOS with HarfBuzz's repacker instead of
24its own, and every instanced font and preview comes out different. This
25script always uses fontTools' own serialiser.
26
27Downloads are cached under $DOCS_FONT_CACHE (default /tmp/docs-font-cache),
28one directory per URL, and checked against internal/fonts/files/SOURCES.lock.
29A URL that is not in the lock yet is added to it; one whose bytes changed
30is refused.
31
32Licences: a family whose licence reserves its name ("reserved" in the
33manifest) is vendored from the authors' own static files, unchanged. The
34woff2 beside it is the same font in a lossless wrapper. Families without a
35reserved name may be cut from the variable font ("axes"), which the OFL
36allows. The picker's preview subsets are modified fonts, so they are
37renamed "Docs Preview NN" and carry no family's name inside them.
38"""
39
40import hashlib
41import io
42import json
43import os
44import shutil
45import sys
46import urllib.request
47import zipfile
48
49from fontTools import subset
50from fontTools.ttLib import TTFont
51from fontTools.ttLib.tables import otBase
52from fontTools.varLib import instancer
53
54# fontTools' own GSUB/GPOS serialiser, whether or not uharfbuzz happens to
55# be installed: the repacker's layout differs, and the output must not
56# depend on what else is in the venv.
57otBase.have_uharfbuzz = False
58
59ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
60MANIFEST = os.path.join(ROOT, "internal", "fonts", "fonts.json")
61SOURCES = os.path.join(ROOT, "internal", "fonts", "sources.json")
62COMMITTED = os.path.join(ROOT, "internal", "fonts", "files")
63FILES = COMMITTED
64LOCK = os.path.join(FILES, "SOURCES.lock")
65CACHE = os.environ.get("DOCS_FONT_CACHE", "/tmp/docs-font-cache")
66
67STYLES = {
68 "regular": (400, False),
69 "bold": (700, False),
70 "italic": (400, True),
71 "boldItalic": (700, True),
72}
73
74
75def load_lock():
76 lock = {}
77 if os.path.exists(LOCK):
78 for line in open(LOCK, encoding="utf-8"):
79 line = line.strip()
80 if line and not line.startswith("#"):
81 digest, url = line.split(None, 1)
82 lock[url] = digest
83 return lock
84
85
86def save_lock(lock):
87 with open(LOCK, "w", encoding="utf-8") as f:
88 f.write("# sha256 of every upstream download scripts/vendor-fonts.py uses.\n")
89 for url in sorted(lock):
90 f.write(f"{lock[url]} {url}\n")
91
92
93def fetch(url, lock):
94 key = hashlib.sha256(url.encode()).hexdigest()[:16]
95 d = os.path.join(CACHE, key)
96 path = os.path.join(d, "download")
97 if not os.path.exists(path):
98 os.makedirs(d, exist_ok=True)
99 print(f"fetch {url}", file=sys.stderr)
100 with urllib.request.urlopen(url) as r, open(path + ".part", "wb") as out:
101 shutil.copyfileobj(r, out)
102 os.replace(path + ".part", path)
103 data = open(path, "rb").read()
104 digest = hashlib.sha256(data).hexdigest()
105 if url in lock and lock[url] != digest:
106 sys.exit(f"vendor-fonts: {url} changed upstream ({digest}, locked {lock[url]})")
107 lock[url] = digest
108 return data
109
110
111def source_bytes(src, lock, family_dir):
112 if src.get("inRepo"):
113 return None
114 data = fetch(src["url"], lock)
115 if "member" in src:
116 with zipfile.ZipFile(io.BytesIO(data)) as z:
117 data = z.read(src["member"])
118 return data
119
120
121def instance(data, axes, italic):
122 font = TTFont(io.BytesIO(data), recalcBBoxes=False, recalcTimestamp=False)
123 if "fvar" not in font:
124 return font
125 pins = {a.axisTag: a.defaultValue for a in font["fvar"].axes}
126 pins.update({k: v for k, v in axes.items() if k in pins})
127 try:
128 font = instancer.instantiateVariableFont(font, pins, updateFontNames=True)
129 except Exception:
130 font = instancer.instantiateVariableFont(font, pins)
131 weight = axes.get("wght", 400)
132 os2 = font["OS/2"]
133 os2.usWeightClass = weight
134 bold = weight >= 700
135 sel = os2.fsSelection & ~(0b1100001) # clear ITALIC, BOLD, REGULAR
136 if italic:
137 sel |= 1
138 if bold:
139 sel |= 1 << 5
140 if not italic and not bold:
141 sel |= 1 << 6
142 os2.fsSelection = sel
143 font["head"].macStyle = (1 if bold else 0) | (2 if italic else 0)
144 return font
145
146
147def save(font, path, flavor=None):
148 font.flavor = flavor
149 buf = io.BytesIO()
150 font.save(buf)
151 with open(path, "wb") as f:
152 f.write(buf.getvalue())
153 return len(buf.getvalue())
154
155
156def preview(ttf_path, text, index, out):
157 """A name-only subset: the glyphs of the family's own name, kerned."""
158 font = TTFont(ttf_path, recalcBBoxes=False, recalcTimestamp=False)
159 opts = subset.Options()
160 opts.layout_features = ["kern", "liga", "calt", "ccmp", "locl"]
161 opts.name_IDs = [0, 13, 14] # copyright and licence travel; names are replaced below
162 opts.notdef_outline = True
163 opts.hinting = False
164 s = subset.Subsetter(opts)
165 s.populate(text=text)
166 s.subset(font)
167 name = f"Docs Preview {index:02d}"
168 ps = f"DocsPreview{index:02d}-Regular"
169 table = font["name"]
170 for nid, value in [(1, name), (2, "Regular"), (3, ps), (4, name), (6, ps)]:
171 table.setName(value, nid, 3, 1, 0x409)
172 table.setName(value, nid, 1, 0, 0)
173 save(font, out, "woff2")
174
175
176def main():
177 manifest = json.load(open(MANIFEST, encoding="utf-8"))
178 sources = json.load(open(SOURCES, encoding="utf-8"))
179 lock = load_lock()
180 total = {"ttf": 0, "woff2": 0, "preview": 0}
181 for index, fam in enumerate(manifest["families"], 1):
182 d = os.path.join(FILES, fam["dir"])
183 os.makedirs(d, exist_ok=True)
184 src_of = sources[fam["key"]]
185 data = source_bytes(src_of["licence"], lock, d)
186 if data is not None:
187 open(os.path.join(d, fam["licence"]), "wb").write(data)
188 reserved = fam.get("reserved")
189 for style, base in fam["styles"].items():
190 src = src_of[style]
191 weight, italic = STYLES[style]
192 ttf = os.path.join(d, base + ".ttf")
193 if not src.get("inRepo"):
194 data = source_bytes(src, lock, d)
195 if "axes" in src:
196 if reserved:
197 sys.exit(f"vendor-fonts: {fam['name']} reserves its name; vendor the authors' statics, not an instance")
198 save(instance(data, src["axes"], italic), ttf)
199 else:
200 open(ttf, "wb").write(data) # the authors' file, byte for byte
201 font = TTFont(ttf, recalcBBoxes=False, recalcTimestamp=False)
202 if "glyf" not in font or "fvar" in font:
203 sys.exit(f"vendor-fonts: {ttf} must be a static glyf font")
204 total["ttf"] += os.path.getsize(ttf)
205 total["woff2"] += save(font, os.path.join(d, base + ".woff2"), "woff2")
206 regular = os.path.join(d, fam["styles"]["regular"] + ".ttf")
207 out = os.path.join(d, f"preview-{fam['key']}.woff2")
208 preview(regular, fam["name"], index, out)
209 total["preview"] += os.path.getsize(out)
210 save_lock(lock)
211 for k, v in total.items():
212 print(f"{k}: {v / 1e6:.2f} MB", file=sys.stderr)
213
214
215def check():
216 """Rebuild into a scratch copy of files/ and compare byte for byte."""
217 import filecmp
218 import tempfile
219
220 global FILES, LOCK
221 with tempfile.TemporaryDirectory() as scratch:
222 FILES = os.path.join(scratch, "files")
223 shutil.copytree(COMMITTED, FILES)
224 LOCK = os.path.join(FILES, "SOURCES.lock")
225 main()
226 differ = []
227 for dirpath, _, names in os.walk(FILES):
228 for n in names:
229 built = os.path.join(dirpath, n)
230 rel = os.path.relpath(built, FILES)
231 if not filecmp.cmp(built, os.path.join(COMMITTED, rel), shallow=False):
232 differ.append(rel)
233 if differ:
234 sys.exit("vendor-fonts: these differ from the committed files:\n " + "\n ".join(sorted(differ)))
235 print("vendor-fonts: every file matches", file=sys.stderr)
236
237
238if __name__ == "__main__":
239 check() if "--check" in sys.argv[1:] else main()
240