Sources/OrgstarMobile/MobileTheme.swift

156 lines · 7576 bytes

  1#if os(iOS)
  2import OrgPresentation
  3import SwiftUI
  4import UIKit
  5
  6/// Attributes for each style role, from a `ThemeSpec`, as the Mac editor's theme sets them.
  7@MainActor
  8struct MobileTheme {
  9    let spec: ThemeSpec
 10    /// The fixed-pitch font: columns, tables, code and the rest of `Presentation.isFixedPitch`.
 11    let font: UIFont
 12    /// The font for prose; `font` unless the theme names a body font.
 13    let body: UIFont
 14
 15    init(_ spec: ThemeSpec = .default) {
 16        self.spec = spec
 17        let size = CGFloat(max(6, spec.fontSize))
 18        // The theme's family when the device has it, else the monospaced system font; at the
 19        // theme's size for the default Dynamic Type size, scaled for others.
 20        let chosen = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? nil
 21            : UIFont(descriptor: UIFontDescriptor(fontAttributes: [.family: spec.font]), size: size)
 22        let metrics = UIFontMetrics(forTextStyle: .body)
 23        font = metrics.scaledFont(for: chosen ?? .monospacedSystemFont(ofSize: size, weight: .regular))
 24        body = switch spec.bodyFont {
 25        case "": font
 26        case "system": metrics.scaledFont(for: .systemFont(ofSize: size))
 27        case let family where !UIFont.fontNames(forFamilyName: family).isEmpty:
 28            metrics.scaledFont(for: UIFont(descriptor: UIFontDescriptor(fontAttributes: [.family: family]), size: size))
 29        default: font
 30        }
 31    }
 32
 33    /// Prose and fixed-pitch text use different fonts.
 34    var mixedPitch: Bool { body != font }
 35
 36    /// The fixed-pitch font at the size and weight of `current`.
 37    func fixedPitch(_ current: UIFont) -> UIFont {
 38        let sized = font.withSize(current.pointSize)
 39        return current.fontDescriptor.symbolicTraits.contains(.traitBold) ? Self.adding(.traitBold, to: sized) : sized
 40    }
 41
 42    /// A color that follows the appearance, or nil when the theme has none for `key`.
 43    func color(_ key: String) -> UIColor? {
 44        // As on the Mac: a key the theme has for one appearance only takes the default for the other.
 45        let light = spec.light[key] ?? ThemeSpec.default.light[key] ?? spec.dark[key]
 46        let dark = spec.dark[key] ?? ThemeSpec.default.dark[key] ?? spec.light[key]
 47        guard let light, let dark else { return nil }
 48        return Self.dynamic(light, dark)
 49    }
 50
 51    static func dynamic(_ light: RGBA, _ dark: RGBA) -> UIColor {
 52        UIColor { traits in
 53            let c = traits.userInterfaceStyle == .dark ? dark : light
 54            return UIColor(red: c.red, green: c.green, blue: c.blue, alpha: c.alpha)
 55        }
 56    }
 57
 58    var foreground: UIColor { color("foreground") ?? .label }
 59
 60    /// A TODO keyword's color: its own from `[theme.todo]`, else its class's (`todo-next`,
 61    /// `todo-waiting`, `todo-cancelled`, `todo`, `done`).
 62    func keywordColor(_ keyword: String, done: Bool) -> UIColor? {
 63        if let custom = spec.todo[keyword] { return Self.dynamic(custom, custom) }
 64        return color(ThemeSpec.TodoClass.of(keyword, isDone: done).key)
 65    }
 66
 67    /// A heading's font: larger by the heading step for levels 1 to 3, bold.
 68    func headingFont(_ level: Int) -> UIFont {
 69        let size = body.pointSize + CGFloat(max(0, spec.headingSizeStep) * max(0, 4 - level))
 70        return Self.adding(.traitBold, to: body.withSize(size))
 71    }
 72
 73    static func adding(_ traits: UIFontDescriptor.SymbolicTraits, to font: UIFont) -> UIFont {
 74        guard let descriptor = font.fontDescriptor.withSymbolicTraits(font.fontDescriptor.symbolicTraits.union(traits)) else { return font }
 75        return UIFont(descriptor: descriptor, size: font.pointSize)
 76    }
 77
 78    var base: [NSAttributedString.Key: Any] {
 79        [.font: body, .foregroundColor: foreground, .paragraphStyle: paragraphStyle(firstLine: 0, wrapped: 0)]
 80    }
 81
 82    /// Markup hidden from view: no width, no color.
 83    var hidden: [NSAttributedString.Key: Any] {
 84        [.font: UIFont.monospacedSystemFont(ofSize: 0.01, weight: .regular), .foregroundColor: UIColor.clear]
 85    }
 86
 87    /// Width of one column of the font.
 88    var column: CGFloat {
 89        ("0" as NSString).size(withAttributes: [.font: font]).width
 90    }
 91
 92    func paragraphStyle(firstLine: Int, wrapped: Int) -> NSParagraphStyle {
 93        let style = NSMutableParagraphStyle()
 94        style.firstLineHeadIndent = CGFloat(firstLine) * column
 95        style.headIndent = CGFloat(wrapped) * column
 96        style.lineSpacing = CGFloat(max(0, spec.lineSpacing))
 97        // `tab-width` 8, counted from the line's own start, past org-indent's indentation.
 98        style.defaultTabInterval = 8 * column
 99        style.tabStops = (1...32).map { NSTextTab(textAlignment: .left, location: style.firstLineHeadIndent + CGFloat($0 * 8) * column) }
100        return style
101    }
102
103    func apply(_ role: StyleRole, to storage: NSTextStorage, range: NSRange) {
104        func fg(_ key: String) {
105            if let color = color(key) { storage.addAttribute(.foregroundColor, value: color, range: range) }
106        }
107        func traits(_ add: UIFontDescriptor.SymbolicTraits) {
108            let current = storage.attribute(.font, at: range.location, effectiveRange: nil) as? UIFont ?? body
109            storage.addAttribute(.font, value: Self.adding(add, to: current), range: range)
110        }
111        if mixedPitch, Presentation.isFixedPitch(role) {
112            let current = storage.attribute(.font, at: range.location, effectiveRange: nil) as? UIFont ?? body
113            storage.addAttribute(.font, value: fixedPitch(current), range: range)
114        }
115        switch role {
116        case .heading(let level):
117            storage.addAttribute(.font, value: headingFont(level), range: range)
118            fg("heading-\(min(max(level, 1), 8))")
119        case .leadingStars:
120            storage.addAttribute(.foregroundColor, value: UIColor.clear, range: range)
121        case .todo, .done:
122            traits(.traitBold)
123            let keyword = (storage.string as NSString).substring(with: range)
124            if let color = keywordColor(keyword, done: role == .done) { storage.addAttribute(.foregroundColor, value: color, range: range) }
125        case .priority: fg("priority")
126        case .tags: fg("tags")
127        case .comment: fg("comment")
128        case .keyword: fg("keyword")
129        case .metadata: fg("metadata")
130        case .bold: traits(.traitBold)
131        case .italic: traits(.traitItalic)
132        case .underline: storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
133        case .strikeThrough: storage.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: range)
134        case .verbatim, .code, .inlineSource:
135            if let background = color("inline-background") { storage.addAttribute(.backgroundColor, value: background, range: range) }
136            fg(role == .verbatim ? "verbatim" : "code")
137        case .markup, .linkMarkup: fg("markup")
138        case .blockDelimiter: fg("block-delimiter")
139        case .link:
140            storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
141            fg("link")
142        case .timestamp: fg("timestamp")
143        case .footnote, .cookie, .target, .macro, .latex: fg("special")
144        case .table, .rule: fg("table")
145        case .block: break
146        case .syntax(let category):
147            if let key = category.themeKey { fg(key) }
148        }
149    }
150
151    // MARK: - SwiftUI
152
153    /// A theme color for SwiftUI views.
154    func swiftColor(_ key: String) -> Color? { color(key).map { Color(uiColor: $0) } }
155}
156#endif