Repository Public License
1# Font engine (`font`) — compatibility23Package `Packages/EngineFont`, module `EngineFont`, factory `makeEngines()`. The sfnt container, WOFF 1.0 and all4table readers are written in Swift; WOFF2 goes through the bundled google/woff2 1.0.2 + Brotli 1.2.15(`EmbeddedEngines/woff2`, MIT, static, 1.0 MB) behind a five-function C shim (`Sources/CWOFF2Shim`); zlib is the6system's. State on 2026-11-21 (macOS 27.0, arm64): **11 declared paths, 18 tests, all passing**7(`swift test`: `Test run with 18 tests in 3 suites passed`).89## Declared paths1011Every path is `supported`, fidelity `lossless`, preserves metadata and vector geometry.12Test for all of them: `MatrixTests.everyDeclaredPathConvertsAndValidates(path:)`.1314| Source | Destination | Operation | What happens | Limitations shown to the user |15|---|---|---|---|---|16| ttf | woff | — | per-table zlib, checksums and padding per the WOFF 1.0 specification | from a collection, one font is converted; licence notice |17| otf | woff | — | same | same |18| ttf | woff2 | — | Brotli + glyf/loca transform (google/woff2) | glyf/loca re-encoded (identical outlines), DSIG removed; collection → one font; licence notice |19| otf | woff2 | — | Brotli | same |20| woff | ttf | — | tables inflated, sfnt rebuilt | saved as .otf with a notice when the outlines are CFF; WOFF metadata / private blocks not carried over |21| woff | otf | — | same | saved as .ttf with a notice when the outlines are TrueType; same |22| woff2 | ttf | — | google/woff2 decoder | saved as .otf with a notice when CFF; glyf/loca rebuilt; WOFF2 collection → one font |23| woff2 | otf | — | same | saved as .ttf with a notice when TrueType; same |24| woff | woff2 | — | through sfnt | glyf/loca re-encoded, DSIG removed; the WOFF metadata block **is** carried over, the private block is not |25| woff2 | woff | — | through sfnt | WOFF cannot hold a collection; metadata block not carried over |26| ttf | folder | `font.split-collection` | each member of a `.ttc` / `.otc` written as a standalone `.ttf` / `.otf` | shared tables are copied into each file; a single font is refused |2728### The `.ttf` / `.otf` decision2930The extension follows the sfnt version tag, as every loader does: `OTTO` (CFF or CFF2 outlines) → `.otf`, otherwise31`.ttf`. For WOFF / WOFF2 → sfnt the engine writes the file **under the extension that matches the font**, whatever32was asked for, and says so: `preflight` and `convert` raise the caution `font-flavour` ("This font has PostScript33(CFF) outlines: it is saved as .otf, not .ttf…"). Nothing is converted and nothing is refused. The core accepts the34pair (`FormatEquivalence`: `ttf ↔ otf`) and keeps the extension the engine chose through the safe writer. Test:35`MatrixTests.theOtherFlavourIsSavedUnderTheRightExtensionWithANotice`.3637### TTF ↔ OTF outline conversion: not offered3839Converting quadratic `glyf` outlines to cubic `CFF` (or back) means re-encoding every glyph: curve approximation40with an error bound, charstring building and subroutinisation (or `glyf` point building, composite handling), new41`maxp` / `hmtx` / `head` / `post` / `OS/2` values, loss of TrueType hinting or of CFF hints, and variable fonts42(`gvar` ↔ `CFF2` blends) on top. Doing it *correctly end to end, with validated rendering equality* is a project of43its own; it was not attempted, and **neither path is declared**. A rename or re-wrap is never offered as a44conversion: a test asserts that no `ttf → otf` or `otf → ttf` path exists and that asking for one throws45`unsupportedPath`.4647## Licence respect4849`inspect` shows the name-table copyright, trademark, licence text, licence URL, vendor and designer URLs, and the50OS/2 `fsType` embedding permission decoded (Installable / Restricted License / Preview & Print / Editable / no51subsetting / bitmap only, with the raw value). When bit 1 (Restricted License embedding) is set, `preflight` and52`convert` emit the caution `license-restricted`, with an extra sentence when the destination is a web font. The53user decides; nothing is bypassed. **`fsType` is never modified** — the matrix test compares it before and after54every conversion, and `restrictedEmbeddingIsFlaggedAndNeverChanged` runs the whole flow on a system font marked55Restricted (`Ayuthaya.ttf`, fsType 2).5657## Inspection5859Read from the file's own tables, `nil` when a table is absent or damaged: family / style / full / PostScript names,60typographic family and style, version, designer, foundry, vendor ID, copyright, trademark, licence and URLs61(`name`: Windows English preferred, then any Windows or Unicode record, then Macintosh Roman); glyph count (`maxp`);62units per em and revision (`head`, or Apple's `bhed`); weight and width class, embedding permission, vendor63(`OS/2`); italic angle and the fixed-pitch flag (`post` — this is the font's own flag: Monaco, for instance, does not64set it); outline flavour; variation axes with ranges and names, named instances (`fvar`); code points mapped and a65per-Unicode-block summary from the best Unicode `cmap` subtable (formats 12, 4, 6, 0); OpenType feature and script66tags (`GSUB`, `GPOS`); colour tables present (`COLR`, `CPAL`, `SVG`, `sbix`, `CBDT`, `CBLC`, `EBDT`); every table67with its size; for web fonts the container version, announced size, metadata and private block sizes; for68collections the member names. A note lists tables whose declared checksum does not match their bytes.6970Not read: kerning pairs, glyph names from `post`/`CFF` (the glyph browser gets them from Core Graphics), `STAT`,71`avar`, `meta`, `cmap` format 14 variation sequences (so emoji / CJK variation selectors are not counted).7273## Public API for the app7475- `FontFile.open(url)` / `.facts(member:)` / `.sfntData(member:)` — any supported file as sfnt fonts.76- `LoadedFont(url:member:)` — the font loaded in Core Text **from memory** (`CGFont(dataProvider)` +77 `CTFontManagerCreateFontDescriptorsFromData`), never registered with the system.78 - `preview(_:pointSize:scale:foreground:background:variation:)` → `CGImage`: one line, glyphs mapped straight to79 this font (no fallback to system fonts: a missing character shows the font's own `.notdef`), optional variation80 coordinates by axis tag. No shaping: ligatures, kerning, contextual forms and right-to-left ordering are **not**81 applied — it is a specimen, not a text layout.82 - `glyphs(in: Range<Int>)` → `[GlyphInfo]`: index, name, code points (from `cmap`, at most 8), advance in font83 units, outline as `CGPath` in font units.84- `FontPreview.render(url:text:…)` — one call for a preview image.8586## Validation8788For every conversion: the output re-opens with the engine's readers; the outline flavour is unchanged; the table set89is equal (minus `DSIG` through WOFF2); **every table is byte-identical with an equal declared checksum** — except90`head.checkSumAdjustment` (4 bytes that depend on the file layout; recomputed when the rebuilt layout makes the91stored value wrong, with an info warning), and except `glyf` / `loca` / `head` through WOFF2, which WOFF292legitimately re-encodes. Then the independent check: source and output are both loaded in **Core Text**, which must93report the same glyph count and units per em, and **identical outlines and advances** for a sample of glyphs94(every glyph up to 512, otherwise 512 spread over the font plus the first 64); `fvar` axes and instance count must95be equal. One informative line says whether Core Text opens the WOFF / WOFF2 file directly (it does on macOS 27).9697Tests go further than `validate`: `woffRoundTripGivesBackEveryTableByteForByte` (six system fonts; when the source98has the standard layout the round-tripped **file** is byte-identical), `woff2RoundTripKeepsOutlinesMetricsAndAxes`99(every glyph compared, plus a non-default instance of a variable font), `everySystemFontParsesAndSmallOnesRoundTrip100ThroughWOFF` (all 369 font files of `/System/Library/Fonts` and `Supplemental`, 786 fonts counting collection101members, parsed; the 477 fonts in files under 1 MB round-tripped through WOFF with identical tables).102103There is no second WOFF *encoder* on this Mac to make fixtures with: web-font inputs in the tests are produced by104the engine and cross-checked by Core Text's own WOFF / WOFF2 reader.105106## Malformed and hostile input (tested)107108Truncated directory, absurd or zero `numTables`, offsets or lengths outside the file, overlapping tables, a table109overlapping the directory, duplicate tags, impossible collection headers; WOFF: length lies, compressed larger than110uncompressed, tables claiming more than deflate can produce (ratio above 1040:1), tables inflating to more or less111than declared, a 700 MB table hidden in 3 MB (refused before allocating), collections, truncated WOFF2. All throw112`malformedInput` or `limitExceeded`. `mutatedFontsNeverCrash`: 400 mutations each of a TTF, a TTC, a WOFF and a113WOFF2 (header damage, random damage, truncation, 32-bit fields set to extremes), every survivor inspected, rebuilt,114and periodically re-encoded and rendered. Limits: 512 MB per file or decoded font, 1 024 tables, 4 096 fonts per115collection. A font whose tables are nonsense but whose directory is valid parses with empty facts and is refused116by Core Text at preview time.117118## Measured119120Debug build, Apple M5 Max, one run on 2026-11-21 (`MeasurementTests.measureSizesAndTimes`; times include validation):121122| Font | Size | WOFF (zlib 9) | WOFF2 (Brotli 11) | WOFF2 → sfnt |123|---|---|---|---|---|124| Arial Rounded Bold.ttf (glyf) | 49 296 B | 32 028 B, 55 ms | 22 144 B, 82 ms | 18 ms |125| Geneva.ttf (glyf) | 731 672 B | 320 640 B, 89 ms | 209 264 B, 944 ms | 48 ms |126| NotoSerifYezidi-Regular.otf (CFF) | 8 664 B | 5 560 B, 5 ms | 4 852 B, 12 ms | 3 ms |127| SFHebrew.ttf (variable) | 62 376 B | 32 504 B, 11 ms | 26 912 B, 86 ms | 8 ms |128129Brotli quality 11 costs roughly 1 s per MB of font; the `quality` option trades size for speed. Memory was not130measured; a font is held in memory decoded (bounded by the 512 MB limit).131132## Evaluated and not implemented133134- TTF ↔ OTF outline conversion (see above).135- Writing a **collection**: WOFF2 can hold one and the bundled encoder accepts TTC input, but the engine converts136 one member at a time (option `collection.index`); merging fonts into a `.ttc` is not offered.137- Subsetting, hinting changes, renaming, instancing a variable font to a static one, `name`-table editing.138- Carrying WOFF2 extended metadata to WOFF or to sfnt (the bundled decoder does not expose it): reported as dropped.139- EOT, Type 1 (`.pfb`), bitmap `.dfont` / suitcase fonts: not read. An sfnt with the `typ1` tag is parsed as a140 container but nothing more is promised.141- 53 of the 369 system font files declare a table checksum that does not match (Apple ships them that way); the142 engine keeps declared checksums as they are and says so in an info warning rather than "repairing" a font.143