Sources/OrgEditorAppKit/Theme.swift

157 lines · 7599 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    /// The fixed-pitch font: columns, tables, code and the rest of `Presentation.isFixedPitch`.
 10    let font: NSFont
 11    /// The font for prose; `font` unless the theme names a body font.
 12    let body: NSFont
 13
 14    init(_ spec: ThemeSpec = .default) {
 15        self.spec = spec
 16        let size = CGFloat(max(6, spec.fontSize))
 17        font = spec.font.isEmpty ? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
 18            : NSFontManager.shared.font(withFamily: spec.font, traits: [], weight: 5, size: size)
 19            ?? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
 20        body = switch spec.bodyFont {
 21        case "": font
 22        case "system": NSFont.systemFont(ofSize: size)
 23        case let family: NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: size) ?? font
 24        }
 25        Self.blockBackground = color("block-background") ?? .clear
 26    }
 27
 28    /// Prose and fixed-pitch text use different fonts.
 29    var mixedPitch: Bool { body != font }
 30
 31    /// The fixed-pitch font at the size and weight the text in `range` has.
 32    func fixedPitch(_ storage: NSTextStorage, _ range: NSRange) -> NSFont {
 33        let current = currentFont(storage, range)
 34        let sized = font.withSize(current.pointSize)
 35        return current.fontDescriptor.symbolicTraits.contains(.bold) ? NSFontManager.shared.convert(sized, toHaveTrait: .boldFontMask) : sized
 36    }
 37
 38    /// A color that follows the appearance, or nil when the theme has none for `key`.
 39    func color(_ key: String) -> NSColor? {
 40        // Editor colors are set for both appearances by the default theme; a key the theme
 41        // has for one only takes the default for the other.
 42        let light = spec.light[key] ?? ThemeSpec.default.light[key] ?? spec.dark[key]
 43        let dark = spec.dark[key] ?? ThemeSpec.default.dark[key] ?? spec.light[key]
 44        guard let light, let dark else { return nil }
 45        return Self.dynamic(light, dark)
 46    }
 47
 48    /// One color object per pair, so equal styling compares equal.
 49    private static var colors: [[RGBA]: NSColor] = [:]
 50
 51    static func dynamic(_ light: RGBA, _ dark: RGBA) -> NSColor {
 52        if let cached = colors[[light, dark]] { return cached }
 53        let color = NSColor(name: nil) { appearance in
 54            let c = appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua ? dark : light
 55            return NSColor(srgbRed: c.red, green: c.green, blue: c.blue, alpha: c.alpha)
 56        }
 57        colors[[light, dark]] = color
 58        return color
 59    }
 60
 61    var foreground: NSColor { color("foreground") ?? .textColor }
 62
 63    var base: [NSAttributedString.Key: Any] {
 64        [.font: body, .foregroundColor: foreground, .paragraphStyle: paragraphStyle(firstLine: 0, wrapped: 0)]
 65    }
 66
 67    /// Width of one column of the monospaced font.
 68    var column: CGFloat {
 69        ("0" as NSString).size(withAttributes: [.font: font]).width
 70    }
 71
 72    /// The band behind blocks, read by layout fragments off the main actor.
 73    nonisolated(unsafe) static var blockBackground = NSColor.clear
 74    /// The selection's color, which shaded block lines draw over their band.
 75    nonisolated(unsafe) static var selection = NSColor.selectedTextBackgroundColor
 76    /// Layout managers whose view has focus in the key window, for the selection's color.
 77    nonisolated(unsafe) static var focusedLayouts: Set<ObjectIdentifier> = []
 78
 79    /// Markup hidden from view: no width, no color.
 80    var hidden: [NSAttributedString.Key: Any] {
 81        [.font: NSFont.monospacedSystemFont(ofSize: 0.01, weight: .regular), .foregroundColor: NSColor.clear]
 82    }
 83
 84    func paragraphStyle(firstLine: Int, wrapped: Int) -> NSParagraphStyle {
 85        let style = NSMutableParagraphStyle()
 86        style.firstLineHeadIndent = CGFloat(firstLine) * column
 87        style.headIndent = CGFloat(wrapped) * column
 88        style.lineSpacing = CGFloat(max(0, spec.lineSpacing))
 89        // `tab-width` 8, counted from the line's own start, past org-indent's indentation.
 90        style.defaultTabInterval = 8 * column
 91        style.tabStops = (1...32).map { NSTextTab(textAlignment: .left, location: style.firstLineHeadIndent + CGFloat($0 * 8) * column) }
 92        return style
 93    }
 94
 95    func apply(_ role: StyleRole, to storage: NSTextStorage, range: NSRange) {
 96        func fg(_ key: String) {
 97            if let color = color(key) { storage.addAttribute(.foregroundColor, value: color, range: range) }
 98        }
 99        if mixedPitch, Presentation.isFixedPitch(role) {
100            storage.addAttribute(.font, value: fixedPitch(storage, range), range: range)
101        }
102        switch role {
103        case .heading(let level):
104            let size = body.pointSize + CGFloat(max(0, spec.headingSizeStep) * max(0, 4 - level))
105            let heading = NSFontManager.shared.convert(body.withSize(size), toHaveTrait: .boldFontMask)
106            storage.addAttribute(.font, value: heading, range: range)
107            fg("heading-\(min(max(level, 1), 8))")
108        case .leadingStars:
109            storage.addAttribute(.foregroundColor, value: NSColor.clear, range: range)
110        case .todo, .done:
111            let keyword = (storage.string as NSString).substring(with: range)
112            storage.addAttribute(.font, value: bold(storage, range), range: range)
113            if let custom = spec.todo[keyword] {
114                storage.addAttribute(.foregroundColor, value: Self.dynamic(custom, custom), range: range)
115            } else {
116                fg(ThemeSpec.TodoClass.of(keyword, isDone: role == .done).key)
117            }
118        case .priority: fg("priority")
119        case .tags: fg("tags")
120        case .comment: fg("comment")
121        case .keyword: fg("keyword")
122        case .metadata: fg("metadata")
123        case .bold:
124            storage.addAttribute(.font, value: bold(storage, range), range: range)
125        case .italic:
126            storage.addAttribute(.font, value: NSFontManager.shared.convert(currentFont(storage, range), toHaveTrait: .italicFontMask), range: range)
127        case .underline:
128            storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
129        case .strikeThrough:
130            storage.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: range)
131        case .verbatim, .code, .inlineSource:
132            if let background = color("inline-background") { storage.addAttribute(.backgroundColor, value: background, range: range) }
133            fg(role == .verbatim ? "verbatim" : "code")
134        case .markup, .linkMarkup: fg("markup")
135        case .blockDelimiter: fg("block-delimiter")
136        case .link:
137            storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
138            fg("link")
139        case .timestamp: fg("timestamp")
140        case .footnote, .cookie, .target, .macro, .latex: fg("special")
141        case .table, .rule: fg("table")
142        case .block:
143            break
144        case .syntax(let category):
145            if let key = category.themeKey { fg(key) }
146        }
147    }
148
149    private func currentFont(_ storage: NSTextStorage, _ range: NSRange) -> NSFont {
150        storage.attribute(.font, at: range.location, effectiveRange: nil) as? NSFont ?? body
151    }
152
153    private func bold(_ storage: NSTextStorage, _ range: NSRange) -> NSFont {
154        NSFontManager.shared.convert(currentFont(storage, range), toHaveTrait: .boldFontMask)
155    }
156}
157#endif