62 lines
2.8 KiB
Swift
62 lines
2.8 KiB
Swift
import CoreText
|
|
import Foundation
|
|
|
|
/// Registers the bundled OpenDyslexic faces for this process.
|
|
public enum FontRegistry {
|
|
public static let resourceBundleName = "Plak_PlakUI.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<String> {
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
if let done = registered { return done }
|
|
var names = Set<String>()
|
|
guard let dir = fontsDirectory(),
|
|
let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) else {
|
|
NSLog("plak: bundled fonts not found; using the system fonts")
|
|
registered = names
|
|
return names
|
|
}
|
|
for url in files where ["otf", "ttf"].contains(url.pathExtension.lowercased()) {
|
|
var error: Unmanaged<CFError>?
|
|
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 {
|
|
NSLog("plak: cannot register font %@", url.lastPathComponent)
|
|
}
|
|
}
|
|
registered = names
|
|
return names
|
|
}
|
|
|
|
private final class BundleToken {}
|
|
private static let lock = NSLock()
|
|
nonisolated(unsafe) private static var registered: Set<String>?
|
|
}
|