SPB Git

Repository Public License

font.md 10.6 KB

# Font engine (font) — compatibility

Package Packages/EngineFont, module EngineFont, factory makeEngines(). The sfnt container, WOFF 1.0 and all table readers are written in Swift; WOFF2 goes through the bundled google/woff2 1.0.2 + Brotli 1.2.1 (EmbeddedEngines/woff2, MIT, static, 1.0 MB) behind a five-function C shim (Sources/CWOFF2Shim); zlib is the system's. State on 2026-11-21 (macOS 27.0, arm64): 11 declared paths, 18 tests, all passing (swift test: Test run with 18 tests in 3 suites passed).

# Declared paths

Every path is supported, fidelity lossless, preserves metadata and vector geometry. Test for all of them: MatrixTests.everyDeclaredPathConvertsAndValidates(path:).

Source Destination Operation What happens Limitations shown to the user
ttf woff — per-table zlib, checksums and padding per the WOFF 1.0 specification from a collection, one font is converted; licence notice
otf woff — same same
ttf woff2 — Brotli + glyf/loca transform (google/woff2) glyf/loca re-encoded (identical outlines), DSIG removed; collection → one font; licence notice
otf woff2 — Brotli same
woff ttf — tables inflated, sfnt rebuilt saved as .otf with a notice when the outlines are CFF; WOFF metadata / private blocks not carried over
woff otf — same saved as .ttf with a notice when the outlines are TrueType; same
woff2 ttf — google/woff2 decoder saved as .otf with a notice when CFF; glyf/loca rebuilt; WOFF2 collection → one font
woff2 otf — same saved as .ttf with a notice when TrueType; same
woff woff2 — through sfnt glyf/loca re-encoded, DSIG removed; the WOFF metadata block is carried over, the private block is not
woff2 woff — through sfnt WOFF cannot hold a collection; metadata block not carried over
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

# The .ttf / .otf decision

The extension follows the sfnt version tag, as every loader does: OTTO (CFF or CFF2 outlines) → .otf, otherwise .ttf. For WOFF / WOFF2 → sfnt the engine writes the file under the extension that matches the font, whatever was asked for, and says so: preflight and convert raise the caution font-flavour ("This font has PostScript (CFF) outlines: it is saved as .otf, not .ttf…"). Nothing is converted and nothing is refused. The core accepts the pair (FormatEquivalence: ttf ↔ otf) and keeps the extension the engine chose through the safe writer. Test: MatrixTests.theOtherFlavourIsSavedUnderTheRightExtensionWithANotice.

# TTF ↔ OTF outline conversion: not offered

Converting quadratic glyf outlines to cubic CFF (or back) means re-encoding every glyph: curve approximation with an error bound, charstring building and subroutinisation (or glyf point building, composite handling), new maxp / hmtx / head / post / OS/2 values, loss of TrueType hinting or of CFF hints, and variable fonts (gvar ↔ CFF2 blends) on top. Doing it correctly end to end, with validated rendering equality is a project of its own; it was not attempted, and neither path is declared. A rename or re-wrap is never offered as a conversion: a test asserts that no ttf → otf or otf → ttf path exists and that asking for one throws unsupportedPath.

# Licence respect

inspect shows the name-table copyright, trademark, licence text, licence URL, vendor and designer URLs, and the OS/2 fsType embedding permission decoded (Installable / Restricted License / Preview & Print / Editable / no subsetting / bitmap only, with the raw value). When bit 1 (Restricted License embedding) is set, preflight and convert emit the caution license-restricted, with an extra sentence when the destination is a web font. The user decides; nothing is bypassed. fsType is never modified — the matrix test compares it before and after every conversion, and restrictedEmbeddingIsFlaggedAndNeverChanged runs the whole flow on a system font marked Restricted (Ayuthaya.ttf, fsType 2).

# Inspection

Read from the file's own tables, nil when a table is absent or damaged: family / style / full / PostScript names, typographic family and style, version, designer, foundry, vendor ID, copyright, trademark, licence and URLs (name: Windows English preferred, then any Windows or Unicode record, then Macintosh Roman); glyph count (maxp); units per em and revision (head, or Apple's bhed); weight and width class, embedding permission, vendor (OS/2); italic angle and the fixed-pitch flag (post — this is the font's own flag: Monaco, for instance, does not set it); outline flavour; variation axes with ranges and names, named instances (fvar); code points mapped and a per-Unicode-block summary from the best Unicode cmap subtable (formats 12, 4, 6, 0); OpenType feature and script tags (GSUB, GPOS); colour tables present (COLR, CPAL, SVG, sbix, CBDT, CBLC, EBDT); every table with its size; for web fonts the container version, announced size, metadata and private block sizes; for collections the member names. A note lists tables whose declared checksum does not match their bytes.

Not read: kerning pairs, glyph names from post/CFF (the glyph browser gets them from Core Graphics), STAT, avar, meta, cmap format 14 variation sequences (so emoji / CJK variation selectors are not counted).

# Public API for the app

  • FontFile.open(url) / .facts(member:) / .sfntData(member:) — any supported file as sfnt fonts.
  • LoadedFont(url:member:) — the font loaded in Core Text from memory (CGFont(dataProvider) + CTFontManagerCreateFontDescriptorsFromData), never registered with the system.
    • preview(_:pointSize:scale:foreground:background:variation:) → CGImage: one line, glyphs mapped straight to this font (no fallback to system fonts: a missing character shows the font's own .notdef), optional variation coordinates by axis tag. No shaping: ligatures, kerning, contextual forms and right-to-left ordering are not applied — it is a specimen, not a text layout.
    • glyphs(in: Range<Int>) → [GlyphInfo]: index, name, code points (from cmap, at most 8), advance in font units, outline as CGPath in font units.
  • FontPreview.render(url:text:…) — one call for a preview image.

# Validation

For every conversion: the output re-opens with the engine's readers; the outline flavour is unchanged; the table set is equal (minus DSIG through WOFF2); every table is byte-identical with an equal declared checksum — except head.checkSumAdjustment (4 bytes that depend on the file layout; recomputed when the rebuilt layout makes the stored value wrong, with an info warning), and except glyf / loca / head through WOFF2, which WOFF2 legitimately re-encodes. Then the independent check: source and output are both loaded in Core Text, which must report the same glyph count and units per em, and identical outlines and advances for a sample of glyphs (every glyph up to 512, otherwise 512 spread over the font plus the first 64); fvar axes and instance count must be equal. One informative line says whether Core Text opens the WOFF / WOFF2 file directly (it does on macOS 27).

Tests go further than validate: woffRoundTripGivesBackEveryTableByteForByte (six system fonts; when the source has the standard layout the round-tripped file is byte-identical), woff2RoundTripKeepsOutlinesMetricsAndAxes (every glyph compared, plus a non-default instance of a variable font), everySystemFontParsesAndSmallOnesRoundTrip ThroughWOFF (all 369 font files of /System/Library/Fonts and Supplemental, 786 fonts counting collection members, parsed; the 477 fonts in files under 1 MB round-tripped through WOFF with identical tables).

There is no second WOFF encoder on this Mac to make fixtures with: web-font inputs in the tests are produced by the engine and cross-checked by Core Text's own WOFF / WOFF2 reader.

# Malformed and hostile input (tested)

Truncated directory, absurd or zero numTables, offsets or lengths outside the file, overlapping tables, a table overlapping the directory, duplicate tags, impossible collection headers; WOFF: length lies, compressed larger than uncompressed, tables claiming more than deflate can produce (ratio above 1040:1), tables inflating to more or less than declared, a 700 MB table hidden in 3 MB (refused before allocating), collections, truncated WOFF2. All throw malformedInput or limitExceeded. mutatedFontsNeverCrash: 400 mutations each of a TTF, a TTC, a WOFF and a WOFF2 (header damage, random damage, truncation, 32-bit fields set to extremes), every survivor inspected, rebuilt, and periodically re-encoded and rendered. Limits: 512 MB per file or decoded font, 1 024 tables, 4 096 fonts per collection. A font whose tables are nonsense but whose directory is valid parses with empty facts and is refused by Core Text at preview time.

# Measured

Debug build, Apple M5 Max, one run on 2026-11-21 (MeasurementTests.measureSizesAndTimes; times include validation):

Font Size WOFF (zlib 9) WOFF2 (Brotli 11) WOFF2 → sfnt
Arial Rounded Bold.ttf (glyf) 49 296 B 32 028 B, 55 ms 22 144 B, 82 ms 18 ms
Geneva.ttf (glyf) 731 672 B 320 640 B, 89 ms 209 264 B, 944 ms 48 ms
NotoSerifYezidi-Regular.otf (CFF) 8 664 B 5 560 B, 5 ms 4 852 B, 12 ms 3 ms
SFHebrew.ttf (variable) 62 376 B 32 504 B, 11 ms 26 912 B, 86 ms 8 ms

Brotli quality 11 costs roughly 1 s per MB of font; the quality option trades size for speed. Memory was not measured; a font is held in memory decoded (bounded by the 512 MB limit).

# Evaluated and not implemented

  • TTF ↔ OTF outline conversion (see above).
  • Writing a collection: WOFF2 can hold one and the bundled encoder accepts TTC input, but the engine converts one member at a time (option collection.index); merging fonts into a .ttc is not offered.
  • Subsetting, hinting changes, renaming, instancing a variable font to a static one, name-table editing.
  • Carrying WOFF2 extended metadata to WOFF or to sfnt (the bundled decoder does not expose it): reported as dropped.
  • EOT, Type 1 (.pfb), bitmap .dfont / suitcase fonts: not read. An sfnt with the typ1 tag is parsed as a container but nothing more is promised.
  • 53 of the 369 system font files declare a table checksum that does not match (Apple ships them that way); the engine keeps declared checksums as they are and says so in an info warning rather than "repairing" a font.
Files main
Menu

Theme