Sources/OrgEditorAppKit/Theme.swift

8c221170c5ed1f01bcb7cabccac77177aa399d9a
orgstar/Sources/OrgEditorAppKit/Theme.swift history · blame · raw

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