Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocLayout/Fonts.swift3// Description: Font resolution: family + weight + slant + size to a Core Text font, with the system designs (New York, SF) addressed by name4// and a record of the families that had to be substituted.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import AppKit10import CoreText11import DocModel1213public final class FontCache: @unchecked Sendable {14 public static let shared = FontCache()1516 private struct Key: Hashable { var family: String; var size: CGFloat; var weight: Int; var italic: Bool; var smallCaps: Bool }17 private var fonts: [Key: CTFont] = [:]18 private var missing = Set<String>()19 private let lock = NSLock()2021 /// Families that are system designs rather than installed font files.22 public static let systemFamilies = ["New York", "SF Pro", "SF Pro Display", "SF Pro Text", "SF Pro Rounded", "SF Mono"]2324 /// Families requested by a document that are not installed; text using them was drawn with a substitute.25 public var missingFamilies: [String] { lock.lock(); defer { lock.unlock() }; return missing.sorted() }2627 /// Every family the user can pick: installed families plus the system designs.28 public static func availableFamilies() -> [String] {29 let installed = (CTFontManagerCopyAvailableFontFamilyNames() as? [String] ?? []).filter { !$0.hasPrefix(".") }30 return Array(Set(installed + systemFamilies)).sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }31 }3233 static func nsWeight(_ w: Int) -> NSFont.Weight {34 switch w {35 case ..<150: return .ultraLight36 case ..<250: return .thin37 case ..<350: return .light38 case ..<450: return .regular39 case ..<550: return .medium40 case ..<650: return .semibold41 case ..<750: return .bold42 case ..<850: return .heavy43 default: return .black44 }45 }4647 static func ctWeight(_ w: Int) -> CGFloat {48 switch w {49 case ..<150: return -0.850 case ..<250: return -0.651 case ..<350: return -0.452 case ..<450: return 053 case ..<550: return 0.2354 case ..<650: return 0.355 case ..<750: return 0.456 case ..<850: return 0.5657 default: return 0.6258 }59 }6061 /// Installed family names, lower-cased. Read once: asking the font registry per family from many threads is slow and can stall.62 private static let installedFamilies: Set<String> = Set((CTFontManagerCopyAvailableFontFamilyNames() as? [String] ?? []).map { $0.lowercased() })6364 public func isInstalled(_ family: String) -> Bool {65 FontCache.systemFamilies.contains(family) || FontCache.installedFamilies.contains(family.lowercased())66 }6768 public func font(family: String, size: CGFloat, weight: Int = 400, italic: Bool = false, smallCaps: Bool = false) -> CTFont {69 let key = Key(family: family, size: size, weight: weight, italic: italic, smallCaps: smallCaps)70 lock.lock()71 if let f = fonts[key] { lock.unlock(); return f }72 lock.unlock()73 var font: CTFont74 if let design = FontCache.systemDesign(family) {75 var d = NSFont.systemFont(ofSize: size, weight: FontCache.nsWeight(weight)).fontDescriptor76 if let dd = d.withDesign(design) { d = dd }77 if italic { d = d.withSymbolicTraits(d.symbolicTraits.union(.italic)) }78 font = (NSFont(descriptor: d, size: size) ?? NSFont.systemFont(ofSize: size)) as CTFont79 } else {80 let installed = isInstalled(family)81 if !installed { lock.lock(); missing.insert(family); lock.unlock() }82 var symbolic: UInt32 = 083 if italic { symbolic |= CTFontSymbolicTraits.traitItalic.rawValue }84 if weight >= 600 { symbolic |= CTFontSymbolicTraits.traitBold.rawValue }85 let traits: [CFString: Any] = [kCTFontWeightTrait: FontCache.ctWeight(weight), kCTFontSymbolicTrait: symbolic]86 let attrs: [CFString: Any] = [kCTFontFamilyNameAttribute: installed ? family : "Times New Roman", kCTFontTraitsAttribute: traits]87 let desc = CTFontDescriptorCreateWithAttributes(attrs as CFDictionary)88 font = CTFontCreateWithFontDescriptor(desc, size, nil)89 // Families without a real italic get a synthetic slant so emphasis stays visible.90 if italic, !CTFontGetSymbolicTraits(font).contains(.traitItalic) {91 var m = CGAffineTransform(a: 1, b: 0, c: 0.2, d: 1, tx: 0, ty: 0)92 font = CTFontCreateCopyWithAttributes(font, size, &m, nil)93 }94 }95 if smallCaps {96 // OpenType small capitals for lowercase letters (feature type 37, selector 1), when the font has them.97 let desc = CTFontDescriptorCreateCopyWithFeature(CTFontCopyFontDescriptor(font), 37 as CFNumber, 1 as CFNumber)98 font = CTFontCreateWithFontDescriptor(desc, size, nil)99 }100 lock.lock()101 fonts[key] = font102 lock.unlock()103 return font104 }105106 static func systemDesign(_ family: String) -> NSFontDescriptor.SystemDesign? {107 switch family {108 case "New York": return .serif109 case "SF Pro", "SF Pro Display", "SF Pro Text", "System": return .default110 case "SF Pro Rounded": return .rounded111 case "SF Mono": return .monospaced112 default: return nil113 }114 }115116 private var nbspDelta: [String: CGFloat] = [:]117118 /// Difference between the advance of a space and that of a no-break space in `font` (0 for well-behaved fonts).119 func noBreakSpaceCorrection(_ font: CTFont) -> CGFloat {120 let key = "\(CTFontCopyPostScriptName(font) as String)-\(CTFontGetSize(font))"121 lock.lock()122 if let d = nbspDelta[key] { lock.unlock(); return d }123 lock.unlock()124 var chars: [UniChar] = [0x20, 0xA0]125 var glyphs: [CGGlyph] = [0, 0]126 var delta: CGFloat = 0127 if CTFontGetGlyphsForCharacters(font, &chars, &glyphs, 2), glyphs[0] != 0, glyphs[1] != 0 {128 var adv = [CGSize](repeating: .zero, count: 2)129 CTFontGetAdvancesForGlyphs(font, .horizontal, glyphs, &adv, 2)130 delta = adv[0].width - adv[1].width131 }132 lock.lock(); nbspDelta[key] = delta; lock.unlock()133 return delta134 }135136 public func font(for c: ResolvedChar, scale: CGFloat = 1) -> CTFont {137 let shrink: CGFloat = c.vertical == .baseline ? 1 : 0.66138 return font(family: c.fontFamily, size: max(1, c.fontSize * shrink * scale), weight: c.weight, italic: c.italic, smallCaps: c.smallCaps)139 }140}141142extension RGBA {143 public var cgColor: CGColor { CGColor(srgbRed: r, green: g, blue: b, alpha: a) }144}145