Files
byre/mac/Sources/Byre/Fonts.swift
T

53 lines
2.1 KiB
Swift
Raw Normal View History

import CoreText
import SwiftUI
enum Fonts {
nonisolated(unsafe) private static let descriptors: [String: CTFontDescriptor] = {
let dir = Bundle.main.resourceURL!.appendingPathComponent("fonts")
var out: [String: CTFontDescriptor] = [:]
for name in try! FileManager.default.contentsOfDirectory(atPath: dir.path) where name.hasSuffix(".woff2") {
let url = dir.appendingPathComponent(name)
let found = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as! [CTFontDescriptor]
out[name] = found[0]
}
return out
}()
private static func file(_ subset: String, _ italic: Bool, _ weight: CGFloat) -> CTFontDescriptor {
let d = descriptors["atkinson-hyperlegible-mono-\(subset)-wght-\(italic ? "italic" : "normal").woff2"]!
return CTFontDescriptorCreateCopyWithVariation(d, 0x7767_6874 as CFNumber, weight)
}
static func ct(_ size: CGFloat, weight: CGFloat = 400, italic: Bool = false) -> CTFont {
let ext = file("latin-ext", italic, weight)
let d = CTFontDescriptorCreateCopyWithAttributes(file("latin", italic, weight), [kCTFontCascadeListAttribute: [ext]] as CFDictionary)
return CTFontCreateWithFontDescriptor(d, size, nil)
}
2026-10-17 09:15:50 -07:00
nonisolated(unsafe) private static var fonts: [String: (font: Font, ns: NSFont)] = [:]
2026-10-16 23:30:57 -07:00
private static let lock = NSLock()
2026-10-17 09:15:50 -07:00
private static func cached(_ size: CGFloat, _ weight: CGFloat, _ italic: Bool) -> (font: Font, ns: NSFont) {
2026-10-16 23:30:57 -07:00
let key = "\(size) \(weight) \(italic)"
lock.lock()
defer {
lock.unlock()
}
if let f = fonts[key] {
return f
}
2026-10-17 09:15:50 -07:00
let c = ct(size, weight: weight, italic: italic)
let f = (Font(c), c as NSFont)
2026-10-16 23:30:57 -07:00
fonts[key] = f
return f
}
2026-10-17 09:15:50 -07:00
static func font(_ size: CGFloat, weight: CGFloat = 400, italic: Bool = false) -> Font {
cached(size, weight, italic).font
}
static func ns(_ size: CGFloat, weight: CGFloat = 400, italic: Bool = false) -> NSFont {
cached(size, weight, italic).ns
}
}