Sources/OrgEditorAppKit/Theme.swift

427abbbee0d20a70754de8e0e0846dae001f9c92
orgstar/Sources/OrgEditorAppKit/Theme.swift history · blame · raw

141 lines · 6169 bytes

  1#if os(macOS)
  2import AppKit
  3import OrgPresentation
  4
  5/// Attributes for each style role, from a `ThemeSpec`.
  6@MainActor
  7struct Theme {
  8    let spec: ThemeSpec
  9    let font: NSFont
 10
 11    init(_ spec: ThemeSpec = .default) {
 12        self.spec = spec
 13        let size = CGFloat(max(6, spec.fontSize))
 14        font = spec.font.isEmpty ? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
 15            : NSFontManager.shared.font(withFamily: spec.font, traits: [], weight: 5, size: size)
 16            ?? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
 17        Self.blockBackground = color("block-background") ?? .clear
 18    }
 19
 20    /// A color that follows the appearance, or nil when the theme has none for `key`.
 21    func color(_ key: String) -> NSColor? {
 22        let light = spec.light[key] ?? spec.dark[key]
 23        let dark = spec.dark[key] ?? spec.light[key]
 24        guard let light, let dark else { return nil }
 25        return Self.dynamic(light, dark)
 26    }
 27
 28    /// One color object per pair, so equal styling compares equal.
 29    private static var colors: [[RGBA]: NSColor] = [:]
 30
 31    static func dynamic(_ light: RGBA, _ dark: RGBA) -> NSColor {
 32        if let cached = colors[[light, dark]] { return cached }
 33        let color = NSColor(name: nil) { appearance in
 34            let c = appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua ? dark : light
 35            return NSColor(srgbRed: c.red, green: c.green, blue: c.blue, alpha: c.alpha)
 36        }
 37        colors[[light, dark]] = color
 38        return color
 39    }
 40
 41    var foreground: NSColor { color("foreground") ?? .textColor }
 42
 43    var base: [NSAttributedString.Key: Any] {
 44        [.font: font, .foregroundColor: foreground, .paragraphStyle: paragraphStyle(firstLine: 0, wrapped: 0)]
 45    }
 46
 47    /// Width of one column of the monospaced font.
 48    var column: CGFloat {
 49        ("0" as NSString).size(withAttributes: [.font: font]).width
 50    }
 51
 52    /// The band behind blocks, read by layout fragments off the main actor.
 53    nonisolated(unsafe) static var blockBackground = NSColor.clear
 54
 55    /// Markup hidden from view: no width, no color.
 56    var hidden: [NSAttributedString.Key: Any] {
 57        [.font: NSFont.monospacedSystemFont(ofSize: 0.01, weight: .regular), .foregroundColor: NSColor.clear]
 58    }
 59
 60    func paragraphStyle(firstLine: Int, wrapped: Int) -> NSParagraphStyle {
 61        let style = NSMutableParagraphStyle()
 62        style.firstLineHeadIndent = CGFloat(firstLine) * column
 63        style.headIndent = CGFloat(wrapped) * column
 64        style.lineSpacing = CGFloat(max(0, spec.lineSpacing))
 65        return style
 66    }
 67
 68    func apply(_ role: StyleRole, to storage: NSTextStorage, range: NSRange) {
 69        func fg(_ key: String) {
 70            if let color = color(key) { storage.addAttribute(.foregroundColor, value: color, range: range) }
 71        }
 72        switch role {
 73        case .heading(let level):
 74            let size = font.pointSize + CGFloat(max(0, spec.headingSizeStep) * max(0, 4 - level))
 75            let heading = NSFontManager.shared.convert(font.withSize(size), toHaveTrait: .boldFontMask)
 76            storage.addAttribute(.font, value: heading, range: range)
 77            fg("heading-\(min(max(level, 1), 8))")
 78        case .leadingStars:
 79            storage.addAttribute(.foregroundColor, value: NSColor.clear, range: range)
 80        case .todo, .done:
 81            let keyword = (storage.string as NSString).substring(with: range)
 82            storage.addAttribute(.font, value: bold(storage, range), range: range)
 83            if let custom = spec.todo[keyword] {
 84                storage.addAttribute(.foregroundColor, value: Self.dynamic(custom, custom), range: range)
 85            } else {
 86                fg(role == .todo ? "todo" : "done")
 87            }
 88        case .priority: fg("priority")
 89        case .tags: fg("tags")
 90        case .comment: fg("comment")
 91        case .keyword: fg("keyword")
 92        case .metadata: fg("metadata")
 93        case .bold:
 94            storage.addAttribute(.font, value: bold(storage, range), range: range)
 95        case .italic:
 96            storage.addAttribute(.font, value: NSFontManager.shared.convert(currentFont(storage, range), toHaveTrait: .italicFontMask), range: range)
 97        case .underline:
 98            storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
 99        case .strikeThrough:
100            storage.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: range)
101        case .verbatim, .code, .inlineSource:
102            if let background = color("inline-background") { storage.addAttribute(.backgroundColor, value: background, range: range) }
103            fg(role == .verbatim ? "verbatim" : "code")
104        case .markup, .linkMarkup: fg("markup")
105        case .blockDelimiter: fg("block-delimiter")
106        case .link:
107            storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
108            fg("link")
109        case .timestamp: fg("timestamp")
110        case .footnote, .cookie, .target, .macro, .latex: fg("special")
111        case .table, .rule: fg("table")
112        case .block:
113            break
114        case .syntax(let category):
115            if let key = Self.slot(category) { fg(key) }
116        }
117    }
118
119    static func slot(_ category: SyntaxCategory) -> String? {
120        switch category {
121        case .keyword: "syntax-keyword"
122        case .string: "syntax-string"
123        case .comment: "syntax-comment"
124        case .function: "syntax-function"
125        case .type: "syntax-type"
126        case .number, .constant, .escape: "syntax-number"
127        case .property, .attribute, .tag: "syntax-property"
128        case .label: "syntax-label"
129        case .variable, .operator, .punctuation: nil
130        }
131    }
132
133    private func currentFont(_ storage: NSTextStorage, _ range: NSRange) -> NSFont {
134        storage.attribute(.font, at: range.location, effectiveRange: nil) as? NSFont ?? font
135    }
136
137    private func bold(_ storage: NSTextStorage, _ range: NSRange) -> NSFont {
138        NSFontManager.shared.convert(currentFont(storage, range), toHaveTrait: .boldFontMask)
139    }
140}
141#endif