import CoreText import Foundation import HelderServices /// Registers the bundled IBM Plex faces for this process. CoreText reads WOFF2 directly. public enum FontRegistry { public static let resourceBundleName = "Helder_HelderUI.bundle" /// The Fonts folder, found without `Bundle.module`: its generated accessor looks next to /// the .app (not in Contents/Resources) and falls back to an absolute build path. public static func fontsDirectory() -> URL? { let fm = FileManager.default let candidates = [ Bundle.main.resourceURL, Bundle.main.bundleURL, Bundle.main.executableURL?.deletingLastPathComponent(), // Under `swift test` the code lives in an .xctest bundle beside the resource bundle. Bundle(for: BundleToken.self).bundleURL.deletingLastPathComponent(), ] for base in candidates.compactMap({ $0 }) { let fonts = base.appendingPathComponent(resourceBundleName).appendingPathComponent("Fonts") if fm.fileExists(atPath: fonts.path) { return fonts } let flat = base.appendingPathComponent(resourceBundleName).appendingPathComponent("Contents/Resources/Fonts") if fm.fileExists(atPath: flat.path) { return flat } } return nil } /// Registers every font file once; returns the PostScript names now available. Safe to call repeatedly. @discardableResult public static func registerBundledFonts() -> Set { lock.lock() defer { lock.unlock() } if let done = registered { return done } var names = Set() guard let dir = fontsDirectory(), let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) else { Log.warn("fonts", "bundled fonts not found; using the system fonts") registered = names return names } for url in files where ["woff2", "woff", "ttf", "otf"].contains(url.pathExtension.lowercased()) { var error: Unmanaged? let ok = CTFontManagerRegisterFontsForURL(url as CFURL, .process, &error) let already = (error?.takeRetainedValue()).map { CFErrorGetCode($0) == CTFontManagerError.alreadyRegistered.rawValue } ?? false if ok || already { let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor] ?? [] for d in descriptors { if let name = CTFontDescriptorCopyAttribute(d, kCTFontNameAttribute) as? String { names.insert(name) } } } else { Log.warn("fonts", "cannot register \(url.lastPathComponent)") } } Log.info("fonts", "registered \(names.sorted().joined(separator: ", "))") registered = names return names } private final class BundleToken {} private static let lock = NSLock() nonisolated(unsafe) private static var registered: Set? }