| 1 | import CoreText |
| 2 | import Foundation |
| 3 | import RastrilloApple |
| 4 | import SwiftUI |
| 5 | import XCTest |
| 6 | @testable import DocsKit |
| 7 | #if os(macOS) |
| 8 | import AppKit |
| 9 | #else |
| 10 | import UIKit |
| 11 | #endif |
| 12 | |
| 13 | /// Paul's font rulings (2026-10-24) on the apps: the default is Carlito, every |
| 14 | /// family is bundled and resolved from its own file, Sans is Liberation Sans |
| 15 | /// and never the default, and the picker shows each family in its face. |
| 16 | /// |
| 17 | /// The expectations are read from internal/fonts/fonts.json in the |
| 18 | /// repository, not from DocsKit, so a bundle that drifted from the shared |
| 19 | /// list fails here rather than agreeing with itself. |
| 20 | final class DocsFontsTests: XCTestCase { |
| 21 | struct SharedFamily { let key: String; let name: String; let dir: String; let styles: [String: String]; let twin: String? } |
| 22 | static let repository = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() |
| 23 | .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() |
| 24 | static func shared() throws -> (standard: String, code: String, families: [SharedFamily]) { |
| 25 | let data = try Data(contentsOf: repository.appendingPathComponent("internal/fonts/fonts.json")) |
| 26 | let json = try XCTUnwrap(try JSONSerialization.jsonObject(with: data) as? [String: Any]) |
| 27 | let families = try XCTUnwrap(json["families"] as? [[String: Any]]).map { |
| 28 | SharedFamily(key: $0["key"] as! String, name: $0["name"] as! String, dir: $0["dir"] as! String, |
| 29 | styles: $0["styles"] as! [String: String], twin: $0["twin"] as? String) |
| 30 | } |
| 31 | return (json["default"] as! String, json["code"] as! String, families) |
| 32 | } |
| 33 | static func url(of font: DocsPlatformFont) -> URL? { |
| 34 | CTFontCopyAttribute(font as CTFont, kCTFontURLAttribute) as? URL |
| 35 | } |
| 36 | static func bundled(_ family: SharedFamily, _ style: String) throws -> URL { |
| 37 | let file = try XCTUnwrap(family.styles[style], "\(family.key) has no \(style)") |
| 38 | return try XCTUnwrap(DocsResources.bundle.url(forResource: file, withExtension: "ttf", subdirectory: "Fonts/" + family.dir), |
| 39 | "\(file).ttf is not in the app bundle") |
| 40 | } |
| 41 | |
| 42 | /// Every face of all sixteen families is in the bundle, registers for the |
| 43 | /// process, resolves by its PostScript name, and is drawn from the |
| 44 | /// bundled file itself. Inter is installed system-wide on the machine |
| 45 | /// this was written on, and NSFont(name:) returns that copy; the run's |
| 46 | /// face must not. |
| 47 | @MainActor func testEveryBundledFaceRegistersAndResolvesFromItsOwnFile() throws { |
| 48 | let shared = try Self.shared() |
| 49 | XCTAssertEqual(shared.families.count, 16) |
| 50 | for family in shared.families { |
| 51 | for (style, bold, italic) in [("regular", false, false), ("bold", true, false), ("italic", false, true), ("boldItalic", true, true)] { |
| 52 | var marks: [String: JSONValue] = ["font_" + family.key: .object([:])] |
| 53 | if bold { marks["strong"] = .object([:]) } |
| 54 | if italic { marks["em"] = .object([:]) } |
| 55 | let font = DocsFonts.font(marks: marks, size: 12, heading: false) |
| 56 | // Caveat has no italic: it stays upright, as on the web and in the PDF. |
| 57 | let expected = family.styles[style] != nil ? style : (bold ? "bold" : "regular") |
| 58 | let file = try Self.bundled(family, expected) |
| 59 | XCTAssertEqual(Self.url(of: font)?.standardizedFileURL, file.standardizedFileURL, "\(family.key) \(style)") |
| 60 | let descriptor = try XCTUnwrap((CTFontManagerCreateFontDescriptorsFromURL(file as CFURL) as? [CTFontDescriptor])?.first) |
| 61 | let postScript = try XCTUnwrap(CTFontDescriptorCopyAttribute(descriptor, kCTFontNameAttribute) as? String) |
| 62 | XCTAssertEqual(CTFontCopyPostScriptName(font as CTFont) as String, postScript) |
| 63 | XCTAssertEqual(CTFontCopyFamilyName(font as CTFont) as String, family.name, "\(family.key)'s face names its family") |
| 64 | XCTAssertNotNil(DocsPlatformFont(name: postScript, size: 12), "\(postScript) resolves by name once registered") |
| 65 | #if os(macOS) |
| 66 | let registered = (CTFontManagerCopyAvailableFontURLs() as? [URL] ?? []).map(\.standardizedFileURL) |
| 67 | #else |
| 68 | let registered = (CTFontManagerCopyRegisteredFontDescriptors(.process, true) as? [CTFontDescriptor] ?? []).compactMap { |
| 69 | (CTFontDescriptorCopyAttribute($0, kCTFontURLAttribute) as? URL)?.standardizedFileURL |
| 70 | } |
| 71 | #endif |
| 72 | XCTAssertTrue(registered.contains(file.standardizedFileURL), "\(file.lastPathComponent) is registered for the process") |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | /// A name lookup is cached for the process: once anything has resolved |
| 78 | /// "Inter-Regular" while only an installed Inter answered to it, |
| 79 | /// NSFont(name:) keeps returning that copy even after the bundled one is |
| 80 | /// registered. The run's face must still be the bundled file. Needs an |
| 81 | /// Inter installed outside the app, as on the machine this was written on. |
| 82 | @MainActor func testAnInstalledCopyNeverStandsInForABundledFace() throws { |
| 83 | #if os(macOS) |
| 84 | DocsFonts.register() |
| 85 | let family = try XCTUnwrap(DocsFonts.family(key: "inter")) |
| 86 | let ours = try XCTUnwrap(DocsFonts.url(family, .regular)) |
| 87 | let installed = (CTFontManagerCopyAvailableFontURLs() as? [URL] ?? []).filter { |
| 88 | $0.lastPathComponent.hasPrefix("Inter") && !$0.path.hasPrefix(ours.deletingLastPathComponent().path) |
| 89 | } |
| 90 | guard !installed.isEmpty else { throw XCTSkip("no Inter is installed outside the app to stand in for the bundled one") } |
| 91 | CTFontManagerUnregisterFontsForURL(ours as CFURL, .process, nil) |
| 92 | _ = NSFont(name: "Inter-Regular", size: 12) |
| 93 | CTFontManagerRegisterFontsForURL(ours as CFURL, .process, nil) |
| 94 | let byName = try XCTUnwrap(NSFont(name: "Inter-Regular", size: 12)) |
| 95 | XCTAssertNotEqual(Self.url(of: byName)?.standardizedFileURL, ours.standardizedFileURL, "precondition: the name now answers with the installed copy") |
| 96 | XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["font_inter": .object([:])], size: 12, heading: false))?.standardizedFileURL, ours.standardizedFileURL) |
| 97 | #else |
| 98 | throw XCTSkip("an installed copy of a bundled family is a Mac case") |
| 99 | #endif |
| 100 | } |
| 101 | |
| 102 | /// The default is Carlito, body and headings; code stays Liberation Mono. |
| 103 | @MainActor func testTheDefaultFontIsCarlito() throws { |
| 104 | let shared = try Self.shared() |
| 105 | XCTAssertEqual(shared.standard, "carlito") |
| 106 | let carlito = try XCTUnwrap(shared.families.first { $0.key == "carlito" }) |
| 107 | let mono = try XCTUnwrap(shared.families.first { $0.key == shared.code }) |
| 108 | XCTAssertEqual(Self.url(of: DocsFonts.font(marks: [:], size: 12, heading: false)), try Self.bundled(carlito, "regular")) |
| 109 | XCTAssertEqual(Self.url(of: DocsFonts.font(marks: [:], size: 24, heading: true)), try Self.bundled(carlito, "bold")) |
| 110 | XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["em": .object([:])], size: 12, heading: false)), try Self.bundled(carlito, "italic")) |
| 111 | XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["code": .object([:]), "font_inter": .object([:])], size: 12, heading: false)), try Self.bundled(mono, "regular")) |
| 112 | // A family this build does not know is the default, as on the web and in the PDF. |
| 113 | XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["font_futura": .object([:])], size: 12, heading: false)), try Self.bundled(carlito, "regular")) |
| 114 | // Two font marks (POST /d/{sqid}/updates allows it): the later in manifest order wins. |
| 115 | let inter = try XCTUnwrap(shared.families.first { $0.key == "inter" }) |
| 116 | XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["font_carlito": .object([:]), "font_inter": .object([:])], size: 12, heading: false)), try Self.bundled(inter, "regular")) |
| 117 | |
| 118 | // Every run of a rendered document, headings and lists included. |
| 119 | let projection = CRDTProjection(children: [ |
| 120 | CRDTNode(id: "h", type: "heading", attrs: ["level": "1"], children: [CRDTNode(id: "ht", type: "text", runs: [CRDTRun(insert: "Title")])]), |
| 121 | CRDTNode(id: "p", type: "paragraph", children: [CRDTNode(id: "pt", type: "text", runs: [CRDTRun(insert: "Body "), CRDTRun(insert: "bold", marks: ["strong": .object([:])])])]), |
| 122 | CRDTNode(id: "l", type: "bullet_list", children: [CRDTNode(id: "li", type: "list_item", children: [CRDTNode(id: "lp", type: "paragraph", children: [CRDTNode(id: "lt", type: "text", runs: [CRDTRun(insert: "Item")])])])]), |
| 123 | CRDTNode(id: "e", type: "paragraph"), |
| 124 | ], canUndo: false, canRedo: false) |
| 125 | let rendered = NativeTextProjection.render(projection) |
| 126 | var faces = Set<String>() |
| 127 | rendered.enumerateAttribute(.font, in: NSRange(location: 0, length: rendered.length)) { value, _, _ in |
| 128 | if let font = value as? DocsPlatformFont, let url = Self.url(of: font) { faces.insert(url.lastPathComponent) } else { faces.insert("unbundled") } |
| 129 | } |
| 130 | XCTAssertEqual(faces, ["Carlito-Regular.ttf", "Carlito-Bold.ttf"]) |
| 131 | } |
| 132 | |
| 133 | /// Choosing Sans sets font_sans, Liberation Sans. It used to clear the |
| 134 | /// group, so Sans picked on the Mac showed as Carlito on the web. |
| 135 | @MainActor func testSansIsLiberationSansAndNotTheDefault() throws { |
| 136 | let model = DocsModel(client: NativeHTTP(origin: URL(string: "https://example.invalid")!)) |
| 137 | model.detail = DocumentDetail(sqid: "fixture", title: "Fixture", guid: "fixture", can_write: true, can_share: false) |
| 138 | model.projection = CRDTProjection(children: [CRDTNode(id: "p", type: "paragraph", children: [CRDTNode(id: "t", type: "text", runs: [ |
| 139 | CRDTRun(insert: "plain "), CRDTRun(insert: "sans", marks: ["font_sans": .object([:])]), |
| 140 | ])])], canUndo: false, canRedo: false) |
| 141 | let content = NativeTextProjection.render(model.projection!) |
| 142 | let commands = DocumentCommands(model: model, content: content) |
| 143 | model.selection = NSRange(location: 2, length: 0) |
| 144 | XCTAssertEqual(try XCTUnwrap(DocumentToolbarSelection(commands: commands)).font, "carlito", "unmarked text is Carlito") |
| 145 | model.selection = NSRange(location: 8, length: 0) |
| 146 | XCTAssertEqual(try XCTUnwrap(DocumentToolbarSelection(commands: commands)).font, "sans") |
| 147 | |
| 148 | // The toolbar's own call for Sans, at a collapsed caret. |
| 149 | model.selection = NSRange(location: 2, length: 0) |
| 150 | XCTAssertTrue(commands.format("font_sans", exclusive: ["font_sans", "font_serif", "font_mono"])) |
| 151 | XCTAssertEqual(model.typingMarks?["font_sans"], .object([:]), "Sans is a mark, not the default") |
| 152 | let sans = DocsFonts.font(marks: ["font_sans": .object([:])], size: 12, heading: false) |
| 153 | XCTAssertEqual(CTFontCopyFamilyName(sans as CTFont) as String, "Liberation Sans") |
| 154 | } |
| 155 | |
| 156 | /// A pasted font name maps to the shared list deterministically, once: |
| 157 | /// Word's names to their twins, other names to the family that stands in |
| 158 | /// for them, and anything else to the default rather than to Sans. |
| 159 | @MainActor func testPastedFontNamesMapToTheSharedList() { |
| 160 | // Copying unmarked text inside the app keeps it unmarked. |
| 161 | let source = NSAttributedString(string: "Plain\n", attributes: [.font: DocsFonts.font(marks: [:], size: 12, heading: false)]) |
| 162 | let marks = DocsRichClipboard.marks(source.attributes(at: 0, effectiveRange: nil)) |
| 163 | XCTAssertEqual(marks.keys.filter { $0.hasPrefix("font_") }, [], "Carlito pastes as the default, not as Sans") |
| 164 | let inter = DocsRichClipboard.marks([.font: DocsFonts.font(marks: ["font_inter": .object([:])], size: 12, heading: false)]) |
| 165 | XCTAssertEqual(inter["font_inter"], .object([:])) |
| 166 | |
| 167 | let html = DocsHTMLClipboard.blocks("<p><span class='docs-font-playfair'>Display</span> <span style=\"font-family: Calibri\">Word</span> <span style=\"font-family: Georgia\">Serif</span></p>") |
| 168 | let runs = html.flatMap { block -> [JSONValue] in |
| 169 | if case .object(let node) = block, case .array(let children)? = node["children"] { |
| 170 | return children.flatMap { child -> [JSONValue] in |
| 171 | if case .object(let text) = child, case .array(let runs)? = text["runs"] { return runs } |
| 172 | return [] |
| 173 | } |
| 174 | } |
| 175 | return [] |
| 176 | } |
| 177 | func marksOf(_ run: JSONValue) -> [String: JSONValue] { |
| 178 | if case .object(let values) = run, case .object(let marks)? = values["marks"] { return marks } |
| 179 | return [:] |
| 180 | } |
| 181 | func fonts(containing text: String) -> [String] { |
| 182 | let run = runs.first { if case .object(let values) = $0, case .string(let insert)? = values["insert"] { return insert.contains(text) }; return false } |
| 183 | return run.map { marksOf($0).keys.filter { $0.hasPrefix("font_") }.sorted() } ?? ["no run"] |
| 184 | } |
| 185 | XCTAssertEqual(fonts(containing: "Display"), ["font_playfair"]) |
| 186 | XCTAssertEqual(fonts(containing: "Word"), [], "Calibri is Carlito, the default") |
| 187 | XCTAssertEqual(fonts(containing: "Serif"), ["font_caladea"], "Georgia's nearest in the shared list is Caladea") |
| 188 | } |
| 189 | |
| 190 | /// Copying out writes every family's class, which the web editor parses, |
| 191 | /// and its name for any other application. |
| 192 | @MainActor func testCopiedHTMLNamesEveryFamily() throws { |
| 193 | let block: JSONValue = .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([ |
| 194 | .object(["insert": .string("Inter"), "marks": .object(["font_inter": .object([:])])]), |
| 195 | .object(["insert": .string("Sans"), "marks": .object(["font_sans": .object([:])])]), |
| 196 | ])])])]) |
| 197 | let html = DocsRichClipboard.html([block]) |
| 198 | XCTAssertTrue(html.contains("class=\"docs-font-inter\""), html) |
| 199 | XCTAssertTrue(html.contains("font-family:'Inter'"), html) |
| 200 | XCTAssertTrue(html.contains("class=\"docs-font-sans\""), html) |
| 201 | XCTAssertTrue(html.contains("font-family:'Liberation Sans'"), html) |
| 202 | } |
| 203 | |
| 204 | #if os(macOS) |
| 205 | /// The first frame the editor draws is already the final one: every run |
| 206 | /// in Carlito, nothing blank, and no later frame differs. A frame drawn |
| 207 | /// with another face first would differ from the settled one, as the |
| 208 | /// Sans control shows. |
| 209 | @MainActor func testFirstFrameOfADocumentIsAlreadyInCarlito() throws { |
| 210 | let words = "Quarterly report. The first frame of this document is already in Carlito, and so is every frame after it." |
| 211 | func frames(_ marks: [String: JSONValue]?) throws -> (first: Data, settled: Data, storage: NSTextStorage) { |
| 212 | let projection = CRDTProjection(children: [ |
| 213 | CRDTNode(id: "h", type: "heading", attrs: ["level": "1"], children: [CRDTNode(id: "ht", type: "text", runs: [CRDTRun(insert: "Report", marks: marks)])]), |
| 214 | CRDTNode(id: "p", type: "paragraph", children: [CRDTNode(id: "pt", type: "text", runs: [CRDTRun(insert: words, marks: marks)])]), |
| 215 | ], canUndo: false, canRedo: false) |
| 216 | let surface = DocumentSurface() |
| 217 | surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil)) |
| 218 | let view = DocumentEditorHost(surface: surface, paged: false) |
| 219 | let host = NSHostingView(rootView: view.frame(width: 640, height: 240)) |
| 220 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 240), styleMask: [.borderless], backing: .buffered, defer: false) |
| 221 | window.contentView = host |
| 222 | host.layoutSubtreeIfNeeded() |
| 223 | func frame() throws -> Data { |
| 224 | let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds)) |
| 225 | host.cacheDisplay(in: host.bounds, to: rep) |
| 226 | return try XCTUnwrap(rep.representation(using: .png, properties: [:])) |
| 227 | } |
| 228 | let first = try frame() |
| 229 | RunLoop.main.run(until: Date().addingTimeInterval(0.6)) |
| 230 | host.layoutSubtreeIfNeeded() |
| 231 | let settled = try frame() |
| 232 | let text = try XCTUnwrap(Self.textView(in: host)) |
| 233 | return (first, settled, try XCTUnwrap(text.textStorage)) |
| 234 | } |
| 235 | let carlito = try frames(nil) |
| 236 | XCTAssertEqual(carlito.first, carlito.settled, "the first frame is the final frame") |
| 237 | var faces = Set<String>() |
| 238 | carlito.storage.enumerateAttribute(.font, in: NSRange(location: 0, length: carlito.storage.length)) { value, range, _ in |
| 239 | guard (carlito.storage.string as NSString).substring(with: range).contains(where: { !$0.isWhitespace }) else { return } |
| 240 | faces.insert((value as? NSFont).flatMap(Self.url(of:))?.lastPathComponent ?? "unbundled") |
| 241 | } |
| 242 | XCTAssertEqual(faces, ["Carlito-Bold.ttf", "Carlito-Regular.ttf"]) |
| 243 | let sans = try frames(["font_sans": .object([:])]) |
| 244 | XCTAssertNotEqual(carlito.first, sans.first, "a frame in another face is visibly different") |
| 245 | XCTAssertGreaterThan(Self.ink(carlito.first), 2_000, "the first frame shows the words, not a gap") |
| 246 | } |
| 247 | static func ink(_ png: Data) -> Int { |
| 248 | guard let rep = NSBitmapImageRep(data: png) else { return 0 } |
| 249 | var dark = 0 |
| 250 | for y in 0..<rep.pixelsHigh { for x in 0..<rep.pixelsWide where (rep.colorAt(x: x, y: y)?.usingColorSpace(.deviceGray)?.whiteComponent ?? 1) < 0.5 { dark += 1 } } |
| 251 | return dark |
| 252 | } |
| 253 | static func textView(in view: NSView) -> NSTextView? { |
| 254 | if let text = view as? NSTextView { return text } |
| 255 | for subview in view.subviews { if let text = textView(in: subview) { return text } } |
| 256 | return nil |
| 257 | } |
| 258 | #endif |
| 259 | } |
| 260 | |