Sources/OrgPresentation/ThemeSpec.swift

363 lines · 18953 bytes

  1import OrgCore
  2
  3/// A color as `#rrggbb` or `#rrggbbaa`.
  4public struct RGBA: Hashable, Sendable {
  5    public var red, green, blue, alpha: Double
  6
  7    public init(red: Double, green: Double, blue: Double, alpha: Double = 1) {
  8        self.red = red
  9        self.green = green
 10        self.blue = blue
 11        self.alpha = alpha
 12    }
 13
 14    public init?(hex: String) {
 15        var digits = Substring(hex.trimmingCharacters(in: .whitespaces))
 16        guard digits.first == "#" else { return nil }
 17        digits = digits.dropFirst()
 18        guard digits.count == 6 || digits.count == 8, let value = UInt64(digits, radix: 16) else { return nil }
 19        let full = digits.count == 6 ? value << 8 | 0xFF : value
 20        red = Double(full >> 24 & 0xFF) / 255
 21        green = Double(full >> 16 & 0xFF) / 255
 22        blue = Double(full >> 8 & 0xFF) / 255
 23        alpha = Double(full & 0xFF) / 255
 24    }
 25
 26    public var hex: String {
 27        func byte(_ d: Double) -> String {
 28            let s = String(Int((d * 255).rounded()), radix: 16)
 29            return s.count == 1 ? "0" + s : s
 30        }
 31        return "#" + byte(red) + byte(green) + byte(blue) + (alpha < 1 ? byte(alpha) : "")
 32    }
 33}
 34
 35/// The editor's look: colors for each kind of text in light and dark appearance, colors for
 36/// TODO keywords and categories, and type. Read from `[theme]`, `[theme.light]`, `[theme.dark]`,
 37/// `[theme.todo]` and `[theme.category]` in config.toml, on top of the default theme.
 38public struct ThemeSpec: Equatable, Sendable {
 39    /// A font family; empty for the system's monospaced font.
 40    public var font = ""
 41    /// The font for prose: a family, `system` for the system's proportional font, or empty for
 42    /// `font` throughout. Tables, code and other `Presentation.isFixedPitch` text keep `font`.
 43    public var bodyFont = ""
 44    public var fontSize = 13
 45    /// Points between lines.
 46    public var lineSpacing = 2
 47    /// The widest the text runs, in columns of `font`, centred in a wider editor; 0 for the
 48    /// editor's whole width.
 49    public var textWidth = 0
 50    /// Points a heading is larger than the next level down (level 4 and deeper are body size).
 51    public var headingSizeStep = 1
 52    public var light: [String: RGBA]
 53    public var dark: [String: RGBA]
 54    /// `org-todo-keyword-faces`: a color per keyword, the same in both appearances.
 55    public var todo: [String: RGBA] = [:]
 56    /// A color per agenda category, the same in both appearances, over `categoryColor`'s hue.
 57    public var category: [String: RGBA] = [:]
 58
 59    public init(light: [String: RGBA], dark: [String: RGBA]) {
 60        self.light = light
 61        self.dark = dark
 62    }
 63
 64    public func color(_ key: String, dark isDark: Bool) -> RGBA? {
 65        (isDark ? dark : light)[key]
 66    }
 67
 68    // MARK: - Slots
 69
 70    /// Every color key, with what it colors.
 71    public static let slots: [(key: String, description: String)] = [
 72        ("background", "the editor's background"),
 73        ("foreground", "body text"),
 74        ("cursor", "the caret"),
 75        ("selection", "selected text's background"),
 76        ("accent", "buttons, toggles and selection in lists; unset: the system's"),
 77        ("heading-1", "level 1 headings"), ("heading-2", "level 2 headings"), ("heading-3", "level 3 headings"),
 78        ("heading-4", "level 4 headings"), ("heading-5", "level 5 headings"), ("heading-6", "level 6 headings"),
 79        ("heading-7", "level 7 headings"), ("heading-8", "level 8 and deeper headings"),
 80        ("todo", "TODO keywords not yet done"),
 81        ("todo-next", "keywords of work under way: NEXT, STRT, STARTED, DOING, ACTIVE"),
 82        ("todo-waiting", "keywords of work on hold: WAIT, WAITING, HOLD, BLOCKED, DEFERRED, SOMEDAY, MAYBE"),
 83        ("done", "DONE keywords"),
 84        ("todo-cancelled", "done keywords that cancel: KILL, CANCELLED, CANCELED, CANCEL, SKIPPED, SKIP, ABORTED, NO, WONTFIX"),
 85        ("priority", "[#A] cookies"),
 86        ("priority-a", "agenda: priority A"),
 87        ("priority-b", "agenda: priority B"),
 88        ("priority-c", "agenda: priority C"),
 89        ("tags", ":tags:"),
 90        ("link", "links"),
 91        ("timestamp", "timestamps"),
 92        ("code", "~code~ and inline source"),
 93        ("verbatim", "=verbatim="),
 94        ("inline-background", "behind ~code~ and =verbatim="),
 95        ("markup", "link brackets and emphasis markers"),
 96        ("comment", "comments"),
 97        ("keyword", "#+KEYWORD lines"),
 98        ("metadata", "planning lines, drawers, properties and clocks"),
 99        ("special", "footnotes, statistics cookies, targets, macros and LaTeX"),
100        ("block-background", "the band behind blocks"),
101        ("block-delimiter", "#+begin_ and #+end_ lines"),
102        ("table", "tables"),
103        ("line-number", "line numbers"),
104        ("line-number-current", "the caret's line number"),
105        ("syntax-keyword", "code: keywords"),
106        ("syntax-string", "code: strings"),
107        ("syntax-comment", "code: comments"),
108        ("syntax-function", "code: functions"),
109        ("syntax-type", "code: types and modules"),
110        ("syntax-number", "code: numbers, constants and escapes"),
111        ("syntax-property", "code: properties, attributes and tags"),
112        ("syntax-label", "code: labels"),
113        ("sidebar-background", "the folder sidebar and the outline; unset: the system's"),
114        ("sidebar-foreground", "file and heading names there; unset: the system's"),
115        ("sidebar-header", "folder names there; unset: the system's"),
116        ("modeline-background", "the modeline and message line; unset: the system's"),
117        ("modeline-foreground", "modeline text; unset: the system's"),
118        ("modeline-highlight", "the outline path and the clock in the modeline"),
119        ("state-normal", "the NORMAL tag"),
120        ("state-insert", "the INSERT tag"),
121        ("state-visual", "the VISUAL and V-LINE tags"),
122        ("agenda-background", "the agenda and board; unset: the system's"),
123        ("agenda-date", "agenda day headers"),
124        ("agenda-today", "today's header and the current time"),
125        ("agenda-time", "times and the time grid"),
126        ("agenda-category", "categories"),
127        ("agenda-overdue", "agenda: the status of entries past their deadline or scheduled date"),
128        ("agenda-due-soon", "agenda: the status of deadlines due today or coming up"),
129        ("agenda-event", "agenda: calendar events whose calendar has no color"),
130        ("habit-clear", "habit graph: not due yet"),
131        ("habit-ready", "habit graph: due"),
132        ("habit-alert", "habit graph: due today, last chance"),
133        ("habit-overdue", "habit graph: overdue"),
134    ]
135
136    /// Keys the default theme leaves to the system, so windows keep the macOS look.
137    public static let systemDefaults: Set<String> = [
138        "sidebar-background", "sidebar-foreground", "sidebar-header", "modeline-background", "modeline-foreground", "agenda-background",
139        "accent",
140    ]
141
142    // MARK: - The default theme
143
144    private static func palette(_ pairs: [String: String]) -> [String: RGBA] {
145        pairs.compactMapValues { RGBA(hex: $0) }
146    }
147
148    /// Calm colors after GitHub's light and dark themes for text and code: headings colored by
149    /// level, code in the colors developers know. Keywords, priorities and the agenda's states
150    /// use the system's accessible reds, oranges, blues and greens, so they match iOS and macOS.
151    public static let `default` = ThemeSpec(
152        light: palette([
153            "background": "#ffffff", "foreground": "#1f2328", "cursor": "#0969da", "selection": "#0969da33",
154            "heading-1": "#0550ae", "heading-2": "#8250df", "heading-3": "#116329", "heading-4": "#953800",
155            "heading-5": "#0550ae", "heading-6": "#8250df", "heading-7": "#116329", "heading-8": "#953800",
156            "todo": "#d70015", "done": "#248a3d", "priority": "#c93400", "tags": "#6e7781",
157            "todo-next": "#0a66d8", "todo-waiting": "#b25000", "todo-cancelled": "#8e8e93",
158            "priority-a": "#d70015", "priority-b": "#c93400", "priority-c": "#6c7a8c",
159            "link": "#0969da", "timestamp": "#8250df", "code": "#953800", "verbatim": "#0a3069", "inline-background": "#afb8c133",
160            "markup": "#8c959f", "comment": "#6e7781", "keyword": "#6e7781", "metadata": "#6e7781", "special": "#1b7c83",
161            "block-background": "#f6f8fa", "block-delimiter": "#8c959f", "table": "#1f2328",
162            "line-number": "#8c959f", "line-number-current": "#1f2328",
163            "syntax-keyword": "#cf222e", "syntax-string": "#0a3069", "syntax-comment": "#6e7781", "syntax-function": "#8250df",
164            "syntax-type": "#953800", "syntax-number": "#1b7c83", "syntax-property": "#0550ae", "syntax-label": "#8250df",
165            "modeline-highlight": "#1f2328", "state-normal": "#0969da", "state-insert": "#1a7f37", "state-visual": "#bc4c00",
166            "agenda-date": "#1f2328", "agenda-today": "#007aff", "agenda-time": "#6c6c70", "agenda-category": "#6c6c70",
167            "agenda-overdue": "#d70015", "agenda-due-soon": "#c93400", "agenda-event": "#8944ab",
168            "habit-clear": "#54aeff", "habit-ready": "#4ac26b", "habit-alert": "#d4a72c", "habit-overdue": "#ff8182",
169        ]),
170        dark: palette([
171            "background": "#0d1117", "foreground": "#e6edf3", "cursor": "#58a6ff", "selection": "#388bfd66",
172            "heading-1": "#79c0ff", "heading-2": "#d2a8ff", "heading-3": "#7ee787", "heading-4": "#ffa657",
173            "heading-5": "#79c0ff", "heading-6": "#d2a8ff", "heading-7": "#7ee787", "heading-8": "#ffa657",
174            "todo": "#ff6961", "done": "#30d158", "priority": "#ff9f0a", "tags": "#8b949e",
175            "todo-next": "#409cff", "todo-waiting": "#ffd60a", "todo-cancelled": "#8e8e93",
176            "priority-a": "#ff6961", "priority-b": "#ff9f0a", "priority-c": "#98a6b8",
177            "link": "#58a6ff", "timestamp": "#d2a8ff", "code": "#ffa657", "verbatim": "#a5d6ff", "inline-background": "#6e768166",
178            "markup": "#6e7681", "comment": "#8b949e", "keyword": "#8b949e", "metadata": "#8b949e", "special": "#56d4dd",
179            "block-background": "#161b22", "block-delimiter": "#6e7681", "table": "#e6edf3",
180            "line-number": "#6e7681", "line-number-current": "#e6edf3",
181            "syntax-keyword": "#ff7b72", "syntax-string": "#a5d6ff", "syntax-comment": "#8b949e", "syntax-function": "#d2a8ff",
182            "syntax-type": "#ffa657", "syntax-number": "#56d4dd", "syntax-property": "#79c0ff", "syntax-label": "#d2a8ff",
183            "modeline-highlight": "#e6edf3", "state-normal": "#1f6feb", "state-insert": "#238636", "state-visual": "#9e6a03",
184            "agenda-date": "#e6edf3", "agenda-today": "#0a84ff", "agenda-time": "#98989d", "agenda-category": "#98989d",
185            "agenda-overdue": "#ff6961", "agenda-due-soon": "#ff9f0a", "agenda-event": "#da8fff",
186            "habit-clear": "#1f6feb", "habit-ready": "#238636", "habit-alert": "#9e6a03", "habit-overdue": "#da3633",
187        ])
188    )
189
190    // MARK: - Reading
191
192    /// Keys of `[theme]` that aren't colors; config.toml's settings handle them.
193    public static let typeKeys: Set<String> = ["font", "body-font", "font-size", "line-spacing", "text-width", "heading-size-step", "theme-file", "light-theme", "dark-theme"]
194
195    /// Whether a table holds theme colors.
196    public static func isThemeTable(_ name: String) -> Bool {
197        name == "theme" || name.hasPrefix("theme.")
198    }
199
200    /// `base` with the colors of `tables` laid over it, in order; problems for keys and
201    /// values it can't use.
202    public static func reading(_ tables: [TOML.Table], over base: ThemeSpec = .default, file: String = "config.toml") -> (ThemeSpec, [String]) {
203        var spec = base
204        var problems: [String] = []
205        let known = Set(slots.map(\.key))
206        for table in tables where isThemeTable(table.name) {
207            for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
208                if table.name == "theme", typeKeys.contains(key) { continue }
209                guard let text = value.string, let color = RGBA(hex: text) else {
210                    problems.append("\(file): \(table.name).\(key) must be a color such as \"#1f2328\"")
211                    continue
212                }
213                switch table.name {
214                case "theme.todo":
215                    spec.todo[key] = color
216                case "theme.category":
217                    spec.category[key] = color
218                case "theme", "theme.light", "theme.dark":
219                    guard known.contains(key) else {
220                        problems.append("\(file): unknown theme color \(key)")
221                        continue
222                    }
223                    if table.name != "theme.dark" { spec.light[key] = color }
224                    if table.name != "theme.light" { spec.dark[key] = color }
225                default:
226                    problems.append("\(file): unknown table [\(table.name)]")
227                }
228            }
229        }
230        return (spec, problems)
231    }
232
233    /// The default theme written out, to copy colors from.
234    public static func defaultThemeFile() -> String {
235        var out = """
236            # orgstar's default theme, for reference: orgstar writes this file again each time it
237            # starts, so change colors in config.toml. A key set under [theme] colors both
238            # appearances; [theme.light] and [theme.dark] set one. Colors are "#rrggbb" or
239            # "#rrggbbaa". [theme.todo] colors TODO keywords by name, as org-todo-keyword-faces:
240            #
241            #   [theme.todo]
242            #   WAIT = "#bf8700"
243            #
244            # Otherwise a keyword takes its class's color: todo, todo-next, todo-waiting, done or
245            # todo-cancelled. [theme.category] colors agenda categories by name the same way;
246            # categories without one get a hue of their own from their name.
247            #
248            # A theme kept in its own file (with the same tables) is used with
249            # `theme-file = "name.toml"` under [theme] in config.toml.
250
251            """
252        for (name, colors) in [("theme.light", ThemeSpec.default.light), ("theme.dark", ThemeSpec.default.dark)] {
253            out += "\n[\(name)]\n"
254            for slot in slots {
255                guard let color = colors[slot.key] else {
256                    let line = "# \(slot.key) = \"#rrggbb\""
257                    out += line + String(repeating: " ", count: max(2, 36 - line.count)) + "# \(slot.description)\n"
258                    continue
259                }
260                let line = "\(slot.key) = \"\(color.hex)\""
261                out += line + String(repeating: " ", count: max(2, 36 - line.count)) + "# \(slot.description)\n"
262            }
263        }
264        return out
265    }
266}
267
268// MARK: - Agenda colors
269
270extension ThemeSpec {
271    /// The color classes of TODO keywords, by name: keywords of work under way and on hold,
272    /// and done keywords that cancel; the others are `todo` or `done`.
273    public enum TodoClass: String, Sendable {
274        case todo, next, waiting, done, cancelled
275
276        /// The theme key.
277        public var key: String {
278            switch self {
279            case .todo: "todo"
280            case .next: "todo-next"
281            case .waiting: "todo-waiting"
282            case .done: "done"
283            case .cancelled: "todo-cancelled"
284            }
285        }
286
287        static let nextWords: Set<String> = ["NEXT", "STRT", "STARTED", "START", "DOING", "ACTIVE", "INPROGRESS", "IN-PROGRESS"]
288        static let waitingWords: Set<String> = ["WAIT", "WAITING", "HOLD", "ONHOLD", "BLOCKED", "DEFERRED", "SOMEDAY", "MAYBE"]
289        static let cancelledWords: Set<String> = ["KILL", "KILLED", "CANCELLED", "CANCELED", "CANCEL", "SKIPPED", "SKIP", "ABORTED", "NO", "WONTFIX"]
290
291        public static func of(_ keyword: String, isDone: Bool) -> TodoClass {
292            let word = keyword.uppercased()
293            if isDone { return cancelledWords.contains(word) ? .cancelled : .done }
294            if nextWords.contains(word) { return .next }
295            if waitingWords.contains(word) { return .waiting }
296            return .todo
297        }
298    }
299
300    /// `[theme.todo]`'s color for the keyword, else its class's.
301    public func todoColor(_ keyword: String, isDone: Bool, dark isDark: Bool) -> RGBA? {
302        todo[keyword] ?? color(TodoClass.of(keyword, isDone: isDone).key, dark: isDark)
303    }
304
305    /// `priority-a`, `-b`, `-c`; `priority` for the others.
306    public func priorityColor(_ priority: String, dark isDark: Bool) -> RGBA? {
307        let key = ["A": "priority-a", "B": "priority-b", "C": "priority-c"][priority] ?? "priority"
308        return color(key, dark: isDark) ?? color("priority", dark: isDark)
309    }
310
311    /// The gutter's color: `agenda-overdue`, `agenda-due-soon`, `done`, else `agenda-time`.
312    public func statusColor(_ status: AgendaRow.Status, dark isDark: Bool) -> RGBA? {
313        switch status {
314        case .overdue: color("agenda-overdue", dark: isDark)
315        case .dueSoon: color("agenda-due-soon", dark: isDark)
316        case .done: color("done", dark: isDark)
317        case .normal: color("agenda-time", dark: isDark)
318        }
319    }
320
321    /// An event's calendar color, else `agenda-event`.
322    public func eventColor(_ event: AgendaEvent, dark isDark: Bool) -> RGBA? {
323        event.color ?? color("agenda-event", dark: isDark)
324    }
325
326    /// `[theme.category]`'s color for the category, else its hue (`categoryHue`) at a
327    /// saturation and lightness that read on the appearance's background.
328    public func categoryColor(_ name: String, dark isDark: Bool) -> RGBA {
329        if let set = category[name] { return set }
330        let hue = Self.categoryHue(name)
331        return isDark ? RGBA(hue: hue, saturation: 0.65, lightness: 0.70) : RGBA(hue: hue, saturation: 0.60, lightness: 0.40)
332    }
333
334    /// A hue in degrees from the category's name (FNV-1a of its UTF-8), the same on every run
335    /// and device.
336    public static func categoryHue(_ name: String) -> Double {
337        var hash: UInt32 = 2166136261
338        for byte in name.utf8 {
339            hash ^= UInt32(byte)
340            hash = hash &* 16777619
341        }
342        return Double(hash % 360)
343    }
344}
345
346extension RGBA {
347    /// From HSL: hue in degrees, saturation and lightness 0 to 1.
348    public init(hue: Double, saturation s: Double, lightness l: Double, alpha: Double = 1) {
349        let c = (1 - abs(2 * l - 1)) * s
350        let h = (hue.truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360) / 60
351        let x = c * (1 - abs(h.truncatingRemainder(dividingBy: 2) - 1))
352        let (r, g, b): (Double, Double, Double) = switch Int(h) {
353        case 0: (c, x, 0)
354        case 1: (x, c, 0)
355        case 2: (0, c, x)
356        case 3: (0, x, c)
357        case 4: (x, 0, c)
358        default: (c, 0, x)
359        }
360        let m = l - c / 2
361        self.init(red: r + m, green: g + m, blue: b + m, alpha: alpha)
362    }
363}