Repository navigation
feat(core): font files read without a browser: widths, kerning, ligatures, line metrics, subsets - #54
Conversation
…ures, line metrics, subsets src/core/font reads TTF, OTF (CFF, also CID-keyed), TTC, WOFF and WOFF2 files with no DOM and no dependency, for a layout that breaks lines the same everywhere (#30) and for PDF output (#44): - Font: character map, glyph widths, metrics, line metrics as browsers and as Word take them, names, what the font says about itself; - layoutText: a run of text as glyphs, with GPOS pair and single adjustments (else the kern table) and the single, multiple and ligature substitutions browsers apply by themselves, text cut where its script changes. What is not applied (contextual rules, marks, Apple's tables, scripts that need shaping) is detected: the run then has exact false and the reason, or is handed to the host's Shaper; - FontBook: the FontSource list of DocViewer's fonts, the file for a text chosen as CSS chooses (family list, style, weight, unicode-range, each character in the first file that has it), fetched when first asked for; - subsetFont and toUnicodeCMap: the glyphs used, renumbered, as a font file of its own (TrueType, or CFF as OTF and as the bare table), and the text of each glyph for a PDF; - in the worker: fonts.set, fonts.measure, the font:error event. WOFF2 is unpacked by the runtime's DecompressionStream('brotli'): Node, Bun and Firefox have it, Chromium 156 does not and is told so in words. Checked against HarfBuzz on 796 font faces (scripts/font-check.ts): of 10,094 runs called exact none differs; 997 subsets have their font's widths and draw the same picture. Fixes #45 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
mkroemer
left a comment
There was a problem hiding this comment.
I read through this with #30's exact layout and the server use from my note on #39 in mind, since I'll be building on both. Really nice work, and the HarfBuzz comparison across 796 faces is impressive.
Most of what I found is about the "never exact by accident" promise: a few cases come back exact: true when they aren't, plus two crashes. I'd suggest fixing those before merging; the rest could easily be follow-ups. Your call, of course.
Before merging, I'd suggest
1. Some variable fonts are reported exact with the wrong widths (src/core/font/book.ts:228)
The variable flag is only set when the face is declared with a weight range (f.face.max > f.face.min). A variable font declared with one weight, or with none (so 400), is drawn by the browser at the requested weight, but here it's measured at the font's default instance. For example, Source Sans 3 VF with no weight declared is measured as ExtraLight 200, with exact: true and nothing in unsure. I think the range check can go: f.font.variable && weight !== f.font.weight.
2. Whole scripts are classed as Zinh (src/core/font/text.ts:172)
0x10800–0x10fff, 0x11000–0x11fff and 0x1e800–0x1efff include Adlam, Brahmi, Kharoshthi and others, so their letters join the previous segment. "Name: 𞤀𞤣𞤤𞤢𞤥" goes to the shaper as Latn / ltr and comes back exact. Also, a Zinh character's rtl is only used when it starts a segment; when it joins cur, rtl isn't updated, despite the comment.
3. letterSpacing is added per glyph rather than per character (src/core/font/text.ts:331)
advances[i] + spacing also applies to zero-advance marks and to every glyph a ccmp decomposition or shaper cluster produces. Browsers add it once per character and never to marks. Could you check "café" with a shaper? I'd expect the acute to be pushed off the e and the width to be one spacing too wide, while the run still says exact.
4. Spreading glyph arrays can throw a RangeError (src/core/font/text.ts:317)
ids.splice(0, ids.length, ...before[0]) (and ...laid[0]) passes a whole segment's glyphs as arguments. Past ~65k glyphs on Bun / JSC (~120k on V8) this throws when substitution fails. container.ts:380 already avoids this. Something like ids.length = 0; for (const g of before[0]) ids.push(g) is enough.
5. A bad src throws synchronously out of fonts.set (src/core/worker/client.ts:127)
direct() isn't async, so new URL(f.src, document.baseURI) throws before a promise exists. .catch never runs, and none of the fonts are set. Could a bad entry be passed through so it fires font:error for that face only?
Also worth fixing
6. measure() re-reads this.fonts on each await (src/core/worker/engine.ts:286)
fonts.set isn't in WRITES, so if it arrives mid-batch, later texts in the same fonts.measure call use the new FontBook. Taking const book = this.fonts before the loop fixes it.
7. There's no public way to set Engine.shaper (src/core/worker/engine.ts:279)
The docs say to use it with worker: false, but DocumentClient keeps its engine private, and the shaper is only read when fonts.set builds the FontBook. Unless I'm missing a path, Arabic and Indic text always comes back unsure: ['shaping']. Maybe a shaper option on DocumentClient.open?
Follow-ups (fine as separate PRs)
8. faces() fetches before it knows what the text needs (src/core/font/book.ts:190)
It downloads and parses, one after another, every file of the best style and weight in every family of the stack, ignoring unicodeRange. A CJK font split into ~120 subsets is fully downloaded to measure "Hello", and every unused file that fails fires font:error. This contradicts "fetched when text first asks for them" in the docs. If it stays as is for now, please adjust the docs.
9. Invisible characters reuse the space glyph (src/core/font/text.ts:338)
Soft hyphen, ZWSP, word joiner and BOM go back in as glyphOf(0x20). With the toUnicodeCMap(new Map(...)) recipe in docs/api.md, the last mapping wins, so I'd expect real spaces in the PDF to copy and search as . Glyph 0 (.notdef) or a separate entry might avoid it.
10. The CFF subset doesn't follow seac (src/core/font/subset.ts:334)
The TrueType path keeps composite parts, but in the CFF path, endchar with four arguments (base + accent) loses its referenced glyphs. Type 1–derived CFF fonts draw accented letters this way, so é would draw nothing or the wrong glyphs in the subset. Worth a test with such a font.
…r one weight, a bad address in fonts.set, long runs From the review of #54: - a variable font declared for one weight (or for none: 400) was measured at the weight of its tables and called exact, though a browser sets it at the declared weight. The weight asked for, kept within the declared ones, is now compared with the tables' own: `variable` when they differ; - `fonts.set` threw at the call, with no promise to catch, when a `src` was not an address, and set none of the fonts. Such a `src` now crosses as written: its file fails alone, with `font:error`, when text first asks for it; - a run of more glyphs than a call takes arguments (some 120,000 in V8) threw a RangeError when a rule of its font is not applied here: the glyphs are put back in a loop, not spread into `splice`. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Fixes #45.
src/core/font: font files read with no DOM and no dependency, exported from@p10node/office-engine/coreand reachable in the worker. It is the shared base of #30'sexactlayout and of PDF output (#44); the viewer itself does not use it yet.What is in
Font.open(): TTF, OTF (CFF, also CID-keyed), TTC by index, WOFF, WOFF2 (with its rewrittenglyf/loca/hmtx)cmap,hmtx,hhea/OS/2glyphOf,advanceOf,metrics,lineMetrics()(as browsers) andlineMetrics('word')(Windows values: Word's single spacing)kern, pair kerning ofGPOSkerntable when GPOS has no kerning, as HarfBuzzliga,clig,ccmp,locl,rlig,calt,rclt)FontSourceFontBook: bytes, Blobs or URLs, fetched when text first asks for themcssFont()unicodeRange, each character in the first file that has itsubsetFont()(TrueType with the parts of composites; CFF with its charstrings and subroutines, as OTF and as the bare table),toUnicodeCMap()exactand the reasons it is not:font,missing,shaping,features,kerning,synthetic,variableshaperoptionShaperas proposed (scriptis an ISO 15924 code); called for text that needs shaping, and for runs a font rule not applied here would changeIn the worker:
fonts.set(fonts),fonts.measure(texts), eventfont:error. No document has to be open, so a server can use anEnginefor it.DocumentClientresolves font URLs against the page before they cross to the worker.Never exact by accident
What is not applied is detected instead of ignored. Contextual lookups are matched (not applied); mark attachment, cursive joining, Apple's
morx/kerx/trakand a rule table that is damaged or too long are known by their presence. A run they would change is laid out without them and hasexact: false. Text is cut where its script changes before it is laid out, as browsers do.Checked against
hb-shape), 796 font faces, 9 texts, kerning / ligatures on and offhb-viewpictures), same 796 facese2e/font-read.spec.ts)FontErroror a font, nothing elseThe 796 faces are the fonts of a Mac and of the test VM: Liberation, DejaVu, FreeFont, TLWG (CFF), the macOS fonts (TTC, CID-keyed CFF, variable ones at their default instance). None is in the repository:
scripts/font-check.tsrepeats the first two rows on any fonts. Unit tests (test/font-read.test.ts, 35 tests) use fonts written bytest/font-tables.ts; the one binary fixture is a 732-byte WOFF2 of that generated font.Speed: a 22 MB font opens in 2 ms, text is laid out at about 1 µs per character. The worker bundle is about 34 KB larger (13 KB gzipped).
Decided
DecompressionStream('brotli'): Node 26, Bun 1.4 and Firefox 157 have it, Chromium 156 does not. There a WOFF2 file is refused with a message that says so and its text is reported as without a file. For text that has to be measured in Chrome, declare TTF, OTF or WOFF files (documented).engine.shapercovers a server andworker: false.Not in this change
variableotherwise).kerning: false/ligatures: falsefrom the run properties.🤖 Generated with Claude Code