import CoreText import Foundation import RastrilloApple import SwiftUI import XCTest @testable import DocsKit #if os(macOS) import AppKit #else import UIKit #endif /// Paul's font rulings (2026-10-24) on the apps: the default is Carlito, every /// family is bundled and resolved from its own file, Sans is Liberation Sans /// and never the default, and the picker shows each family in its face. /// /// The expectations are read from internal/fonts/fonts.json in the /// repository, not from DocsKit, so a bundle that drifted from the shared /// list fails here rather than agreeing with itself. final class DocsFontsTests: XCTestCase { struct SharedFamily { let key: String; let name: String; let dir: String; let styles: [String: String]; let twin: String? } static let repository = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() static func shared() throws -> (standard: String, code: String, families: [SharedFamily]) { let data = try Data(contentsOf: repository.appendingPathComponent("internal/fonts/fonts.json")) let json = try XCTUnwrap(try JSONSerialization.jsonObject(with: data) as? [String: Any]) let families = try XCTUnwrap(json["families"] as? [[String: Any]]).map { SharedFamily(key: $0["key"] as! String, name: $0["name"] as! String, dir: $0["dir"] as! String, styles: $0["styles"] as! [String: String], twin: $0["twin"] as? String) } return (json["default"] as! String, json["code"] as! String, families) } static func url(of font: DocsPlatformFont) -> URL? { CTFontCopyAttribute(font as CTFont, kCTFontURLAttribute) as? URL } static func bundled(_ family: SharedFamily, _ style: String) throws -> URL { let file = try XCTUnwrap(family.styles[style], "\(family.key) has no \(style)") return try XCTUnwrap(DocsResources.bundle.url(forResource: file, withExtension: "ttf", subdirectory: "Fonts/" + family.dir), "\(file).ttf is not in the app bundle") } /// Every face of all sixteen families is in the bundle, registers for the /// process, resolves by its PostScript name, and is drawn from the /// bundled file itself. Inter is installed system-wide on the machine /// this was written on, and NSFont(name:) returns that copy; the run's /// face must not. @MainActor func testEveryBundledFaceRegistersAndResolvesFromItsOwnFile() throws { let shared = try Self.shared() XCTAssertEqual(shared.families.count, 16) for family in shared.families { for (style, bold, italic) in [("regular", false, false), ("bold", true, false), ("italic", false, true), ("boldItalic", true, true)] { var marks: [String: JSONValue] = ["font_" + family.key: .object([:])] if bold { marks["strong"] = .object([:]) } if italic { marks["em"] = .object([:]) } let font = DocsFonts.font(marks: marks, size: 12, heading: false) // Caveat has no italic: it stays upright, as on the web and in the PDF. let expected = family.styles[style] != nil ? style : (bold ? "bold" : "regular") let file = try Self.bundled(family, expected) XCTAssertEqual(Self.url(of: font)?.standardizedFileURL, file.standardizedFileURL, "\(family.key) \(style)") let descriptor = try XCTUnwrap((CTFontManagerCreateFontDescriptorsFromURL(file as CFURL) as? [CTFontDescriptor])?.first) let postScript = try XCTUnwrap(CTFontDescriptorCopyAttribute(descriptor, kCTFontNameAttribute) as? String) XCTAssertEqual(CTFontCopyPostScriptName(font as CTFont) as String, postScript) XCTAssertEqual(CTFontCopyFamilyName(font as CTFont) as String, family.name, "\(family.key)'s face names its family") XCTAssertNotNil(DocsPlatformFont(name: postScript, size: 12), "\(postScript) resolves by name once registered") #if os(macOS) let registered = (CTFontManagerCopyAvailableFontURLs() as? [URL] ?? []).map(\.standardizedFileURL) #else let registered = (CTFontManagerCopyRegisteredFontDescriptors(.process, true) as? [CTFontDescriptor] ?? []).compactMap { (CTFontDescriptorCopyAttribute($0, kCTFontURLAttribute) as? URL)?.standardizedFileURL } #endif XCTAssertTrue(registered.contains(file.standardizedFileURL), "\(file.lastPathComponent) is registered for the process") } } } /// A name lookup is cached for the process: once anything has resolved /// "Inter-Regular" while only an installed Inter answered to it, /// NSFont(name:) keeps returning that copy even after the bundled one is /// registered. The run's face must still be the bundled file. Needs an /// Inter installed outside the app, as on the machine this was written on. @MainActor func testAnInstalledCopyNeverStandsInForABundledFace() throws { #if os(macOS) DocsFonts.register() let family = try XCTUnwrap(DocsFonts.family(key: "inter")) let ours = try XCTUnwrap(DocsFonts.url(family, .regular)) let installed = (CTFontManagerCopyAvailableFontURLs() as? [URL] ?? []).filter { $0.lastPathComponent.hasPrefix("Inter") && !$0.path.hasPrefix(ours.deletingLastPathComponent().path) } guard !installed.isEmpty else { throw XCTSkip("no Inter is installed outside the app to stand in for the bundled one") } CTFontManagerUnregisterFontsForURL(ours as CFURL, .process, nil) _ = NSFont(name: "Inter-Regular", size: 12) CTFontManagerRegisterFontsForURL(ours as CFURL, .process, nil) let byName = try XCTUnwrap(NSFont(name: "Inter-Regular", size: 12)) XCTAssertNotEqual(Self.url(of: byName)?.standardizedFileURL, ours.standardizedFileURL, "precondition: the name now answers with the installed copy") XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["font_inter": .object([:])], size: 12, heading: false))?.standardizedFileURL, ours.standardizedFileURL) #else throw XCTSkip("an installed copy of a bundled family is a Mac case") #endif } /// The default is Carlito, body and headings; code stays Liberation Mono. @MainActor func testTheDefaultFontIsCarlito() throws { let shared = try Self.shared() XCTAssertEqual(shared.standard, "carlito") let carlito = try XCTUnwrap(shared.families.first { $0.key == "carlito" }) let mono = try XCTUnwrap(shared.families.first { $0.key == shared.code }) XCTAssertEqual(Self.url(of: DocsFonts.font(marks: [:], size: 12, heading: false)), try Self.bundled(carlito, "regular")) XCTAssertEqual(Self.url(of: DocsFonts.font(marks: [:], size: 24, heading: true)), try Self.bundled(carlito, "bold")) XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["em": .object([:])], size: 12, heading: false)), try Self.bundled(carlito, "italic")) XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["code": .object([:]), "font_inter": .object([:])], size: 12, heading: false)), try Self.bundled(mono, "regular")) // A family this build does not know is the default, as on the web and in the PDF. XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["font_futura": .object([:])], size: 12, heading: false)), try Self.bundled(carlito, "regular")) // Two font marks (POST /d/{sqid}/updates allows it): the later in manifest order wins. let inter = try XCTUnwrap(shared.families.first { $0.key == "inter" }) XCTAssertEqual(Self.url(of: DocsFonts.font(marks: ["font_carlito": .object([:]), "font_inter": .object([:])], size: 12, heading: false)), try Self.bundled(inter, "regular")) // Every run of a rendered document, headings and lists included. let projection = CRDTProjection(children: [ CRDTNode(id: "h", type: "heading", attrs: ["level": "1"], children: [CRDTNode(id: "ht", type: "text", runs: [CRDTRun(insert: "Title")])]), CRDTNode(id: "p", type: "paragraph", children: [CRDTNode(id: "pt", type: "text", runs: [CRDTRun(insert: "Body "), CRDTRun(insert: "bold", marks: ["strong": .object([:])])])]), 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")])])])]), CRDTNode(id: "e", type: "paragraph"), ], canUndo: false, canRedo: false) let rendered = NativeTextProjection.render(projection) var faces = Set() rendered.enumerateAttribute(.font, in: NSRange(location: 0, length: rendered.length)) { value, _, _ in if let font = value as? DocsPlatformFont, let url = Self.url(of: font) { faces.insert(url.lastPathComponent) } else { faces.insert("unbundled") } } XCTAssertEqual(faces, ["Carlito-Regular.ttf", "Carlito-Bold.ttf"]) } /// Choosing Sans sets font_sans, Liberation Sans. It used to clear the /// group, so Sans picked on the Mac showed as Carlito on the web. @MainActor func testSansIsLiberationSansAndNotTheDefault() throws { let model = DocsModel(client: NativeHTTP(origin: URL(string: "https://example.invalid")!)) model.detail = DocumentDetail(sqid: "fixture", title: "Fixture", guid: "fixture", can_write: true, can_share: false) model.projection = CRDTProjection(children: [CRDTNode(id: "p", type: "paragraph", children: [CRDTNode(id: "t", type: "text", runs: [ CRDTRun(insert: "plain "), CRDTRun(insert: "sans", marks: ["font_sans": .object([:])]), ])])], canUndo: false, canRedo: false) let content = NativeTextProjection.render(model.projection!) let commands = DocumentCommands(model: model, content: content) model.selection = NSRange(location: 2, length: 0) XCTAssertEqual(try XCTUnwrap(DocumentToolbarSelection(commands: commands)).font, "carlito", "unmarked text is Carlito") model.selection = NSRange(location: 8, length: 0) XCTAssertEqual(try XCTUnwrap(DocumentToolbarSelection(commands: commands)).font, "sans") // The toolbar's own call for Sans, at a collapsed caret. model.selection = NSRange(location: 2, length: 0) XCTAssertTrue(commands.format("font_sans", exclusive: ["font_sans", "font_serif", "font_mono"])) XCTAssertEqual(model.typingMarks?["font_sans"], .object([:]), "Sans is a mark, not the default") let sans = DocsFonts.font(marks: ["font_sans": .object([:])], size: 12, heading: false) XCTAssertEqual(CTFontCopyFamilyName(sans as CTFont) as String, "Liberation Sans") } /// A pasted font name maps to the shared list deterministically, once: /// Word's names to their twins, other names to the family that stands in /// for them, and anything else to the default rather than to Sans. @MainActor func testPastedFontNamesMapToTheSharedList() { // Copying unmarked text inside the app keeps it unmarked. let source = NSAttributedString(string: "Plain\n", attributes: [.font: DocsFonts.font(marks: [:], size: 12, heading: false)]) let marks = DocsRichClipboard.marks(source.attributes(at: 0, effectiveRange: nil)) XCTAssertEqual(marks.keys.filter { $0.hasPrefix("font_") }, [], "Carlito pastes as the default, not as Sans") let inter = DocsRichClipboard.marks([.font: DocsFonts.font(marks: ["font_inter": .object([:])], size: 12, heading: false)]) XCTAssertEqual(inter["font_inter"], .object([:])) let html = DocsHTMLClipboard.blocks("

Display Word Serif

") let runs = html.flatMap { block -> [JSONValue] in if case .object(let node) = block, case .array(let children)? = node["children"] { return children.flatMap { child -> [JSONValue] in if case .object(let text) = child, case .array(let runs)? = text["runs"] { return runs } return [] } } return [] } func marksOf(_ run: JSONValue) -> [String: JSONValue] { if case .object(let values) = run, case .object(let marks)? = values["marks"] { return marks } return [:] } func fonts(containing text: String) -> [String] { let run = runs.first { if case .object(let values) = $0, case .string(let insert)? = values["insert"] { return insert.contains(text) }; return false } return run.map { marksOf($0).keys.filter { $0.hasPrefix("font_") }.sorted() } ?? ["no run"] } XCTAssertEqual(fonts(containing: "Display"), ["font_playfair"]) XCTAssertEqual(fonts(containing: "Word"), [], "Calibri is Carlito, the default") XCTAssertEqual(fonts(containing: "Serif"), ["font_caladea"], "Georgia's nearest in the shared list is Caladea") } /// Copying out writes every family's class, which the web editor parses, /// and its name for any other application. @MainActor func testCopiedHTMLNamesEveryFamily() throws { let block: JSONValue = .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([ .object(["insert": .string("Inter"), "marks": .object(["font_inter": .object([:])])]), .object(["insert": .string("Sans"), "marks": .object(["font_sans": .object([:])])]), ])])])]) let html = DocsRichClipboard.html([block]) XCTAssertTrue(html.contains("class=\"docs-font-inter\""), html) XCTAssertTrue(html.contains("font-family:'Inter'"), html) XCTAssertTrue(html.contains("class=\"docs-font-sans\""), html) XCTAssertTrue(html.contains("font-family:'Liberation Sans'"), html) } #if os(macOS) /// The first frame the editor draws is already the final one: every run /// in Carlito, nothing blank, and no later frame differs. A frame drawn /// with another face first would differ from the settled one, as the /// Sans control shows. @MainActor func testFirstFrameOfADocumentIsAlreadyInCarlito() throws { let words = "Quarterly report. The first frame of this document is already in Carlito, and so is every frame after it." func frames(_ marks: [String: JSONValue]?) throws -> (first: Data, settled: Data, storage: NSTextStorage) { let projection = CRDTProjection(children: [ CRDTNode(id: "h", type: "heading", attrs: ["level": "1"], children: [CRDTNode(id: "ht", type: "text", runs: [CRDTRun(insert: "Report", marks: marks)])]), CRDTNode(id: "p", type: "paragraph", children: [CRDTNode(id: "pt", type: "text", runs: [CRDTRun(insert: words, marks: marks)])]), ], canUndo: false, canRedo: false) let surface = DocumentSurface() surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil)) let view = DocumentEditorHost(surface: surface, paged: false) let host = NSHostingView(rootView: view.frame(width: 640, height: 240)) let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 240), styleMask: [.borderless], backing: .buffered, defer: false) window.contentView = host host.layoutSubtreeIfNeeded() func frame() throws -> Data { let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds)) host.cacheDisplay(in: host.bounds, to: rep) return try XCTUnwrap(rep.representation(using: .png, properties: [:])) } let first = try frame() RunLoop.main.run(until: Date().addingTimeInterval(0.6)) host.layoutSubtreeIfNeeded() let settled = try frame() let text = try XCTUnwrap(Self.textView(in: host)) return (first, settled, try XCTUnwrap(text.textStorage)) } let carlito = try frames(nil) XCTAssertEqual(carlito.first, carlito.settled, "the first frame is the final frame") var faces = Set() carlito.storage.enumerateAttribute(.font, in: NSRange(location: 0, length: carlito.storage.length)) { value, range, _ in guard (carlito.storage.string as NSString).substring(with: range).contains(where: { !$0.isWhitespace }) else { return } faces.insert((value as? NSFont).flatMap(Self.url(of:))?.lastPathComponent ?? "unbundled") } XCTAssertEqual(faces, ["Carlito-Bold.ttf", "Carlito-Regular.ttf"]) let sans = try frames(["font_sans": .object([:])]) XCTAssertNotEqual(carlito.first, sans.first, "a frame in another face is visibly different") XCTAssertGreaterThan(Self.ink(carlito.first), 2_000, "the first frame shows the words, not a gap") } static func ink(_ png: Data) -> Int { guard let rep = NSBitmapImageRep(data: png) else { return 0 } var dark = 0 for y in 0.. NSTextView? { if let text = view as? NSTextView { return text } for subview in view.subviews { if let text = textView(in: subview) { return text } } return nil } #endif }