Cotton code
155 lines · 9.5 KB · SwiftRaw
// The faces the surface writes in. `sans` is Nunito Sans (SIL Open Font// Licence 1.1, bundled under Resources/Fonts with its licence): chosen over// Figtree and Clarity City, rendered side by side at the list's and the// editor's sizes, as the most readable of the three for long text — humanist// and open at small sizes, warm without being rounded, and the only one of// the three that covers Latin Extended, Cyrillic and Vietnamese. It is one// variable file per slope, so every weight comes from the same two files.// `serif`, `mono` and `system` are the phone's own designs. Cotton Notes// sets its words in `figtree` and its code in `jetbrains`, the faces its app// alone carries (`NotesFonts`). The faces Look offers in every redesigned app// (assets/design/shared/DECISIONS.md "Look"), carried by Words, Days, Comms// and Story from `assets/fonts/look` (the bundle's `look` folder): `literata` (a serif for long reading), `courier`// (Courier Prime, the typewriter), `atkinson` (Atkinson Hyperlegible Next) and// `opendyslexic`, each SIL OFL 1.1 with its licence beside it.#if canImport(UIKit)import CoreTextimport UIKitpublic enum WritingFonts {    /// The variable axis CoreText names weight by ('wght').    private static let weightAxis = 0x7767_6874    /// The bundled faces' PostScript names, upright and italic, once registered.    private static let bundled: (upright: String?, italic: String?) = {        func register(_ name: String) -> String? {            guard let url = Bundle.module.url(forResource: name, withExtension: "ttf", subdirectory: "Fonts") else { return nil }            CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)            let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor] ?? []            return descriptors.first.flatMap { CTFontDescriptorCopyAttribute($0, kCTFontNameAttribute) as? String }        }        return (register("NunitoSans"), register("NunitoSans-Italic"))    }()    /// Cotton Notes' own faces (assets/design/notes/DECISIONS.md "Look"),    /// carried by Notes alone in its app's `NotesFonts`: Figtree, one    /// variable file per slope, and JetBrains Mono at two weights.    private static let notes: (upright: String?, italic: String?, mono: String?, monoBold: String?) = {        func register(_ name: String) -> String? {            guard let url = Bundle.main.url(forResource: name, withExtension: "ttf", subdirectory: "NotesFonts") else { return nil }            CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)            let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor] ?? []            return descriptors.first.flatMap { CTFontDescriptorCopyAttribute($0, kCTFontNameAttribute) as? String }        }        return (register("Figtree"), register("Figtree-Italic"), register("JetBrainsMono-Regular"), register("JetBrainsMono-SemiBold"))    }()    /// Look's faces, once registered: each a PostScript name per style (nil where this app carries none).    private struct Styles { var upright: String?; var italic: String?; var bold: String?; var boldItalic: String? }    private static let look: [String: Styles] = {        func register(_ file: String) -> String? {            let name = (file as NSString).deletingPathExtension, ext = (file as NSString).pathExtension            guard let url = Bundle.main.url(forResource: name, withExtension: ext, subdirectory: "look") else { return nil }            CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)            let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor] ?? []            return descriptors.first.flatMap { CTFontDescriptorCopyAttribute($0, kCTFontNameAttribute) as? String }        }        return [            // Variable files: one per slope, the weight drawn from the axis.            "literata": Styles(upright: register("Literata.ttf"), italic: register("Literata-Italic.ttf")),            "atkinson": Styles(upright: register("AtkinsonHyperlegibleNext.ttf"), italic: register("AtkinsonHyperlegibleNext-Italic.ttf")),            // One file per style.            "courier": Styles(upright: register("CourierPrime-Regular.ttf"), italic: register("CourierPrime-Italic.ttf"),                              bold: register("CourierPrime-Bold.ttf"), boldItalic: register("CourierPrime-BoldItalic.ttf")),            "opendyslexic": Styles(upright: register("OpenDyslexic-Regular.otf"), italic: register("OpenDyslexic-Italic.otf"),                                   bold: register("OpenDyslexic-Bold.otf"), boldItalic: register("OpenDyslexic-BoldItalic.otf")),        ]    }()    /// Whether this build carries Look's face `id` (`literata`, `courier`, `atkinson`, `opendyslexic`).    public static func carries(_ id: String) -> Bool { look[id]?.upright != nil }    /// Whether Notes' faces are in this build.    public static var hasFigtree: Bool { notes.upright != nil }    /// Whether the bundled sans is in this build.    public static var hasSans: Bool { bundled.upright != nil }    /// A face at `size` points as the phone's text size scales it (the    /// largest accessibility size included), at `weight`, upright or italic.    public static func font(_ face: String, size: CGFloat, weight: UIFont.Weight = .regular, italic: Bool = false,                            traits: UITraitCollection? = nil, scaled: Bool = true) -> UIFont {        let base = unscaled(face, size: size, weight: weight, italic: italic)        guard scaled else { return base }        return UIFontMetrics(forTextStyle: .body).scaledFont(for: base, compatibleWith: traits)    }    static func unscaled(_ face: String, size: CGFloat, weight: UIFont.Weight, italic: Bool) -> UIFont {        switch face {        case "figtree":            if let name = italic ? notes.italic : notes.upright { return variable(name, size: size, weight: weight) }            return unscaled("sans", size: size, weight: weight, italic: italic)        case "jetbrains":            if let name = weight.rawValue >= UIFont.Weight.semibold.rawValue ? notes.monoBold : notes.mono {                return UIFont(name: name, size: size) ?? system(size: size, weight: weight, italic: italic, design: .monospaced)            }            return system(size: size, weight: weight, italic: italic, design: .monospaced)        case "sans":            if let name = italic ? bundled.italic : bundled.upright {                let wght = 400 + Double(weight.rawValue) * 500 // .regular 0 → 400, .bold 0.4 → 600, .heavy 0.56 → 680                let variation = UIFontDescriptor.AttributeName(rawValue: kCTFontVariationAttribute as String)                let descriptor = UIFontDescriptor(name: name, size: size).addingAttributes([variation: [weightAxis: Self.wght(weight, fallback: wght)]])                return UIFont(descriptor: descriptor, size: size)            }            return system(size: size, weight: weight, italic: italic, design: .default)        case "literata", "atkinson":            if let styles = look[face], let name = italic ? styles.italic : styles.upright { return variable(name, size: size, weight: weight) }            return system(size: size, weight: weight, italic: italic, design: face == "literata" ? .serif : .default)        case "courier", "opendyslexic":            if let styles = look[face] {                let heavy = weight.rawValue >= UIFont.Weight.semibold.rawValue                let name = italic ? (heavy ? styles.boldItalic : styles.italic) : (heavy ? styles.bold : styles.upright)                if let name, let font = UIFont(name: name, size: size) { return font }            }            return system(size: size, weight: weight, italic: italic, design: face == "courier" ? .monospaced : .default)        case "serif":            return system(size: size, weight: weight, italic: italic, design: .serif)        case "mono":            return system(size: size, weight: weight, italic: italic, design: .monospaced)        default:            return system(size: size, weight: weight, italic: italic, design: .default)        }    }    /// A variable face at the 'wght' a named weight stands for.    private static func variable(_ name: String, size: CGFloat, weight: UIFont.Weight) -> UIFont {        let variation = UIFontDescriptor.AttributeName(rawValue: kCTFontVariationAttribute as String)        let descriptor = UIFontDescriptor(name: name, size: size).addingAttributes([variation: [weightAxis: wght(weight, fallback: 400)]])        return UIFont(descriptor: descriptor, size: size)    }    /// The 'wght' value a named weight stands for.    private static func wght(_ weight: UIFont.Weight, fallback: Double) -> Double {        switch weight {        case .ultraLight: 200        case .thin: 250        case .light: 300        case .regular: 400        case .medium: 500        case .semibold: 600        case .bold: 700        case .heavy: 800        case .black: 900        default: fallback        }    }    private static func system(size: CGFloat, weight: UIFont.Weight, italic: Bool, design: UIFontDescriptor.SystemDesign) -> UIFont {        var descriptor = UIFont.systemFont(ofSize: size, weight: weight).fontDescriptor        if let designed = descriptor.withDesign(design) { descriptor = designed }        if italic, let slanted = descriptor.withSymbolicTraits(descriptor.symbolicTraits.union(.traitItalic)) { descriptor = slanted }        return UIFont(descriptor: descriptor, size: size)    }}#endif