| 1 | import CoreText |
| 2 | import Foundation |
| 3 | #if os(macOS) |
| 4 | import AppKit |
| 5 | typealias DocsPlatformFont = NSFont |
| 6 | #else |
| 7 | import UIKit |
| 8 | typealias DocsPlatformFont = UIFont |
| 9 | #endif |
| 10 | |
| 11 | /// One family of internal/fonts/fonts.json, the font vocabulary the server, |
| 12 | /// the editor, the Rust renderer and these apps all read. |
| 13 | struct DocsFontFamily: Sendable, Hashable, Identifiable { |
| 14 | enum Style: String, Sendable, CaseIterable { case regular, bold, italic, boldItalic } |
| 15 | /// The mark is `font_<key>`. Keys never change: sans, serif and mono are |
| 16 | /// Liberation, as they were when there were only three. |
| 17 | let key: String |
| 18 | /// The family's own name, shown untranslated in the picker. |
| 19 | let name: String |
| 20 | let category: String |
| 21 | /// The proprietary face this one has the metrics of (Carlito: Calibri). |
| 22 | let twin: String? |
| 23 | /// The name a .docx uses for it: a twin's Word name, or its own. |
| 24 | let docxName: String |
| 25 | /// The CSS stack the web commits to when the face is late. Read here as |
| 26 | /// the names this family stands in for, when a paste names one of them. |
| 27 | let fallback: [String] |
| 28 | /// The position in the picker, from 0. |
| 29 | let index: Int |
| 30 | let directory: String |
| 31 | /// The licence's file name in the family's directory (OFL.txt). |
| 32 | let licenceFile: String |
| 33 | let files: [Style: String] |
| 34 | var id: String { key } |
| 35 | var mark: String { "font_" + key } |
| 36 | var styles: [Style] { Style.allCases.filter { files[$0] != nil } } |
| 37 | } |
| 38 | |
| 39 | /// Docs' fonts on the Mac and iPhone: all bundled, registered synchronously |
| 40 | /// before the first window, and resolved from the bundled files themselves. |
| 41 | /// |
| 42 | /// Nothing is downloaded, so nothing is ever drawn in a face it later leaves |
| 43 | /// (polish-audit/fonts/NO-FOUT.md §7): a document opens, a collaborator's |
| 44 | /// change arrives and a pick applies with the face already in memory. |
| 45 | /// |
| 46 | /// Faces are created from descriptors made from the bundled files, never |
| 47 | /// looked up by PostScript name: a person with Inter installed would |
| 48 | /// otherwise get their copy, with other metrics than the web's and the |
| 49 | /// PDF's (NSFont(name: "Inter-Regular") returns the installed variable font |
| 50 | /// on a Mac that has one). |
| 51 | public enum DocsFonts { |
| 52 | struct Manifest: Decodable { |
| 53 | struct Family: Decodable { |
| 54 | struct Docx: Decodable { let name: String } |
| 55 | let key: String, name: String, category: String, twin: String?, docx: Docx |
| 56 | let fallback: [String], dir: String, licence: String, styles: [String: String] |
| 57 | } |
| 58 | let `default`: String, code: String, families: [Family] |
| 59 | } |
| 60 | |
| 61 | final class Catalog: @unchecked Sendable { |
| 62 | let families: [DocsFontFamily] |
| 63 | let byKey: [String: DocsFontFamily] |
| 64 | let standard: DocsFontFamily |
| 65 | let code: DocsFontFamily |
| 66 | /// Every face's descriptor, from its file. CTFontDescriptor is |
| 67 | /// immutable, so sharing them across threads is safe. |
| 68 | let descriptors: [String: CTFontDescriptor] |
| 69 | let files: [String: URL] |
| 70 | let urls: [URL] |
| 71 | |
| 72 | init(bundle: Bundle) { |
| 73 | guard let url = bundle.url(forResource: "fonts", withExtension: "json", subdirectory: "Fonts"), |
| 74 | let data = try? Data(contentsOf: url), |
| 75 | let manifest = try? JSONDecoder().decode(Manifest.self, from: data) else { |
| 76 | // A build that lost its fonts would set every document in a |
| 77 | // system face. That is a packaging mistake, not a state to run in. |
| 78 | fatalError("DocsFonts: Fonts/fonts.json is missing from the DocsKit bundle") |
| 79 | } |
| 80 | var families: [DocsFontFamily] = [] |
| 81 | var descriptors: [String: CTFontDescriptor] = [:] |
| 82 | var urls: [URL] = [] |
| 83 | var fileURLs: [String: URL] = [:] |
| 84 | for (index, entry) in manifest.families.enumerated() { |
| 85 | var files: [DocsFontFamily.Style: String] = [:] |
| 86 | for (name, file) in entry.styles { |
| 87 | guard let style = DocsFontFamily.Style(rawValue: name) else { fatalError("DocsFonts: \(entry.key) has unknown style \(name)") } |
| 88 | guard let fileURL = bundle.url(forResource: file, withExtension: "ttf", subdirectory: "Fonts/" + entry.dir), |
| 89 | let descriptor = (CTFontManagerCreateFontDescriptorsFromURL(fileURL as CFURL) as? [CTFontDescriptor])?.first else { |
| 90 | fatalError("DocsFonts: Fonts/\(entry.dir)/\(file).ttf is missing or unreadable") |
| 91 | } |
| 92 | files[style] = file |
| 93 | descriptors[entry.key + "/" + name] = descriptor |
| 94 | fileURLs[entry.key + "/" + name] = fileURL |
| 95 | urls.append(fileURL) |
| 96 | } |
| 97 | guard files[.regular] != nil else { fatalError("DocsFonts: \(entry.key) has no regular face") } |
| 98 | families.append(DocsFontFamily(key: entry.key, name: entry.name, category: entry.category, twin: entry.twin, |
| 99 | docxName: entry.docx.name, fallback: entry.fallback, index: index, |
| 100 | directory: entry.dir, licenceFile: entry.licence, files: files)) |
| 101 | } |
| 102 | let byKey = Dictionary(uniqueKeysWithValues: families.map { ($0.key, $0) }) |
| 103 | guard let standard = byKey[manifest.default], let code = byKey[manifest.code] else { |
| 104 | fatalError("DocsFonts: the default or code family is not in the manifest") |
| 105 | } |
| 106 | self.families = families |
| 107 | self.byKey = byKey |
| 108 | self.standard = standard |
| 109 | self.code = code |
| 110 | self.descriptors = descriptors |
| 111 | self.files = fileURLs |
| 112 | self.urls = urls |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | static let catalog = Catalog(bundle: DocsResources.bundle) |
| 117 | |
| 118 | /// Every family, in the picker's order: Carlito and Caladea first. |
| 119 | static var families: [DocsFontFamily] { catalog.families } |
| 120 | /// The face an unmarked run is in: Carlito (Paul, 2026-10-24). |
| 121 | static var defaultFamily: DocsFontFamily { catalog.standard } |
| 122 | /// The face code is in, whatever else the run says. |
| 123 | static var codeFamily: DocsFontFamily { catalog.code } |
| 124 | /// Every font mark, the default's included. Choosing a font clears all |
| 125 | /// of them first, so a run is never in two faces. |
| 126 | static var marks: [String] { catalog.families.map(\.mark) } |
| 127 | static func family(key: String) -> DocsFontFamily? { catalog.byKey[key] } |
| 128 | |
| 129 | /// The bundled file of one of a family's faces. |
| 130 | static func url(_ family: DocsFontFamily, _ style: DocsFontFamily.Style) -> URL? { catalog.files[family.key + "/" + style.rawValue] } |
| 131 | |
| 132 | private nonisolated(unsafe) static var isRegistered = false |
| 133 | private static let registration = NSLock() |
| 134 | |
| 135 | /// Registers every bundled face for this process, synchronously. The |
| 136 | /// apps call it before their first window; font(...) calls it too, so |
| 137 | /// no layout can ever run ahead of it. Idempotent. |
| 138 | public static func register() { |
| 139 | registration.lock() |
| 140 | defer { registration.unlock() } |
| 141 | guard !isRegistered else { return } |
| 142 | for url in catalog.urls { |
| 143 | // Already registered (a second test host in one process) is fine: |
| 144 | // the faces are still resolved from their descriptors below. |
| 145 | CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil) |
| 146 | } |
| 147 | isRegistered = true |
| 148 | } |
| 149 | |
| 150 | /// The family a run with these marks is drawn in, as the web's |
| 151 | /// fontForMarks and internal/fonts' ForMarks decide it: code is always |
| 152 | /// the code family; otherwise the font mark latest in manifest order |
| 153 | /// wins; no font mark, or only marks this build does not know, is the |
| 154 | /// default. An unknown family (a newer build's) is Carlito everywhere, |
| 155 | /// on the web, in the PDF and here, and stays Carlito: it never swaps. |
| 156 | static func family(forMarks marks: [String: JSONValue]) -> DocsFontFamily { |
| 157 | if marks["code"] != nil { return catalog.code } |
| 158 | return family(forMarkNames: marks.keys) |
| 159 | } |
| 160 | |
| 161 | /// The font a selection shows, from the font marks active on it. |
| 162 | static func family<S: Sequence>(forMarkNames names: S) -> DocsFontFamily where S.Element == String { |
| 163 | var found: DocsFontFamily? |
| 164 | for name in names where name.hasPrefix("font_") { |
| 165 | if let family = catalog.byKey[String(name.dropFirst(5))], family.index > (found?.index ?? -1) { found = family } |
| 166 | } |
| 167 | return found ?? catalog.standard |
| 168 | } |
| 169 | |
| 170 | /// The mark a pick sets: nil for the default, which is spelled as the |
| 171 | /// absence of a font mark, so choosing Carlito clears the group. Sans |
| 172 | /// is font_sans, Liberation Sans, and is never the default. |
| 173 | static func mark(forPick key: String) -> String?? { |
| 174 | guard let family = catalog.byKey[key] else { return .none } |
| 175 | return .some(family.key == catalog.standard.key ? nil : family.mark) |
| 176 | } |
| 177 | |
| 178 | /// The face for a weight and slope. A family without the style keeps |
| 179 | /// the nearest it has, as internal/fonts' Face does: Caveat has no |
| 180 | /// italic and stays upright, on the web (font-synthesis: none), in the |
| 181 | /// PDF and here. |
| 182 | static func font(_ family: DocsFontFamily, bold: Bool, italic: Bool, size: CGFloat) -> DocsPlatformFont { |
| 183 | register() |
| 184 | let wanted: DocsFontFamily.Style = bold ? (italic ? .boldItalic : .bold) : (italic ? .italic : .regular) |
| 185 | let style = family.files[wanted] != nil ? wanted : family.files[bold ? .bold : .regular] != nil ? (bold ? .bold : .regular) : .regular |
| 186 | guard let descriptor = catalog.descriptors[family.key + "/" + style.rawValue] else { |
| 187 | fatalError("DocsFonts: \(family.key) has no \(style.rawValue) face") |
| 188 | } |
| 189 | return CTFontCreateWithFontDescriptor(descriptor, size, nil) as DocsPlatformFont |
| 190 | } |
| 191 | |
| 192 | /// The face a run is drawn in. |
| 193 | static func font(marks: [String: JSONValue], size baseSize: CGFloat, heading: Bool) -> DocsPlatformFont { |
| 194 | var size = baseSize |
| 195 | for key in marks.keys.sorted() where key.hasPrefix("size_") { |
| 196 | if let value = Double(key.dropFirst(5)), [8, 9, 10, 11, 12, 14, 18, 24, 36, 48, 72].contains(value) { size = value } |
| 197 | else if key == "size_sm" { size = 10 } |
| 198 | else if key == "size_lg" { size = 14 } |
| 199 | else if key == "size_xl" { size = 18 } |
| 200 | } |
| 201 | if marks["code"] != nil { size *= 0.85 } |
| 202 | return font(family(forMarks: marks), bold: marks["strong"] != nil || heading, italic: marks["em"] != nil, size: size) |
| 203 | } |
| 204 | |
| 205 | /// The default face at the document's body size, for an empty document's |
| 206 | /// caret and anything else that stands for document text. |
| 207 | static func defaultFont(size: CGFloat = 12) -> DocsPlatformFont { |
| 208 | font(catalog.standard, bold: false, italic: false, size: size) |
| 209 | } |
| 210 | |
| 211 | /// The family a pasted font stack stands for, deterministically, from the |
| 212 | /// shared list alone. The stack is read in order and the first name that |
| 213 | /// maps wins; a later name is only consulted when an earlier one maps to |
| 214 | /// nothing. Each name is matched exactly first, against Docs' private CSS |
| 215 | /// name ("Docs Inter", which text copied out of web Docs carries), then |
| 216 | /// each family's Word name and then its own name (the rule internal/fonts' ByDocxName |
| 217 | /// applies to .docx: Calibri is Carlito, Cambria is Caladea), and then |
| 218 | /// against the names each family stands in for, its fallback stack, in |
| 219 | /// picker order: Georgia is Caladea, Helvetica is Liberation Sans, Menlo |
| 220 | /// is JetBrains Mono, generic serif is Caladea. Nil when no name maps, |
| 221 | /// which is the default: an unknown face pastes as Carlito. The web's |
| 222 | /// familyForStack is the same rule; fixtures/vectors/font-stacks.json |
| 223 | /// holds the cases both are tested against. |
| 224 | static func family(cssStack stack: String) -> DocsFontFamily? { |
| 225 | let names = stack.split(separator: ",").map { |
| 226 | $0.trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters(in: CharacterSet(charactersIn: "\"'")).lowercased() |
| 227 | }.filter { !$0.isEmpty } |
| 228 | for name in names { |
| 229 | // A run copied out of web Docs names its private face first. |
| 230 | if let family = catalog.families.first(where: { ("docs " + $0.name).lowercased() == name }) |
| 231 | ?? catalog.families.first(where: { $0.docxName.lowercased() == name }) |
| 232 | ?? catalog.families.first(where: { $0.name.lowercased() == name }) |
| 233 | ?? catalog.families.first(where: { $0.fallback.contains { $0.lowercased() == name } }) { |
| 234 | return family |
| 235 | } |
| 236 | } |
| 237 | return nil |
| 238 | } |
| 239 | } |
| 240 | |