Repository Public License
1// ORIX Convert — Packages/EngineFont/Tests/EngineFontTests/MatrixTests.swift2// Description: One conversion per declared path of the font engine, round-trips (byte-identical tables through WOFF,3// outline-identical through WOFF2), variable fonts, collections, inspection and the Core Text API.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import ConvertCore6import CoreGraphics7import CoreText8@testable import EngineFont9import Foundation10import Testing1112@Suite struct MatrixTests {13 static let engine = FontEngine()14 static let allPaths = engine.paths1516 /// Builds the input a path needs. Web-font inputs are produced from a system font by the engine's own encoder17 /// (no other WOFF encoder exists on this Mac); the decoders are then cross-checked against Core Text.18 static func input(for path: ConversionPath, in scratch: Scratch) async throws -> URL {19 let wantsCFF = path.source == .otf || path.destination == .otf20 let base = try scratch.fixture(path.operation != nil ? .collection : wantsCFF ? .cff : .glyf)21 switch path.source {22 case .woff: return try await convert(base, wantsCFF ? .otf : .ttf, .woff, in: scratch).url23 case .woff2: return try await convert(base, wantsCFF ? .otf : .ttf, .woff2, in: scratch).url24 default: return base25 }26 }2728 @Test func declaresElevenPathsAndNoOutlineConversion() {29 #expect(Self.allPaths.count == 11 && Set(Self.allPaths.map(\.id)).count == 11)30 // A rename is not a conversion: TTF ↔ OTF is never offered.31 #expect(!Self.allPaths.contains { ($0.source == .ttf && $0.destination == .otf) || ($0.source == .otf && $0.destination == .ttf) })32 #expect(Self.allPaths.allSatisfy { $0.fidelity == .lossless && !$0.limitations.isEmpty && $0.status == .supported })33 }3435 @Test(arguments: allPaths)36 func everyDeclaredPathConvertsAndValidates(path: ConversionPath) async throws {37 let scratch = try Scratch(); defer { scratch.cleanUp() }38 let source = try await Self.input(for: path, in: scratch)39 let result = try await convert(source, path.source, path.destination, operation: path.operation, in: scratch)40 expectAllPass(result.checks, path.id)41 #expect(result.checks.count >= 5)42 if path.destination != .folder {43 #expect(FileTypeDetector.detect(result.url).format == path.destination)44 // Independent of the engine's validation: same glyph count and names as the system font it came from.45 let original = try LoadedFont(url: try scratch.fixture(path.source == .otf || path.destination == .otf ? .cff : .glyf))46 let converted = try LoadedFont(url: result.url)47 #expect(converted.glyphCount == original.glyphCount && converted.facts.postScriptName == original.facts.postScriptName)48 #expect(converted.facts.embedding == original.facts.embedding) // fsType is never touched49 #expect(result.collector.progress.last == .some(1))50 }51 let descriptors = Self.engine.options(for: path)52 #expect(Set(descriptors.map(\.id)).count == descriptors.count)53 }5455 @Test(arguments: [SystemFont.glyf, .geneva, .cff, .cffText, .variable, .restricted])56 func woffRoundTripGivesBackEveryTableByteForByte(font: SystemFont) async throws {57 let scratch = try Scratch(); defer { scratch.cleanUp() }58 let source = try scratch.fixture(font)59 let woff = try await convert(source, font.format, .woff, in: scratch)60 expectAllPass(woff.checks, "to WOFF")61 let back = try await convert(woff.url, .woff, font.format, in: scratch)62 expectAllPass(back.checks, "from WOFF")63 let a = try FontFile.open(source).fonts[0], b = try FontFile.open(back.url).fonts[0]64 #expect(a.tables.map(\.tag) == b.tables.map(\.tag))65 for (x, y) in zip(a.tables, b.tables) {66 #expect(x.checksum == y.checksum, "\(x.tag) checksum")67 if x.tag != FontTag("head") { #expect(x.data == y.data, "\(x.tag) bytes") }68 }69 // A font laid out the standard way comes back as the very same file.70 let original = try Data(contentsOf: source)71 if SFNT.build(a).data == original { #expect(back.data == original, "whole file identical") }72 // WOFF structure: header fields, 4-byte alignment, totalSfntSize.73 let w = ByteReader(woff.data)74 #expect(w.u32(0) == 0x774F_4646 && Int(w.u32(8) ?? 0) == woff.data.count && w.u16(14) == 0)75 #expect(Int(w.u32(16) ?? 0) == 12 + a.tables.count * 16 + a.tables.reduce(0) { $0 + ($1.length + 3) & ~3 })76 for i in 0..<a.tables.count { #expect((w.u32(44 + i * 20 + 4) ?? 1) % 4 == 0) }77 #expect(woff.data.count < original.count)78 }7980 @Test func rebuiltSystemFontsAreByteIdenticalWhenTheirLayoutIsStandard() throws {81 // How many of the single-font fixtures the builder reproduces exactly (proves the checksum and layout code).82 var identical = 083 for font in [SystemFont.glyf, .geneva, .cff, .cffText, .variable, .restricted] {84 let data = try Data(contentsOf: font.url)85 let parsed = try SFNT.parse(data)[0]86 let rebuilt = SFNT.build(parsed)87 if rebuilt.data == data { identical += 1; #expect(!rebuilt.headAdjusted) }88 #expect(FontEngine.tablesEqual(try SFNT.parse(rebuilt.data)[0], parsed, except: []))89 }90 #expect(identical >= 3, "only \(identical) of 6 fixtures rebuilt identically")91 }9293 @Test(arguments: [SystemFont.glyf, .cff, .cffText, .variable])94 func woff2RoundTripKeepsOutlinesMetricsAndAxes(font: SystemFont) async throws {95 let scratch = try Scratch(); defer { scratch.cleanUp() }96 let source = try scratch.fixture(font)97 let woff2 = try await convert(source, font.format, .woff2, in: scratch)98 expectAllPass(woff2.checks, "to WOFF2")99 let back = try await convert(woff2.url, .woff2, font.format, in: scratch)100 expectAllPass(back.checks, "from WOFF2")101 let a = try LoadedFont(url: source), b = try LoadedFont(url: back.url)102 // Every glyph, not a sample.103 let cmp = OutlineComparison.compare(a, b, sample: 1_000_000)104 #expect(cmp.compared >= a.glyphCount && cmp.outlineDifferences == 0 && cmp.advanceDifferences == 0)105 #expect(a.facts.axes == b.facts.axes && a.facts.instances == b.facts.instances)106 #expect(a.facts.features == b.facts.features && a.facts.codePointCount == b.facts.codePointCount)107 #expect(woff2.data.count < (try Data(contentsOf: source)).count)108 if font == .glyf { #expect(woff2.collector.has("dsig-removed")) }109 if font == .variable {110 #expect(!a.facts.axes.isEmpty)111 // A non-default instance renders the same after the round trip.112 let axis = try #require(a.facts.axes.first)113 let va = a.ctFont(size: 1000, variation: [axis.tag: axis.maximum]), vb = b.ctFont(size: 1000, variation: [axis.tag: axis.maximum])114 var different = 0115 for g in stride(from: 0, to: a.glyphCount, by: 3) {116 if OutlineComparison.signature(CTFontCreatePathForGlyph(va, CGGlyph(g), nil)) != OutlineComparison.signature(CTFontCreatePathForGlyph(vb, CGGlyph(g), nil)) { different += 1 }117 }118 #expect(different == 0)119 // And the instance really differs from the default one (the axis is live).120 let d = a.ctFont(size: 1000)121 #expect((0..<a.glyphCount).contains { OutlineComparison.signature(CTFontCreatePathForGlyph(va, CGGlyph($0), nil)) != OutlineComparison.signature(CTFontCreatePathForGlyph(d, CGGlyph($0), nil)) })122 }123 }124125 @Test func woffToWoff2AndBackThroughSfnt() async throws {126 let scratch = try Scratch(); defer { scratch.cleanUp() }127 let source = try scratch.fixture(.geneva)128 let woff = try await convert(source, .ttf, .woff, options: ["compression.level": .int(1)], in: scratch)129 let best = try await convert(source, .ttf, .woff, options: ["compression.level": .int(9)], in: scratch)130 #expect(best.data.count <= woff.data.count)131 let woff2 = try await convert(woff.url, .woff, .woff2, options: ["quality": .int(5)], in: scratch)132 expectAllPass(woff2.checks, "woff→woff2")133 let again = try await convert(woff2.url, .woff2, .woff, in: scratch)134 expectAllPass(again.checks, "woff2→woff")135 let cmp = OutlineComparison.compare(try LoadedFont(url: source), try LoadedFont(url: again.url), sample: 1_000_000)136 #expect(cmp.outlineDifferences == 0 && cmp.advanceDifferences == 0 && cmp.compared > 100)137 let untransformed = try await convert(source, .ttf, .woff2, options: ["quality": .int(5), "woff2.transform": .bool(false)], in: scratch)138 expectAllPass(untransformed.checks, "no transform")139 }140141 @Test func theOtherFlavourIsSavedUnderTheRightExtensionWithANotice() async throws {142 let scratch = try Scratch(); defer { scratch.cleanUp() }143 // CFF outlines asked as .ttf: delivered as .otf, said before (preflight) and during the conversion.144 let cffWoff = try await convert(try scratch.fixture(.cff), .otf, .woff, in: scratch)145 let request = ConversionRequest(source: cffWoff.url, sourceFormat: .woff, destinationFormat: .ttf)146 let notice = try #require(Self.engine.preflight(request, inspection: nil).first { $0.code == "font-flavour" })147 #expect(notice.severity == .caution && notice.message.contains("saved as .otf") && notice.message.contains("PostScript (CFF)"))148 let asked = try await convert(cffWoff.url, .woff, .ttf, in: scratch)149 expectAllPass(asked.checks, "woff (CFF) → ttf")150 #expect(asked.url.pathExtension == "otf" && FileTypeDetector.detect(asked.url).format == .otf && !FileTypeDetector.detect(asked.url).mismatch)151 #expect(asked.collector.warnings.contains { $0.code == "font-flavour" })152 // The core's generic check accepts the pair (FormatEquivalence ttf ↔ otf).153 #expect(OutputValidator.validate(ConversionOutput(file: asked.url), destinationFormat: .ttf, workDirectory: asked.url.deletingLastPathComponent()).allSatisfy { $0.passed })154 // TrueType outlines asked as .otf: delivered as .ttf.155 let glyfWoff2 = try await convert(try scratch.fixture(.glyf), .ttf, .woff2, options: ["quality": .int(3)], in: scratch)156 let other = try await convert(glyfWoff2.url, .woff2, .otf, in: scratch)157 expectAllPass(other.checks, "woff2 (glyf) → otf")158 #expect(other.url.pathExtension == "ttf" && other.collector.warnings.contains { $0.code == "font-flavour" && $0.message.contains("saved as .ttf") })159 // The matching request raises no notice.160 let natural = try await convert(cffWoff.url, .woff, .otf, in: scratch)161 #expect(natural.url.pathExtension == "otf" && !natural.collector.warnings.contains { $0.code == "font-flavour" })162 // Outline conversion itself is still not a path.163 await #expect(throws: ConversionError.unsupportedPath(source: .ttf, destination: .otf)) {164 _ = try await Self.engine.convert(.init(source: try scratch.fixture(.glyf), sourceFormat: .ttf, destinationFormat: .otf), context: .init(workDirectory: try scratch.work()))165 }166 }167168 @Test func collectionsSplitAndConvertOneMember() async throws {169 let scratch = try Scratch(); defer { scratch.cleanUp() }170 let ttc = try scratch.fixture(.futura)171 let file = try FontFile.open(ttc)172 #expect(file.fonts.count == 5 && file.container == .collection)173 let split = try await convert(ttc, .ttf, .folder, operation: FontEngine.splitOperation, in: scratch)174 expectAllPass(split.checks, "split")175 let members = try FileManager.default.contentsOfDirectory(at: split.url, includingPropertiesForKeys: nil)176 #expect(members.count == 5 && members.allSatisfy { $0.pathExtension == "ttf" })177 let names = Set(try members.map { try #require(try LoadedFont(url: $0).facts.postScriptName) })178 #expect(names == Set(try (0..<5).map { try #require(try file.facts(member: $0).postScriptName) }) && names.count == 5)179 // Converting a collection takes one member and says so.180 let third = try await convert(ttc, .ttf, .woff2, options: ["collection.index": .int(3), "quality": .int(4)], in: scratch)181 expectAllPass(third.checks, "member 3")182 #expect(third.collector.has("collection-member"))183 #expect(try LoadedFont(url: third.url).facts.postScriptName == (try file.facts(member: 2).postScriptName))184 await #expect(throws: ConversionError.self) { _ = try await convert(ttc, .ttf, .woff, options: ["collection.index": .int(6)], in: scratch) }185 await #expect(throws: ConversionError.self) { _ = try await convert(try scratch.fixture(.glyf), .ttf, .folder, operation: FontEngine.splitOperation, in: scratch) }186 }187188 @Test func restrictedEmbeddingIsFlaggedAndNeverChanged() async throws {189 let scratch = try Scratch(); defer { scratch.cleanUp() }190 let source = try scratch.fixture(.restricted)191 let request = ConversionRequest(source: source, sourceFormat: .ttf, destinationFormat: .woff2, options: ConversionOptions(["quality": .int(2)]))192 let warning = try #require(Self.engine.preflight(request, inspection: nil).first { $0.code == "license-restricted" })193 #expect(warning.severity == .caution && warning.message.contains("Restricted License") && warning.message.contains("web font"))194 let out = try await convert(source, .ttf, .woff2, options: ["quality": .int(2)], in: scratch)195 #expect(out.collector.has("license-restricted"))196 expectAllPass(out.checks, "restricted")197 let before = try #require(try FontFile.open(source).facts().embedding), after = try #require(try FontFile.open(out.url).facts().embedding)198 #expect(before.rawValue == 2 && after.rawValue == 2 && before.isRestricted)199 // An installable font raises nothing.200 #expect(!Self.engine.preflight(.init(source: try scratch.fixture(.cff), sourceFormat: .otf, destinationFormat: .woff), inspection: nil).contains { $0.code.hasPrefix("license") })201 let i = try await Self.engine.inspect(source, format: .ttf)202 #expect(i.fields.contains { $0.key == "Embedding permission" && $0.value.hasPrefix("Restricted License embedding") && $0.value.hasSuffix("(fsType 0x0002)") })203 }204205 @Test func inspectReadsTheFontsOwnTables() async throws {206 let scratch = try Scratch(); defer { scratch.cleanUp() }207 func fields(_ font: SystemFont) async throws -> [String: String] {208 let i = try await Self.engine.inspect(try scratch.fixture(font), format: font.format)209 return Dictionary(i.fields.map { ($0.key, $0.value) }, uniquingKeysWith: { a, _ in a })210 }211 let arial = try await fields(.glyf)212 #expect(arial["Family"] == "Arial Rounded MT Bold" && arial["PostScript name"] == "ArialRoundedMTBold" && arial["Outlines"] == "TrueType (glyf)")213 #expect(arial["Units per em"] == "2048" && arial["Natural extension"] == ".ttf" && arial["Monospaced"] == "no")214 #expect(arial["Copyright"]?.isEmpty == false && arial["Embedding permission"]?.hasPrefix("Editable embedding") == true)215 #expect(arial["Unicode blocks"]?.contains("Basic Latin 95/95") == true && arial["Tables"]?.contains("glyf ") == true && arial["Tables"]?.contains("DSIG ") == true)216 let stix = try await fields(.cff)217 #expect(stix["Outlines"] == "PostScript (CFF)" && stix["Natural extension"] == ".otf" && stix["Tables"]?.contains("CFF ") == true)218 let hebrew = try await fields(.variable)219 #expect(hebrew["Variation axes"]?.contains("wght") == true && hebrew["Named instances"] != nil)220 #expect(hebrew["Unicode blocks"]?.contains("Hebrew") == true && hebrew["OpenType features"]?.isEmpty == false)221 let kufi = try await fields(.collection)222 #expect(kufi["Fonts in the collection"] == "2" && kufi["Container"] == "collection (TTC / OTC)" && kufi["Collection members"]?.contains(",") == true)223 // Glyph count agrees with Core Text for every fixture.224 for font in SystemFont.allCases {225 let file = try FontFile.open(font.url)226 #expect(try file.facts().glyphCount == (try LoadedFont(file: file).glyphCount), "\(font)")227 }228 let mono = try FontFile.open(URL(fileURLWithPath: "/System/Library/Fonts/Supplemental/Courier New.ttf")).facts()229 #expect(mono.isMonospaced == true && mono.family == "Courier New")230 // A web font reports its container too.231 let woff = try await convert(try scratch.fixture(.glyf), .ttf, .woff, in: scratch)232 let w = try await Self.engine.inspect(woff.url, format: .woff)233 #expect(w.fields.contains { $0.key == "Container" && $0.value == "WOFF" } && w.fields.contains { $0.key == "Family" && $0.value == "Arial Rounded MT Bold" })234 #expect(w.fields.contains { $0.key == "Uncompressed font size" })235 }236237 @Test func previewAndGlyphInspectionWorkWithoutInstallingTheFont() async throws {238 let scratch = try Scratch(); defer { scratch.cleanUp() }239 let source = try scratch.fixture(.glyf)240 let font = try LoadedFont(url: source)241 let short = try #require(font.preview("Hi", pointSize: 40, scale: 2)), long = try #require(font.preview("Hamburgefonstiv", pointSize: 40, scale: 2))242 #expect(long.width > short.width * 3 && short.height == long.height && short.height > 80)243 // Something was actually drawn: the bitmap has opaque pixels and transparent ones.244 let data = try #require(long.dataProvider?.data as Data?)245 var opaque = 0, clear = 0246 for i in stride(from: 3, to: data.count, by: 4) { if data[i] > 200 { opaque += 1 } else if data[i] == 0 { clear += 1 } }247 #expect(opaque > 500 && clear > opaque)248 #expect(font.preview("", pointSize: 40) == nil && font.preview("x", pointSize: 0) == nil && font.preview(String(repeating: "W", count: 4000), pointSize: 400, scale: 8) == nil)249 // The same API reads a WOFF2 (decoded by the engine) and a collection member.250 let woff2 = try await convert(source, .ttf, .woff2, options: ["quality": .int(3)], in: scratch)251 let fromWeb = try FontPreview.render(url: woff2.url, text: "Hamburgefonstiv", pointSize: 40)252 #expect(fromWeb.width == long.width && (fromWeb.dataProvider?.data as Data?) == data)253 _ = try FontPreview.render(url: try scratch.fixture(.futura), text: "Futura", member: 4)254 #expect(throws: ConversionError.self) { _ = try FontPreview.render(url: source, text: "x", member: 1) }255 // Glyph browser: a page by index, with names, code points, advances and outlines.256 let page = font.glyphs(in: 0..<64)257 #expect(page.count == 64 && font.glyphs(in: font.glyphCount - 2..<font.glyphCount + 50).count == 2 && font.glyphs(in: 70_000..<70_010).isEmpty)258 let all = font.glyphs(in: 0..<font.glyphCount)259 let a = try #require(all.first { $0.codePoints.contains(0x41) })260 #expect(a.name == "A" && a.advance > 500 && a.outline != nil && a.outline?.isEmpty == false)261 let space = try #require(all.first { $0.codePoints.contains(0x20) })262 #expect(space.advance > 0 && (space.outline == nil || space.outline?.isEmpty == true))263 #expect(font.glyphCount == 242 || font.glyphCount > 100)264 }265}266