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