Skip to main content

max / makeover

118.3 KB · 3115 lines History Blame Raw
1 //! Shared theme loading + intent resolution for TOML-based theme files.
2 //!
3 //! Used by GoingsOn, Balanced Breakfast (Tauri apps), audiofiles (egui), and the
4 //! MNW web server. Themes are authored by **intent** ("human design"): colors are
5 //! declared by role (surface / content / action / status / line / category), not
6 //! by hue. This crate is the single place that resolves an authored theme into a
7 //! full set of intent tokens — including the derived interactive states
8 //! (hover/active/selection/row-stripe/contrast) that each app used to recompute
9 //! itself — and emits them as CSS variables or RGB tuples.
10 //!
11 //! Theme file shape:
12 //! ```text
13 //! [meta]
14 //! name = "Nord"
15 //! variant = "dark" # or "light"
16 //!
17 //! [surface] # container backgrounds by role/elevation
18 //! page = "#2e3440"; raised = "#3b4252"; sunken = "#434c5e"; overlay = "#3b4252"
19 //!
20 //! [content] # the ink. Its emphasis steps are derived, not authored:
21 //! primary = "#d8dee9" # `content-secondary` and `content-muted` are tonal
22 //! # steps of this toward `surface.page`. See `Emphasis`.
23 //!
24 //! [action] # interactive / brand color
25 //! primary = "#81a1c1"
26 //!
27 //! [status] # state semantics
28 //! danger = "#bf616a"; success = "#a3be8c"; warning = "#ebcb8b"; info = "#88c0d0"
29 //!
30 //! [line]
31 //! border = "#4c566a"
32 //!
33 //! [category] # distinct decorative colors for tags/badges/charts
34 //! one = "#bf616a"; two = "#a3be8c"; three = "#81a1c1"
35 //! four = "#ebcb8b"; five = "#b48ead"; six = "#88c0d0"
36 //! ```
37
38 // Color-space math: single-letter channel names (r/g/b/l/m/s) and the published
39 // high-precision OKLab/sRGB matrix constants are the domain vocabulary here.
40 #![allow(clippy::many_single_char_names, clippy::unreadable_literal)]
41
42 use serde::Serialize;
43 use std::collections::{BTreeMap, HashMap};
44 use std::path::{Path, PathBuf};
45
46 /// The color sections an authored theme may declare.
47 pub const COLOR_SECTIONS: &[&str] = &["surface", "content", "action", "status", "line", "category"];
48
49 /// Theme metadata parsed from the `[meta]` section.
50 #[derive(Debug, Clone, Serialize)]
51 #[serde(rename_all = "camelCase")]
52 pub struct ThemeMeta {
53 pub id: String,
54 pub name: String,
55 pub variant: String,
56 pub is_custom: bool,
57 }
58
59 /// A loaded theme: metadata plus the authored colors, flattened to dotted keys
60 /// (e.g. `"surface.page"`, `"status.danger"`, `"category.one"`).
61 #[derive(Debug, Serialize)]
62 #[serde(rename_all = "camelCase")]
63 pub struct ThemeColors {
64 pub meta: ThemeMeta,
65 pub colors: HashMap<String, String>,
66 }
67
68 // ============================================================================
69 // Color math — perceptual (OKLab) derivations + WCAG contrast.
70 //
71 // Interactive states (hover/active/selection/surfaces) are derived in OKLab so
72 // equal steps look equal across every theme's hues (Ottosson 2020; the modern
73 // CIELAB). Text-on-color is picked by the WCAG 2.x contrast ratio, not a naive
74 // luminance threshold, so the choice actually meets AA where achievable.
75 // This is the single source of truth shared by every product.
76 // ============================================================================
77
78 /// An sRGB color. Hex round-trips losslessly.
79 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
80 pub struct Rgb {
81 pub r: u8,
82 pub g: u8,
83 pub b: u8,
84 }
85
86 impl Rgb {
87 /// Parse `#rgb` or `#rrggbb` (case-insensitive). Returns `None` otherwise.
88 pub fn from_hex(s: &str) -> Option<Rgb> {
89 let h = s.strip_prefix('#')?;
90 let (r, g, b) = match h.len() {
91 6 => (
92 u8::from_str_radix(&h[0..2], 16).ok()?,
93 u8::from_str_radix(&h[2..4], 16).ok()?,
94 u8::from_str_radix(&h[4..6], 16).ok()?,
95 ),
96 3 => {
97 let d = |c: &str| u8::from_str_radix(c, 16).ok().map(|v| v * 17);
98 (d(&h[0..1])?, d(&h[1..2])?, d(&h[2..3])?)
99 }
100 _ => return None,
101 };
102 Some(Rgb { r, g, b })
103 }
104
105 /// Lowercase `#rrggbb`.
106 pub fn to_hex(self) -> String {
107 format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
108 }
109
110 pub fn tuple(self) -> (u8, u8, u8) {
111 (self.r, self.g, self.b)
112 }
113 }
114
115 /// A color in OKLab (perceptually uniform): `l` lightness in [0,1], `a`/`b` opponent axes.
116 #[derive(Clone, Copy, Debug)]
117 pub struct Oklab {
118 pub l: f32,
119 pub a: f32,
120 pub b: f32,
121 }
122
123 fn srgb_to_linear(c: u8) -> f32 {
124 let c = c as f32 / 255.0;
125 if c <= 0.04045 {
126 c / 12.92
127 } else {
128 ((c + 0.055) / 1.055).powf(2.4)
129 }
130 }
131
132 fn linear_to_srgb(c: f32) -> u8 {
133 let c = c.clamp(0.0, 1.0);
134 let v = if c <= 0.0031308 {
135 c * 12.92
136 } else {
137 1.055 * c.powf(1.0 / 2.4) - 0.055
138 };
139 (v * 255.0).round().clamp(0.0, 255.0) as u8
140 }
141
142 impl Rgb {
143 /// Convert to OKLab (Ottosson's sRGB matrices).
144 ///
145 /// The matrix coefficients are quoted at their published precision so they
146 /// can be diffed against the reference. `f32` rounds them at compile time;
147 /// truncating the literals would only make them harder to check.
148 #[allow(clippy::excessive_precision)]
149 pub fn to_oklab(self) -> Oklab {
150 let (r, g, b) = (
151 srgb_to_linear(self.r),
152 srgb_to_linear(self.g),
153 srgb_to_linear(self.b),
154 );
155 let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
156 let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
157 let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
158 let (l_, m_, s_) = (l.cbrt(), m.cbrt(), s.cbrt());
159 Oklab {
160 l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
161 a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
162 b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
163 }
164 }
165
166 /// Convert from OKLab back to the nearest in-gamut sRGB.
167 ///
168 /// Published precision, as in [`Rgb::to_oklab`].
169 #[allow(clippy::excessive_precision)]
170 pub fn from_oklab(c: Oklab) -> Rgb {
171 let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b;
172 let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b;
173 let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b;
174 let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
175 Rgb {
176 r: linear_to_srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
177 g: linear_to_srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
178 b: linear_to_srgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s),
179 }
180 }
181 }
182
183 /// WCAG 2.x relative luminance of an sRGB color.
184 fn rel_luminance(c: Rgb) -> f32 {
185 0.2126 * srgb_to_linear(c.r) + 0.7152 * srgb_to_linear(c.g) + 0.0722 * srgb_to_linear(c.b)
186 }
187
188 /// WCAG 2.x contrast ratio between two colors, in [1, 21].
189 pub fn wcag_contrast(a: Rgb, b: Rgb) -> f32 {
190 let (la, lb) = (rel_luminance(a), rel_luminance(b));
191 let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
192 (hi + 0.05) / (lo + 0.05)
193 }
194
195 /// Pick black or white for legible text on `bg`, by the higher WCAG contrast
196 /// ratio (so the choice meets AA wherever the background allows it).
197 pub fn readable_on(bg: Rgb) -> Rgb {
198 let white = Rgb {
199 r: 255,
200 g: 255,
201 b: 255,
202 };
203 let black = Rgb { r: 0, g: 0, b: 0 };
204 if wcag_contrast(white, bg) >= wcag_contrast(black, bg) {
205 white
206 } else {
207 black
208 }
209 }
210
211 /// Shift OKLab lightness by `delta` (perceptually uniform). Positive lightens.
212 pub fn lighten(c: Rgb, delta: f32) -> Rgb {
213 let mut lab = c.to_oklab();
214 lab.l = (lab.l + delta).clamp(0.0, 1.0);
215 Rgb::from_oklab(lab)
216 }
217
218 /// Shift OKLab lightness down by `delta` (perceptually uniform).
219 pub fn darken(c: Rgb, delta: f32) -> Rgb {
220 lighten(c, -delta)
221 }
222
223 /// Interpolate between `a` and `b` by `t` in [0,1] in OKLab (perceptual blend).
224 pub fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb {
225 let (x, y) = (a.to_oklab(), b.to_oklab());
226 Rgb::from_oklab(Oklab {
227 l: x.l + (y.l - x.l) * t,
228 a: x.a + (y.a - x.a) * t,
229 b: x.b + (y.b - x.b) * t,
230 })
231 }
232
233 // ============================================================================
234 // Tonal steps
235 // ============================================================================
236
237 /// How far a tonal step sits from the token it is a step of.
238 ///
239 /// The named ratios. [`tonal`] is the same operation with the number written
240 /// out, and this is the small set of steps the vocabulary has agreed on, so a
241 /// consumer asking for "the muted form of this" names it rather than picking a
242 /// number and disagreeing with the next consumer to pick one.
243 ///
244 /// The rule these encode, stated as the three-tone convention:
245 ///
246 /// | step | what it means |
247 /// |------|---------------|
248 /// | [`Full`](Self::Full) | active, emphasised, the thing itself |
249 /// | [`Secondary`](Self::Secondary) | inactive but usable: a control that still answers |
250 /// | [`Muted`](Self::Muted) | inert: disabled, or not a control at all |
251 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252 pub enum Emphasis {
253 /// The token unchanged.
254 Full,
255 /// One step back. Still legible as content, not competing with `Full`.
256 Secondary,
257 /// Two steps back. Present, and saying it is not the point.
258 Muted,
259 }
260
261 impl Emphasis {
262 /// The fraction of the way to the ground this step travels.
263 ///
264 /// Both numbers are the shipped corpus' own, not invented: across the 31
265 /// bundled themes, hand-authored `content.secondary` sat at a median 0.115
266 /// of the way from `content.primary` to `surface.page`, and `content.muted`
267 /// at 0.424. So the derivation reproduces what theme authors converged on
268 /// by eye, and the themes that move are the ones that were off the cluster.
269 #[must_use]
270 pub const fn ratio(self) -> f32 {
271 match self {
272 Self::Full => 0.0,
273 Self::Secondary => 0.12,
274 Self::Muted => 0.42,
275 }
276 }
277
278 /// The suffix a derived token takes, or `None` for the token itself.
279 ///
280 /// `content` + [`Muted`](Self::Muted) is `content-muted`, which is the
281 /// naming every consumer already spells by hand. Grouping a family this way
282 /// is what makes `danger-muted` or `action-secondary` nameable without a
283 /// second table saying what they mean.
284 #[must_use]
285 pub const fn suffix(self) -> Option<&'static str> {
286 match self {
287 Self::Full => None,
288 Self::Secondary => Some("-secondary"),
289 Self::Muted => Some("-muted"),
290 }
291 }
292
293 /// The derived token key for `token` at this step.
294 #[must_use]
295 pub fn token(self, token: &str) -> String {
296 match self.suffix() {
297 Some(suffix) => format!("{token}{suffix}"),
298 None => token.to_string(),
299 }
300 }
301 }
302
303 /// A tonal step of `base`, `ratio` of the way toward the `ground` it is read
304 /// against.
305 ///
306 /// The numerical form of [`Emphasis`], for a consumer that wants a step the
307 /// named set does not have. `ratio` is clamped to [0,1]: past 1 the step is no
308 /// longer a step of `base` but a colour beyond the ground, which is a different
309 /// operation wearing this one's name.
310 ///
311 /// # Toward the ground, not toward grey
312 ///
313 /// A tonal step is a *reduction in contrast against what it is read on*, so it
314 /// interpolates toward the surface rather than desaturating or lightening. That
315 /// is why it takes two colours: lightening is wrong on a light theme and
316 /// darkening is wrong on a dark one, and mixing toward the ground is correct on
317 /// both without asking which theme this is. It is also why the ground is a
318 /// parameter rather than assumed — text in a well is read against the well.
319 ///
320 /// # It composes
321 ///
322 /// Two steps toward the same ground are one step toward that ground, since
323 /// OKLab interpolation is linear: `tonal(tonal(c, g, a), g, b)` is
324 /// `tonal(c, g, a + b - a*b)`. So a family can be derived recursively — the
325 /// muted form of a secondary is a well-defined colour and not a compounding
326 /// error — and re-deriving a token that was already derived is stable rather
327 /// than a slow slide into the background.
328 #[must_use]
329 pub fn tonal(base: Rgb, ground: Rgb, ratio: f32) -> Rgb {
330 mix(base, ground, ratio.clamp(0.0, 1.0))
331 }
332
333 /// A named tonal step of `base` against the `ground` it is read on.
334 ///
335 /// [`tonal`] with [`Emphasis::ratio`], and the form to reach for: the two
336 /// spellings of "muted" a pair of consumers pick independently are the drift
337 /// this replaces.
338 #[must_use]
339 pub fn emphasized(base: Rgb, ground: Rgb, emphasis: Emphasis) -> Rgb {
340 tonal(base, ground, emphasis.ratio())
341 }
342
343 // ============================================================================
344 // Low-color terminals
345 // ============================================================================
346
347 /// The 16 colors an ANSI terminal addresses by index, in the PC/VGA
348 /// arrangement the Linux console and most emulators start from.
349 ///
350 /// 0-7 are the normal colors and 8-15 the bright ones. Index 7 is a light gray
351 /// rather than white, which is the entry a themed surface usually lands on, and
352 /// index 15 is the true white.
353 ///
354 /// Emulators let the user repaint all sixteen, so this is the standard
355 /// arrangement rather than a promise about any one terminal. The Linux console
356 /// keeps it, which is the case that matters: a console app cannot fall back to
357 /// 24-bit color there.
358 pub const ANSI_16: [Rgb; 16] = [
359 Rgb {
360 r: 0x00,
361 g: 0x00,
362 b: 0x00,
363 },
364 Rgb {
365 r: 0xaa,
366 g: 0x00,
367 b: 0x00,
368 },
369 Rgb {
370 r: 0x00,
371 g: 0xaa,
372 b: 0x00,
373 },
374 Rgb {
375 r: 0xaa,
376 g: 0x55,
377 b: 0x00,
378 },
379 Rgb {
380 r: 0x00,
381 g: 0x00,
382 b: 0xaa,
383 },
384 Rgb {
385 r: 0xaa,
386 g: 0x00,
387 b: 0xaa,
388 },
389 Rgb {
390 r: 0x00,
391 g: 0xaa,
392 b: 0xaa,
393 },
394 Rgb {
395 r: 0xaa,
396 g: 0xaa,
397 b: 0xaa,
398 },
399 Rgb {
400 r: 0x55,
401 g: 0x55,
402 b: 0x55,
403 },
404 Rgb {
405 r: 0xff,
406 g: 0x55,
407 b: 0x55,
408 },
409 Rgb {
410 r: 0x55,
411 g: 0xff,
412 b: 0x55,
413 },
414 Rgb {
415 r: 0xff,
416 g: 0xff,
417 b: 0x55,
418 },
419 Rgb {
420 r: 0x55,
421 g: 0x55,
422 b: 0xff,
423 },
424 Rgb {
425 r: 0xff,
426 g: 0x55,
427 b: 0xff,
428 },
429 Rgb {
430 r: 0x55,
431 g: 0xff,
432 b: 0xff,
433 },
434 Rgb {
435 r: 0xff,
436 g: 0xff,
437 b: 0xff,
438 },
439 ];
440
441 /// The 256 colors an xterm-compatible terminal addresses by index, so that
442 /// entry `i` is what the terminal paints for `38;5;i`.
443 ///
444 /// Three regions, and they are not equally trustworthy. 0-15 are the [`ANSI_16`]
445 /// system colors, which every emulator lets the user repaint. 16-231 are a
446 /// 6x6x6 RGB cube and 232-255 a 24-step gray ramp, and those 240 are fixed.
447 ///
448 /// So a color whose whole job is to be told apart from another should quantize
449 /// against [`ANSI_240`] rather than against this table: a match landing in the
450 /// low sixteen is a match against a color the user may have moved.
451 pub const ANSI_256: [Rgb; 256] = build_ansi_256();
452
453 /// The fixed region of [`ANSI_256`]: the 6x6x6 cube and the gray ramp, without
454 /// the sixteen repaintable system colors.
455 ///
456 /// Quantizing against this returns an index into *this* slice; add
457 /// [`ANSI_240_OFFSET`] to get the index the terminal wants.
458 pub const ANSI_240: &[Rgb] = ANSI_256.split_at(16).1;
459
460 /// What to add to an [`ANSI_240`] index to get an [`ANSI_256`] one.
461 pub const ANSI_240_OFFSET: usize = 16;
462
463 /// The twelve chromatic ANSI slots, as the intents that paint them.
464 ///
465 /// Indexed 1-6 and 9-14. The hues do not depend on whether the theme is light
466 /// or dark, since red is the theme's danger tone either way, which is exactly
467 /// why the four achromatic slots are not in this table.
468 ///
469 /// Lifted from Alloy's `skelgen` on 2026-07-31, which had folded three
470 /// disagreeing hand-maintained copies into one and is the reason the
471 /// arrangement is trusted. It moved here so a program that paints its own
472 /// palette at runtime, rather than reading a generated config, resolves the
473 /// same slots. Slot 14 was the one the copies disagreed on and is
474 /// `category.six`, which both the Linux console table and the retired
475 /// `vtrgb.py` had.
476 const CHROMATIC: [(usize, &str); 12] = [
477 (1, "status.danger"),
478 (2, "status.success"),
479 (3, "status.warning"),
480 (4, "status.info"),
481 (5, "category.five"),
482 (6, "category.six"),
483 (9, "action.primary"), // bright red, the theme's warm accent
484 (10, "status.success"),
485 (11, "status.warning"),
486 (12, "status.info"),
487 (13, "category.five"),
488 (14, "category.six"),
489 ];
490
491 /// The four achromatic slots, 0, 7, 8 and 15, which invert with the theme.
492 ///
493 /// These are the slots a naive table gets wrong. ANSI 0 is "black" and 7 is
494 /// "white", but what a terminal wants there is *the darkest tone* and *the
495 /// lightest tone*, and which intent that is flips with the theme's polarity. A
496 /// light theme's darkest tone is its ink; a dark theme's is its deepest
497 /// surface. Pinning slot 0 to `content.primary` reads correctly on a light
498 /// theme and hands a dark one a pale cream as "black".
499 ///
500 /// Slot 7 is a surface and not a text tone, because it is what a program with
501 /// no way to name anything else draws its container on: a greeter's login card
502 /// is a light card on the darker field slot 0 paints.
503 ///
504 /// Anything that is not `dark`, including `high-contrast`, follows the light
505 /// anchors.
506 fn achromatic_slot(index: usize, variant: &str) -> Option<&'static str> {
507 let dark = variant == "dark";
508 Some(match (index, dark) {
509 (0, false) => "content.primary", // darkest text tone
510 (0, true) => "surface.sunken", // darkest surface
511 (7, false) => "surface.raised", // the login card
512 (7, true) => "content.secondary", // a readable light tone
513 (8, _) => "content.muted", // muted chrome, either way
514 (15, false) => "surface.overlay", // lightest surface
515 (15, true) => "content.primary", // lightest text tone
516 _ => return None,
517 })
518 }
519
520 /// The authored intent painting ANSI slot `index` under a theme of `variant`,
521 /// as a dotted key into [`ThemeColors::colors`].
522 ///
523 /// `None` for an index outside 0-15. Every slot in range resolves, so a caller
524 /// that has the intent can fill all sixteen.
525 ///
526 /// This is what makes a bare console, a terminal emulator and a generated
527 /// config agree on what red means. They disagreed for as long as each kept its
528 /// own table.
529 #[must_use]
530 pub fn ansi_intent(index: usize, variant: &str) -> Option<&'static str> {
531 achromatic_slot(index, variant).or_else(|| {
532 CHROMATIC
533 .iter()
534 .find(|(slot, _)| *slot == index)
535 .map(|(_, intent)| *intent)
536 })
537 }
538
539 const fn build_ansi_256() -> [Rgb; 256] {
540 let mut table = [Rgb { r: 0, g: 0, b: 0 }; 256];
541
542 let mut i = 0;
543 while i < 16 {
544 table[i] = ANSI_16[i];
545 i += 1;
546 }
547
548 // The cube's six levels are not evenly spaced. The step from black to the
549 // first is more than twice any later one, which is xterm's arrangement
550 // rather than a choice available here, and it is why the darkest tones a
551 // theme can reach on 256 colors come from the gray ramp instead.
552 const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
553 let mut r = 0;
554 while r < 6 {
555 let mut g = 0;
556 while g < 6 {
557 let mut b = 0;
558 while b < 6 {
559 table[16 + 36 * r + 6 * g + b] = Rgb {
560 r: LEVELS[r],
561 g: LEVELS[g],
562 b: LEVELS[b],
563 };
564 b += 1;
565 }
566 g += 1;
567 }
568 r += 1;
569 }
570
571 // 8 to 238 in steps of 10. Neither end is black or white; both of those are
572 // in the cube, so the ramp is 24 steps of gray between them rather than 24
573 // steps of the whole range.
574 let mut k = 0;
575 while k < 24 {
576 let v = 8 + 10 * k as u8;
577 table[232 + k as usize] = Rgb { r: v, g: v, b: v };
578 k += 1;
579 }
580
581 table
582 }
583
584 /// The contrast ratio two colors must clear to read as separate areas.
585 ///
586 /// WCAG 2.x asks 3:1 of user interface components and graphics, which is what
587 /// a border, a rule, or a focus ring is. Text wants more, and a caller drawing
588 /// text can ask for more by checking [`wcag_contrast`] itself.
589 pub const DISTINCT: f32 = 3.0;
590
591 /// Perceptual distance between two colors, for choosing the closest of a set.
592 fn oklab_distance(a: Rgb, b: Rgb) -> f32 {
593 let (x, y) = (a.to_oklab(), b.to_oklab());
594 ((x.l - y.l).powi(2) + (x.a - y.a).powi(2) + (x.b - y.b).powi(2)).sqrt()
595 }
596
597 /// Index of the entry in `palette` that looks most like `c`.
598 ///
599 /// OKLab distance rather than distance in sRGB, for the same reason [`mix`]
600 /// interpolates there: sRGB's numbers are not spaced the way seeing is, so a
601 /// nearest match computed in it picks visibly wrong entries in the mid tones.
602 ///
603 /// # Panics
604 ///
605 /// If `palette` is empty.
606 pub fn quantize(c: Rgb, palette: &[Rgb]) -> usize {
607 assert!(!palette.is_empty(), "a palette needs at least one color");
608 let mut best = 0;
609 let mut best_distance = f32::INFINITY;
610 for (index, entry) in palette.iter().enumerate() {
611 let distance = oklab_distance(c, *entry);
612 if distance < best_distance {
613 best = index;
614 best_distance = distance;
615 }
616 }
617 best
618 }
619
620 /// Index of the entry in `palette` closest to `fg` that still reads against
621 /// `bg`.
622 ///
623 /// [`quantize`] answers about one color at a time, and two colors that differ
624 /// can quantize to the same entry: a themed page and a border drawn on it are
625 /// often a few steps apart in a 24-bit theme and land together on a 16-color
626 /// terminal, leaving one flat area where there was a frame. Alloy's console
627 /// showed exactly this, and it is not a contrived pairing: a light page and the
628 /// mid-tone border derived from it both land on index 7.
629 ///
630 /// So the background is quantized first, because what the border must be
631 /// distinguished from is the entry the terminal will actually paint, not the
632 /// color the theme asked for. Then the nearest entry to `fg` clearing
633 /// [`DISTINCT`] against it wins. When nothing clears it, the entry that gets
634 /// furthest does: at that point the palette cannot honor the design, and the
635 /// most legible approximation beats the closest invisible one.
636 ///
637 /// Only for colors whose whole job is to be told apart from their background.
638 /// Applied to every token it would push a deliberately quiet one until it
639 /// shouted.
640 ///
641 /// # Panics
642 ///
643 /// If `palette` is empty.
644 pub fn quantize_against(fg: Rgb, bg: Rgb, palette: &[Rgb]) -> usize {
645 assert!(!palette.is_empty(), "a palette needs at least one color");
646 let shown = palette[quantize(bg, palette)];
647
648 let mut order: Vec<usize> = (0..palette.len()).collect();
649 order.sort_by(|a, b| {
650 oklab_distance(fg, palette[*a]).total_cmp(&oklab_distance(fg, palette[*b]))
651 });
652
653 order
654 .iter()
655 .copied()
656 .find(|index| wcag_contrast(palette[*index], shown) >= DISTINCT)
657 .unwrap_or_else(|| {
658 order
659 .iter()
660 .copied()
661 .max_by(|a, b| {
662 wcag_contrast(palette[*a], shown).total_cmp(&wcag_contrast(palette[*b], shown))
663 })
664 .expect("the palette is not empty")
665 })
666 }
667
668 // ============================================================================
669 // Intent resolution
670 // ============================================================================
671
672 /// Base intents: (TOML dotted source key, canonical token key). The token key
673 /// is the CSS-var stem (`--{token}`) and the `rgb()` lookup key.
674 ///
675 /// Read straight from the loaded theme, which is not quite the same as read
676 /// from the file: `content.secondary` and `content.muted` are tonal steps of
677 /// `content.primary` and are filled in at load by [`derive_tonal_steps`], so
678 /// they arrive here already computed and take this path like any other.
679 pub const BASE_INTENTS: &[(&str, &str)] = &[
680 ("surface.page", "surface-page"),
681 ("surface.raised", "surface-raised"),
682 ("surface.sunken", "surface-sunken"),
683 ("surface.overlay", "surface-overlay"),
684 ("content.primary", "content"),
685 ("content.secondary", "content-secondary"),
686 ("content.muted", "content-muted"),
687 ("action.primary", "action"),
688 ("status.danger", "danger"),
689 ("status.success", "success"),
690 ("status.warning", "warning"),
691 ("status.info", "info"),
692 ("line.border", "border"),
693 ("category.one", "category-one"),
694 ("category.two", "category-two"),
695 ("category.three", "category-three"),
696 ("category.four", "category-four"),
697 ("category.five", "category-five"),
698 ("category.six", "category-six"),
699 ];
700
701 /// A fully resolved intent layer: every token key → concrete `#rrggbb`.
702 /// Includes both authored base intents and the computed derived intents.
703 #[derive(Debug, Clone, Serialize)]
704 #[serde(rename_all = "camelCase")]
705 pub struct SemanticTokens {
706 pub meta: ThemeMeta,
707 /// token-key → resolved hex. Stable, deterministic ordering.
708 pub intents: BTreeMap<String, String>,
709 }
710
711 impl SemanticTokens {
712 /// Resolved hex for a token key, if present.
713 pub fn hex(&self, key: &str) -> Option<&str> {
714 self.intents.get(key).map(String::as_str)
715 }
716
717 /// Resolved RGB tuple for a token key (for egui / native consumers).
718 ///
719 /// `None` for a translucent token. Two intents are emitted as `rgba(...)`
720 /// rather than hex, `overlay` and `elevation`, and dropping the alpha would
721 /// hand a native consumer an opaque near-black where it asked for a scrim.
722 /// Those want [`rgba`](Self::rgba).
723 pub fn rgb(&self, key: &str) -> Option<(u8, u8, u8)> {
724 self.intents
725 .get(key)
726 .and_then(|h| Rgb::from_hex(h))
727 .map(Rgb::tuple)
728 }
729
730 /// Resolved RGBA tuple for a token key, alpha as 0-255.
731 ///
732 /// Reads both spellings, so a caller that does not care whether an intent
733 /// happens to be translucent can use this for everything: an opaque token
734 /// comes back at 255.
735 ///
736 /// It exists because a CSS consumer can take `rgba(...)` as a string
737 /// straight out of [`hex`](Self::hex) and a native one cannot. Without it
738 /// the two translucent intents are reachable from a stylesheet and from
739 /// nowhere else, which is the coupling deriving in the crate was meant to
740 /// avoid.
741 pub fn rgba(&self, key: &str) -> Option<(u8, u8, u8, u8)> {
742 let value = self.intents.get(key)?;
743 if let Some(rgb) = Rgb::from_hex(value) {
744 let (r, g, b) = rgb.tuple();
745 return Some((r, g, b, 255));
746 }
747 let inner = value.strip_prefix("rgba(")?.strip_suffix(')')?;
748 let mut parts = inner.split(',').map(str::trim);
749 let r = parts.next()?.parse().ok()?;
750 let g = parts.next()?.parse().ok()?;
751 let b = parts.next()?.parse().ok()?;
752 let alpha: f32 = parts.next()?.parse().ok()?;
753 if parts.next().is_some() || !(0.0..=1.0).contains(&alpha) {
754 return None;
755 }
756 Some((r, g, b, (alpha * 255.0).round() as u8))
757 }
758 }
759
760 /// Resolve an authored theme into the full intent token set.
761 ///
762 /// 1. Copy each present base intent from the authored colors.
763 /// 2. Compute the derived interactive states from the base intents, using the
764 /// same math the apps used to apply individually (so output is identical).
765 ///
766 /// Each derived token is emitted only when its source intents exist, mirroring
767 /// the skip-missing behavior of the rest of the crate.
768 pub fn resolve(theme: &ThemeColors) -> SemanticTokens {
769 let mut intents: BTreeMap<String, String> = BTreeMap::new();
770
771 // 1. Base intents (authored). Copy only values that parse as a hex color and
772 // re-emit them in canonical `#rrggbb` form, so an authored value can never
773 // carry arbitrary bytes into the emitted CSS (the resolved tokens are inlined
774 // raw into a `<style>` block by the web server). A malformed value is skipped,
775 // mirroring the skip-missing behavior for absent intents.
776 for (src, token) in BASE_INTENTS {
777 if let Some(rgb) = theme.colors.get(*src).and_then(|v| Rgb::from_hex(v)) {
778 intents.insert((*token).to_string(), rgb.to_hex());
779 }
780 }
781
782 // Helper: parse an already-resolved token to Rgb.
783 let get = |m: &BTreeMap<String, String>, k: &str| m.get(k).and_then(|h| Rgb::from_hex(h));
784
785 // 2. Derived intents — perceptual (OKLab) steps + WCAG-picked text.
786 // Lightness deltas are in OKLab L units; mix ratios interpolate in OKLab.
787 let mut derived: Vec<(String, Rgb)> = Vec::new();
788 if let Some(action) = get(&intents, "action") {
789 derived.push(("action-hover".into(), lighten(action, 0.05)));
790 derived.push(("content-on-action".into(), readable_on(action)));
791 // The focus ring is the action colour itself, not a tint of it: a ring
792 // is a statement that the keyboard is here, and a faded one reads as a
793 // disabled control rather than an emphatic one.
794 //
795 // One ring, not one per primitive. Where the ring sits is a depth
796 // question and not a per-component choice: a well takes it inside its
797 // own edge and a raised surface takes it outside. That is one decision
798 // with two renderings rather than one decision per component, which is
799 // how the three apps ended up with three rings. This token is the one
800 // shared artifact; which thing wears it, and how it is drawn, is each
801 // renderer's own (see `makeover_layout`'s crate header, "reach, focus
802 // and the focus ring").
803 derived.push(("focus-ring".into(), action));
804 }
805 if let Some(page) = get(&intents, "surface-page") {
806 // Modal scrim: a near-black tone carrying a faint hint of the theme's
807 // hue, at 50% alpha. Anchored very dark (OKLab L=0.08) so it dims the
808 // page on light *and* dark themes. Emitted as rgba (not a flat hex), so
809 // it is inserted directly rather than through the hex loop below.
810 let mut o = page.to_oklab();
811 o.l = 0.08;
812 let s = Rgb::from_oklab(o);
813 intents.insert(
814 "overlay".into(),
815 format!("rgba({}, {}, {}, 0.5)", s.r, s.g, s.b),
816 );
817
818 // What a surface that FLOATS OVER the page is cast onto it with.
819 //
820 // The one intent here about a surface's relationship to the page rather
821 // than about the surface itself, which is why it is derived from `page`
822 // and not from `surface-raised`. A shadow is not the thing, it is the
823 // absence of light on what is behind the thing.
824 //
825 // SCOPE, and it is the whole point of this intent existing rather than
826 // a general "shadow": a surface that overlays the page takes this, a
827 // surface IN the page takes a bevel. Menus, toasts, popovers and
828 // dropdowns overlay. A card, a plate and a framed image do not, and
829 // reaching for this on one of those is how a pre-Platinum look survives
830 // a conversion wearing a token's name. `.raised` is the answer there.
831 //
832 // Same anchor as the scrim above and for the same reason: a tone read
833 // off the theme's hue but pinned very dark, so it reads as absence of
834 // light on a light theme and on a dark one alike. A shadow tinted to a
835 // dark theme's own lightness would not be a shadow.
836 //
837 // The alpha is the only number here that is a look decision rather than
838 // a derivation. 0.18 sits between the two literal scales it replaces:
839 // the MNW server's --shadow-2 (0.10) reads as nothing under a menu, and
840 // its --shadow-3 (0.15) was measured invisible at plate size. Geometry
841 // stays with the consumer, the way bevel thickness does.
842 intents.insert(
843 "elevation".into(),
844 format!("rgba({}, {}, {}, 0.18)", s.r, s.g, s.b),
845 );
846 }
847 if let Some(raised) = get(&intents, "surface-raised") {
848 // The two edges of a bevel: a raised control is lit from the top left,
849 // so its top and left edges take `bevel-light` and its bottom and right
850 // edges `bevel-dark`. Inverting the pair gives a pressed state and an
851 // inset well, which is what makes the idiom cheap for a consumer.
852 //
853 // Derived here rather than composed per-app because the two webviews
854 // could do it in `color-mix()` and audiofiles, which is egui, could not.
855 // Geometry (thickness, radius, which side gets which) stays app-side.
856 //
857 // The deltas are asymmetric because the eye is: an equal step down reads
858 // as a smaller change than the same step up, so the shadow is cut deeper
859 // than the highlight is raised.
860 //
861 // A face already at the top of the ramp cannot hold a highlight — the
862 // lightening clamps and the control bevels on two sides without ever
863 // resolving as lit. That is a property of the theme, not of this
864 // derivation; `bevel_edges_are_distinct_from_their_face` names the
865 // shipped themes it currently bites.
866 derived.push(("bevel-light".into(), lighten(raised, 0.14)));
867 derived.push(("bevel-dark".into(), darken(raised, 0.18)));
868
869 // An inset well: the content surface inside a raised container, so a
870 // list reads as content in a container rather than as bands on a panel.
871 // `surface-sunken` cannot serve, because a theme is free to author it
872 // darker than raised (goingson does) and a well has to go the other way.
873 //
874 // Which way is "the other way" depends on the theme, and this is the one
875 // derivation here that inverts. A well is lighter than its face on a
876 // light theme and darker on a dark one, where the bevel pair sidesteps
877 // the question by emitting both directions at once.
878 //
879 // Read the direction off `content` rather than off `Variant`. A theme
880 // whose text is dark is a theme whose surfaces are light, whatever its
881 // `variant` field claims, so this resolves correctly even when that
882 // field is wrong and it keeps the branch on measured color rather than
883 // on metadata.
884 //
885 // Deltas are asymmetric for the same reason the bevel's are, and smaller
886 // than the bevel's because a well is an area rather than an edge. The
887 // step up is the specimen's, measured: #D9DDF4 to #F3F5FD is 0.069.
888 //
889 // A face at the top of its ramp cannot hold a lighter well, the same
890 // clamp `bevel-light` hits; `well_is_visible_against_its_face` names the
891 // shipped themes where it bites.
892 if let Some(content) = get(&intents, "content") {
893 let content_is_darker = content.to_oklab().l < raised.to_oklab().l;
894 let well = if content_is_darker {
895 lighten(raised, 0.07)
896 } else {
897 darken(raised, 0.09)
898 };
899 derived.push(("surface-well".into(), well));
900 }
901 }
902 if let Some(sunken) = get(&intents, "surface-sunken") {
903 derived.push(("hover-surface".into(), sunken));
904 }
905 if let Some(border) = get(&intents, "border") {
906 derived.push(("border-strong".into(), darken(border, 0.05)));
907 }
908
909 for (token, rgb) in derived {
910 intents.insert(token, rgb.to_hex());
911 }
912
913 SemanticTokens {
914 meta: theme.meta.clone(),
915 intents,
916 }
917 }
918
919 /// Emit the resolved intent layer as CSS declarations (no selector), one
920 /// ` --token: #hex;` line each, in deterministic (BTreeMap) order.
921 pub fn intent_css_declarations(tokens: &SemanticTokens) -> String {
922 let mut out = String::new();
923 for (token, hex) in &tokens.intents {
924 out.push_str(" --");
925 out.push_str(token);
926 out.push_str(": ");
927 out.push_str(hex);
928 out.push_str(";\n");
929 }
930 out
931 }
932
933 /// Emit the resolved intent layer as a `:root { … }` block — the single TOML →
934 /// CSS mapping every web surface injects.
935 pub fn intent_css_vars(tokens: &SemanticTokens) -> String {
936 format!(":root {{\n{}}}\n", intent_css_declarations(tokens))
937 }
938
939 // ============================================================================
940 // Typography — layer 1 of the house font model.
941 //
942 // Wiki `typography-standard`. The model is three layers: an app override, the
943 // house default, then a system generic, and this is the middle one. Two needs,
944 // two names, and no others in the suite:
945 //
946 // --font-mono Quasi Mono -> monospace
947 // --font-sans Quasi Body -> sans-serif
948 //
949 // Both are cut by `quasi-type` from the Atkinson Hyperlegible superfamily plus
950 // the house glyph set. This crate does not cut them and cannot: quasi-type is
951 // `publish = false` and makeover is on crates.io, so the cut lives in each
952 // consumer's own build script (`quasi_type::cut`, taken as a git dependency,
953 // the way `shop-font` does it). What lives here is the vocabulary, which is
954 // the half that was scattered.
955 //
956 // Font is not a theme's business and none of this is themeable. A theme
957 // declares colour by role; nothing in a theme file names a face, and the two
958 // tokens below are the same in every theme. That is why they are constants
959 // rather than another section of `SemanticTokens`, and why they belong in a
960 // stylesheet generated once at build time rather than in the block that gets
961 // re-injected on a theme switch.
962 //
963 // The brand/display tier is out of scope, per product and by decision: Young
964 // Serif on MNW, Reglo in GoingsOn, Departure Mono on Alloy, audiofiles' logo
965 // face. No renderer emits them and no described screen resolves a token to
966 // one, so they keep their own `font-family` until the app-override layer
967 // lands and gives them a place to be declared.
968 // ============================================================================
969
970 /// The mono slot: code, data, identifiers, cell grids, anything monospaced.
971 pub const FONT_MONO: &str = "\"Quasi Mono\", monospace";
972
973 /// The body / UI slot. Everything that is not the mono slot or brand tier.
974 pub const FONT_SANS: &str = "\"Quasi Body\", sans-serif";
975
976 /// Filename a consumer writes the cut mono face to, under its own font URL.
977 ///
978 /// `quasi-type` writes `QuasiMono[wght].woff2`, naming the variable axis the
979 /// way a font tool expects. Those brackets have to be percent-encoded to
980 /// survive a URL and are a bug waiting to be written, so the web copy takes a
981 /// plain name and the two places that have to agree — the build script that
982 /// writes the file and the `@font-face` that fetches it — agree through this
983 /// constant rather than by both spelling it out.
984 pub const WEBFONT_MONO_FILE: &str = "QuasiMono.woff2";
985
986 /// Filename a consumer writes the cut body face to. See [`WEBFONT_MONO_FILE`].
987 pub const WEBFONT_SANS_FILE: &str = "QuasiBody.woff2";
988
989 /// The house font tokens as CSS declarations (no selector), for a caller that
990 /// is composing its own block.
991 pub fn typography_css_declarations() -> String {
992 format!(" --font-mono: {FONT_MONO};\n --font-sans: {FONT_SANS};\n")
993 }
994
995 /// The house font tokens as a `:root { … }` block.
996 ///
997 /// Inlined by surfaces that cannot link a stylesheet — the MNW embeds are the
998 /// live case — and written to a file by everything else, through
999 /// `makeover_build::typography_css`.
1000 pub fn typography_css_vars() -> String {
1001 format!(":root {{\n{}}}\n", typography_css_declarations())
1002 }
1003
1004 /// The `@font-face` rules for both slots, fetching from `base_url`.
1005 ///
1006 /// `base_url` is the directory the consumer serves its fonts from, without a
1007 /// trailing slash: `/static/fonts` on the MNW server, `fonts` for a Tauri
1008 /// frontend loading relative to its index.
1009 ///
1010 /// # `font-weight: 200 800`, which is the part that bites
1011 ///
1012 /// Both faces are variable over `wght` 200-800 in one file, and the mono
1013 /// face's **default instance is ExtraLight** — that is upstream Atkinson's
1014 /// default and the cut keeps the axis rather than pinning a master, so a
1015 /// consumer that loads the file and takes what it opens at draws its whole UI
1016 /// at 200. Declaring the range here is what makes the browser resolve `normal`
1017 /// to 400 and `bold` to 700 instead. shop hit the same trap from the other
1018 /// side and names `wght` 400 explicitly in its shaper; this is the web's
1019 /// version of that fix, stated once for every consumer.
1020 ///
1021 /// `font-display: swap` on both: the faces are 31KB and 50KB, they are cached
1022 /// hard after the first paint, and a flash of the fallback beats invisible
1023 /// text either way.
1024 pub fn font_face_css(base_url: &str) -> String {
1025 use std::fmt::Write as _;
1026
1027 let base = base_url.trim_end_matches('/');
1028 let mut out = String::new();
1029 for (family, file) in [
1030 ("Quasi Mono", WEBFONT_MONO_FILE),
1031 ("Quasi Body", WEBFONT_SANS_FILE),
1032 ] {
1033 let _ = write!(
1034 out,
1035 "@font-face {{\n \
1036 font-family: \"{family}\";\n \
1037 src: url(\"{base}/{file}\") format(\"woff2\");\n \
1038 font-weight: 200 800;\n \
1039 font-style: normal;\n \
1040 font-display: swap;\n\
1041 }}\n\n"
1042 );
1043 }
1044 out
1045 }
1046
1047 // ============================================================================
1048 // Loading / parsing
1049 // ============================================================================
1050
1051 /// Validate a theme ID contains only safe characters (alphanumeric, hyphens, underscores).
1052 pub fn validate_theme_id(id: &str) -> Result<(), String> {
1053 if !id
1054 .chars()
1055 .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
1056 {
1057 return Err(format!("Invalid theme ID: {id}"));
1058 }
1059 Ok(())
1060 }
1061
1062 /// Parse the `[meta]` section into `ThemeMeta`.
1063 ///
1064 /// Falls back to the file ID as the name and `"dark"` as the variant.
1065 pub fn parse_meta(id: &str, table: &toml::Table, is_custom: bool) -> ThemeMeta {
1066 let meta = table.get("meta").and_then(|m| m.as_table());
1067 let name = meta
1068 .and_then(|m| m.get("name"))
1069 .and_then(|v| v.as_str())
1070 .unwrap_or(id)
1071 .to_string();
1072 let variant = meta
1073 .and_then(|m| m.get("variant"))
1074 .and_then(|v| v.as_str())
1075 .unwrap_or("dark")
1076 .to_string();
1077
1078 ThemeMeta {
1079 id: id.to_string(),
1080 name,
1081 variant,
1082 is_custom,
1083 }
1084 }
1085
1086 // ============================================================================
1087 // Choosing a theme.
1088 //
1089 // The file half of this crate was always shared; the *selection* half was not,
1090 // and four apps re-rolled it four ways. GoingsOn stores a "system" sentinel in
1091 // localStorage, Balanced Breakfast treats an absent value as follow-the-system
1092 // and hardcodes two theme ids as its light/dark pair, audiofiles keeps the id
1093 // in a synced SQLite table, and the Alloy console parses COLORFGBG. They also
1094 // disagreed about what a variant string means: this crate defaults a missing
1095 // one to "dark" while alloy_tui parsed an unrecognized one as light.
1096 //
1097 // What cannot be shared is the store — localStorage, a synced config table and
1098 // a TOML file are genuinely different places. What can be shared, and is here,
1099 // is the *meaning*: one vocabulary for variants, one encoding for "what did the
1100 // user choose", and one rule for turning that into an id that exists.
1101 // ============================================================================
1102
1103 /// A theme's kind, as declared by `meta.variant`.
1104 ///
1105 /// Three, not two: one shipped theme is `high-contrast`, and an app that
1106 /// matched on light-or-dark alone would quietly file it under the wrong one.
1107 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
1108 #[serde(rename_all = "kebab-case")]
1109 pub enum Variant {
1110 Light,
1111 Dark,
1112 HighContrast,
1113 }
1114
1115 impl Variant {
1116 /// The spelling used in a theme file and in [`ThemeMeta::variant`].
1117 #[must_use]
1118 pub const fn as_str(self) -> &'static str {
1119 match self {
1120 Variant::Light => "light",
1121 Variant::Dark => "dark",
1122 Variant::HighContrast => "high-contrast",
1123 }
1124 }
1125
1126 /// Read a variant string, or `None` if it names none of them.
1127 #[must_use]
1128 pub fn parse(raw: &str) -> Option<Self> {
1129 match raw {
1130 "light" => Some(Variant::Light),
1131 "dark" => Some(Variant::Dark),
1132 "high-contrast" => Some(Variant::HighContrast),
1133 _ => None,
1134 }
1135 }
1136 }
1137
1138 impl std::fmt::Display for Variant {
1139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1140 f.write_str(self.as_str())
1141 }
1142 }
1143
1144 /// Anything unrecognized reads as dark, which is what [`parse_meta`] already
1145 /// does with a missing one. Consumers that guessed light for an unknown string
1146 /// were disagreeing with the crate that produced it.
1147 impl From<&str> for Variant {
1148 fn from(raw: &str) -> Self {
1149 Variant::parse(raw).unwrap_or(Variant::Dark)
1150 }
1151 }
1152
1153 impl ThemeMeta {
1154 /// This theme's variant as a value rather than a string.
1155 #[must_use]
1156 pub fn kind(&self) -> Variant {
1157 Variant::from(self.variant.as_str())
1158 }
1159 }
1160
1161 /// The spelling of "follow whatever the system is doing", in every store.
1162 pub const FOLLOW: &str = "system";
1163
1164 /// What the user chose, as opposed to what is being rendered.
1165 ///
1166 /// The distinction is the whole point: `Follow` is a standing instruction that
1167 /// resolves differently as the ambient mode changes, and a `Fixed` id is an
1168 /// answer that does not. An app that stored only the rendered id could not tell
1169 /// the two apart the next time the system flipped to dark.
1170 #[derive(Debug, Clone, PartialEq, Eq, Default)]
1171 pub enum ThemeSelection {
1172 /// Track the ambient light/dark mode.
1173 #[default]
1174 Follow,
1175 /// Always this theme.
1176 Fixed(String),
1177 }
1178
1179 impl ThemeSelection {
1180 /// Read a stored selection. An empty or absent value is [`Follow`], which
1181 /// is what an app with nothing saved yet should do.
1182 ///
1183 /// [`Follow`]: ThemeSelection::Follow
1184 #[must_use]
1185 pub fn parse(raw: Option<&str>) -> Self {
1186 match raw.map(str::trim) {
1187 None | Some("" | FOLLOW) => ThemeSelection::Follow,
1188 Some(id) => ThemeSelection::Fixed(id.to_string()),
1189 }
1190 }
1191
1192 /// The string to persist, whatever the store is.
1193 #[must_use]
1194 pub fn as_str(&self) -> &str {
1195 match self {
1196 ThemeSelection::Follow => FOLLOW,
1197 ThemeSelection::Fixed(id) => id,
1198 }
1199 }
1200
1201 /// Turn a selection into a theme id that exists.
1202 ///
1203 /// `ambient` is the light/dark mode the app learned however it can: a
1204 /// `prefers-color-scheme` media query, an OS appearance API, `COLORFGBG`
1205 /// from a terminal. `available` is what [`list_themes_from_dirs`] found.
1206 ///
1207 /// A `Fixed` id that is no longer on disk falls through to the same path as
1208 /// `Follow` rather than being returned anyway. Themes are deletable in
1209 /// three of the four apps, and handing back an id that will fail to load
1210 /// only moves the error somewhere less helpful.
1211 ///
1212 /// The fallback chain is: the app's own default for the ambient mode if it
1213 /// is installed, then any installed theme of that variant, then the app's
1214 /// default regardless. The last step means this always returns something,
1215 /// and an app with no theme directory at all gets the id it ships with and
1216 /// the load error it would have had anyway.
1217 #[must_use]
1218 pub fn resolve(
1219 &self,
1220 ambient: Variant,
1221 defaults: &ThemeDefaults,
1222 available: &[ThemeMeta],
1223 ) -> String {
1224 let installed = |id: &str| available.iter().any(|meta| meta.id == id);
1225
1226 if let ThemeSelection::Fixed(id) = self
1227 && installed(id)
1228 {
1229 return id.clone();
1230 }
1231
1232 let preferred = defaults.for_variant(ambient);
1233 if installed(preferred) {
1234 return preferred.to_string();
1235 }
1236 available
1237 .iter()
1238 .find(|meta| meta.kind() == ambient)
1239 .map_or_else(|| preferred.to_string(), |meta| meta.id.clone())
1240 }
1241 }
1242
1243 impl std::fmt::Display for ThemeSelection {
1244 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1245 f.write_str(self.as_str())
1246 }
1247 }
1248
1249 /// The themes an app falls back to, one per ambient mode.
1250 ///
1251 /// App-specific on purpose: which theme is "the app's own" is the app's
1252 /// identity, not this crate's business. What is shared is everything around it.
1253 #[derive(Debug, Clone)]
1254 pub struct ThemeDefaults {
1255 light: String,
1256 dark: String,
1257 high_contrast: Option<String>,
1258 }
1259
1260 impl ThemeDefaults {
1261 pub fn new(light: impl Into<String>, dark: impl Into<String>) -> Self {
1262 Self {
1263 light: light.into(),
1264 dark: dark.into(),
1265 high_contrast: None,
1266 }
1267 }
1268
1269 /// Name a theme for a high-contrast ambient mode. Without one, that mode
1270 /// falls back to the dark default, which is the safer of the two to read.
1271 #[must_use]
1272 pub fn high_contrast(mut self, id: impl Into<String>) -> Self {
1273 self.high_contrast = Some(id.into());
1274 self
1275 }
1276
1277 #[must_use]
1278 pub fn for_variant(&self, variant: Variant) -> &str {
1279 match variant {
1280 Variant::Light => &self.light,
1281 Variant::Dark => &self.dark,
1282 Variant::HighContrast => self.high_contrast.as_ref().unwrap_or(&self.dark),
1283 }
1284 }
1285 }
1286
1287 // ============================================================================
1288 // Where themes are looked for.
1289 //
1290 // Four apps built this vector by hand, two of them byte-for-byte identically,
1291 // and one of them built it backwards: the Alloy console pushed the user's own
1292 // directory first, under a comment saying "highest precedence first", when both
1293 // consumers of the vector resolve *last* wins. A user's custom theme lost to
1294 // the packaged one of the same id.
1295 //
1296 // Hence a builder that names the tiers rather than a function taking a vector.
1297 // The precedence is stated once, here, and a caller cannot express it backwards
1298 // because the order is not theirs to choose.
1299 // ============================================================================
1300
1301 /// Builds the search path [`load_theme`] and [`list_themes_from_dirs`] take.
1302 ///
1303 /// Tiers are added in whatever order is convenient and always end up in
1304 /// precedence order: the user's own themes win, then whatever the system
1305 /// ships, then whatever the app bundles.
1306 ///
1307 /// A directory that does not exist is dropped rather than carried, so callers
1308 /// can offer every tier they might have without checking each one.
1309 #[derive(Debug, Default, Clone)]
1310 pub struct ThemeDirs {
1311 bundled: Vec<PathBuf>,
1312 system: Vec<PathBuf>,
1313 custom: Option<PathBuf>,
1314 }
1315
1316 impl ThemeDirs {
1317 #[must_use]
1318 pub fn new() -> Self {
1319 Self::default()
1320 }
1321
1322 /// Themes the app ships with. Lowest precedence.
1323 ///
1324 /// Takes more than one because a Tauri app has two: the bundled resource
1325 /// directory in production, and the tree `build.rs` materialized for a
1326 /// `cargo run` that has no resource directory at all.
1327 #[must_use]
1328 pub fn bundled(mut self, dir: Option<PathBuf>) -> Self {
1329 self.bundled.extend(dir);
1330 self
1331 }
1332
1333 /// Themes the machine ships, from an image or a package. Overrides bundled.
1334 #[must_use]
1335 pub fn system(mut self, dir: Option<PathBuf>) -> Self {
1336 self.system.extend(dir);
1337 self
1338 }
1339
1340 /// The user's own themes. Highest precedence, and the only tier flagged
1341 /// custom, which is what makes them exportable and deletable.
1342 #[must_use]
1343 pub fn custom(mut self, dir: Option<PathBuf>) -> Self {
1344 self.custom = dir;
1345 self
1346 }
1347
1348 /// The search path, lowest precedence first.
1349 #[must_use]
1350 pub fn build(self) -> Vec<(PathBuf, bool)> {
1351 let mut dirs = Vec::new();
1352 for dir in self.bundled.into_iter().chain(self.system) {
1353 if dir.is_dir() {
1354 dirs.push((dir, false));
1355 }
1356 }
1357 if let Some(dir) = self.custom
1358 && dir.is_dir()
1359 {
1360 dirs.push((dir, true));
1361 }
1362 dirs
1363 }
1364 }
1365
1366 /// Extract the intent color sections into a flat `HashMap` with dotted keys
1367 /// like `"surface.page"`, `"status.danger"`, `"category.one"`.
1368 ///
1369 /// The tonal steps of `content.primary` are filled in here rather than read, by
1370 /// [`derive_tonal_steps`]. Anything a theme authored under those keys is
1371 /// replaced.
1372 pub fn extract_colors(table: &toml::Table) -> HashMap<String, String> {
1373 let mut colors = HashMap::new();
1374 for section in COLOR_SECTIONS {
1375 if let Some(sect) = table.get(*section).and_then(|s| s.as_table()) {
1376 for (key, val) in sect {
1377 if let Some(color) = val.as_str() {
1378 colors.insert(format!("{section}.{key}"), color.to_string());
1379 }
1380 }
1381 }
1382 }
1383 derive_tonal_steps(&mut colors);
1384 colors
1385 }
1386
1387 /// Fill in the tonal steps of `content.primary`, overwriting whatever the theme
1388 /// authored under those keys.
1389 ///
1390 /// # Why they are not authored
1391 ///
1392 /// `content.secondary` and `content.muted` are not independent colours. They are
1393 /// the ink, one step and two steps back, and a theme that names them separately
1394 /// is stating three times something it stated once — which is how three of the
1395 /// bundled themes came to author a `secondary` *lighter* than their own
1396 /// `primary` (nord, solarized-dark) or identical to it (dracula), inverting the
1397 /// emphasis ramp the whole vocabulary rests on. Deriving them makes
1398 /// `content` > `content-secondary` > `content-muted` true by construction in
1399 /// every theme, including one a user writes.
1400 ///
1401 /// Applied at load rather than in [`resolve`] so that there is one answer: the
1402 /// resolved token layer, the ANSI table ([`ansi_intent`] reads authored keys),
1403 /// and every consumer holding a [`ThemeColors`] all see the same value. A
1404 /// derivation visible from only one of those is how a terminal and a webview
1405 /// come to disagree about what muted means.
1406 ///
1407 /// Both keys need `content.primary` and `surface.page` to exist and parse. When
1408 /// either is missing the step is skipped and anything authored is left where it
1409 /// is, mirroring the skip-missing behaviour of the rest of the crate — a
1410 /// half-written theme keeps whatever it has rather than losing it.
1411 pub fn derive_tonal_steps<S: std::hash::BuildHasher>(colors: &mut HashMap<String, String, S>) {
1412 let ink = colors.get("content.primary").and_then(|v| Rgb::from_hex(v));
1413 let page = colors.get("surface.page").and_then(|v| Rgb::from_hex(v));
1414 let (Some(ink), Some(page)) = (ink, page) else {
1415 return;
1416 };
1417 for (key, step) in [
1418 ("content.secondary", Emphasis::Secondary),
1419 ("content.muted", Emphasis::Muted),
1420 ] {
1421 colors.insert(key.to_string(), emphasized(ink, page, step).to_hex());
1422 }
1423 }
1424
1425 /// Scan directories for `.toml` theme files and return metadata for each.
1426 ///
1427 /// Directories are checked in order; later entries override earlier ones by ID.
1428 /// Each entry in `dirs` is `(path, is_custom)`.
1429 pub fn list_themes_from_dirs(dirs: &[(PathBuf, bool)]) -> Vec<ThemeMeta> {
1430 let mut seen: HashMap<String, ThemeMeta> = HashMap::new();
1431
1432 for (dir, is_custom) in dirs {
1433 let Ok(entries) = std::fs::read_dir(dir) else {
1434 continue;
1435 };
1436
1437 for entry in entries {
1438 let Ok(entry) = entry else {
1439 continue;
1440 };
1441 let path = entry.path();
1442 if path.extension().and_then(|e| e.to_str()) != Some("toml") {
1443 continue;
1444 }
1445
1446 let id = path
1447 .file_stem()
1448 .and_then(|s| s.to_str())
1449 .unwrap_or_default()
1450 .to_string();
1451
1452 let Ok(content) = std::fs::read_to_string(&path) else {
1453 continue;
1454 };
1455 let table: toml::Table = match content.parse() {
1456 Ok(t) => t,
1457 Err(_) => continue,
1458 };
1459
1460 seen.insert(id.clone(), parse_meta(&id, &table, *is_custom));
1461 }
1462 }
1463
1464 let mut themes: Vec<ThemeMeta> = seen.into_values().collect();
1465 themes.sort_by(|a, b| a.name.cmp(&b.name));
1466 themes
1467 }
1468
1469 /// Find a theme file by ID in the given directories.
1470 ///
1471 /// Checks directories in reverse order so the highest-priority directory wins.
1472 /// Returns `(path, is_custom)` or `None` if not found.
1473 pub fn find_theme_path(dirs: &[(PathBuf, bool)], id: &str) -> Option<(PathBuf, bool)> {
1474 let filename = format!("{id}.toml");
1475
1476 for (dir, is_custom) in dirs.iter().rev() {
1477 let path = dir.join(&filename);
1478 if path.is_file() {
1479 return Some((path, *is_custom));
1480 }
1481 }
1482
1483 None
1484 }
1485
1486 /// Parse a complete theme (metadata + colors) from raw TOML content, with no
1487 /// filesystem access. For callers that embed themes at compile time.
1488 pub fn parse_theme_str(id: &str, content: &str, is_custom: bool) -> Result<ThemeColors, String> {
1489 validate_theme_id(id)?;
1490 let table: toml::Table = content
1491 .parse()
1492 .map_err(|e| format!("Failed to parse theme '{id}': {e}"))?;
1493 let meta = parse_meta(id, &table, is_custom);
1494 let colors = extract_colors(&table);
1495 Ok(ThemeColors { meta, colors })
1496 }
1497
1498 /// Load a complete theme (metadata + colors) by ID from the given directories.
1499 pub fn load_theme(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemeColors, String> {
1500 validate_theme_id(id)?;
1501
1502 let (path, is_custom) =
1503 find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
1504
1505 let content = std::fs::read_to_string(&path)
1506 .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
1507
1508 let table: toml::Table = content
1509 .parse()
1510 .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
1511
1512 let meta = parse_meta(id, &table, is_custom);
1513 let colors = extract_colors(&table);
1514
1515 Ok(ThemeColors { meta, colors })
1516 }
1517
1518 /// Load a theme and resolve it to the full intent token set in one step.
1519 pub fn load_semantic(dirs: &[(PathBuf, bool)], id: &str) -> Result<SemanticTokens, String> {
1520 Ok(resolve(&load_theme(dirs, id)?))
1521 }
1522
1523 /// Import a theme TOML file into the custom themes directory.
1524 ///
1525 /// Validates that the file is parseable TOML with at least one intent color
1526 /// section, then copies it to `custom_dir/{id}.toml`. Returns the theme metadata.
1527 pub fn import_theme(source_path: &Path, custom_dir: &Path) -> Result<ThemeMeta, String> {
1528 let content = std::fs::read_to_string(source_path)
1529 .map_err(|e| format!("Failed to read {}: {}", source_path.display(), e))?;
1530
1531 let table: toml::Table = content.parse().map_err(|e| format!("Invalid TOML: {e}"))?;
1532
1533 let has_colors = COLOR_SECTIONS
1534 .iter()
1535 .any(|s| table.get(*s).and_then(|v| v.as_table()).is_some());
1536 if !has_colors {
1537 return Err(format!(
1538 "Theme file must have at least one color section ({})",
1539 COLOR_SECTIONS.join(", ")
1540 ));
1541 }
1542
1543 let id = source_path
1544 .file_stem()
1545 .and_then(|s| s.to_str())
1546 .ok_or("Invalid file name")?
1547 .to_string();
1548 validate_theme_id(&id)?;
1549
1550 std::fs::create_dir_all(custom_dir)
1551 .map_err(|e| format!("Failed to create {}: {}", custom_dir.display(), e))?;
1552
1553 let dest = custom_dir.join(format!("{id}.toml"));
1554 std::fs::copy(source_path, &dest).map_err(|e| format!("Failed to copy theme: {e}"))?;
1555
1556 Ok(parse_meta(&id, &table, true))
1557 }
1558
1559 /// Delete a custom theme by ID.
1560 ///
1561 /// Only operates on `custom_dir` — bundled themes are not deletable through
1562 /// this entry point.
1563 pub fn delete_theme(custom_dir: &Path, id: &str) -> Result<(), String> {
1564 validate_theme_id(id)?;
1565
1566 let path = custom_dir.join(format!("{id}.toml"));
1567 if !path.is_file() {
1568 return Err(format!("Custom theme '{id}' not found"));
1569 }
1570
1571 std::fs::remove_file(&path).map_err(|e| format!("Failed to delete {}: {}", path.display(), e))
1572 }
1573
1574 /// A four-color preview for theme thumbnails: the representative swatch from
1575 /// each of the principal roles.
1576 #[derive(Debug, Clone, Serialize)]
1577 #[serde(rename_all = "camelCase")]
1578 pub struct ThemePreview {
1579 pub meta: ThemeMeta,
1580 /// Page background (`surface.page`).
1581 pub background: Option<String>,
1582 /// Body text (`content.primary`).
1583 pub foreground: Option<String>,
1584 /// Brand/interactive color (`action.primary`).
1585 pub accent: Option<String>,
1586 /// Divider/outline color (`line.border`).
1587 pub border: Option<String>,
1588 }
1589
1590 fn color_at(table: &toml::Table, section: &str, key: &str) -> Option<String> {
1591 table
1592 .get(section)
1593 .and_then(|s| s.as_table())
1594 .and_then(|s| s.get(key))
1595 .and_then(|v| v.as_str())
1596 .map(std::string::ToString::to_string)
1597 }
1598
1599 /// Load just the preview swatches for a theme — for UI thumbnails.
1600 pub fn load_theme_preview(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemePreview, String> {
1601 validate_theme_id(id)?;
1602
1603 let (path, is_custom) =
1604 find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
1605
1606 let content = std::fs::read_to_string(&path)
1607 .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
1608
1609 let table: toml::Table = content
1610 .parse()
1611 .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
1612
1613 Ok(ThemePreview {
1614 meta: parse_meta(id, &table, is_custom),
1615 background: color_at(&table, "surface", "page"),
1616 foreground: color_at(&table, "content", "primary"),
1617 accent: color_at(&table, "action", "primary"),
1618 border: color_at(&table, "line", "border"),
1619 })
1620 }
1621
1622 /// Export a theme to a user-chosen path.
1623 pub fn export_theme(dirs: &[(PathBuf, bool)], id: &str, dest_path: &Path) -> Result<(), String> {
1624 validate_theme_id(id)?;
1625
1626 let (source, _) = find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
1627
1628 std::fs::copy(&source, dest_path).map_err(|e| format!("Failed to export theme: {e}"))?;
1629
1630 Ok(())
1631 }
1632
1633 /// The themes this crate ships, embedded at compile time.
1634 ///
1635 /// `include_dir` is an implementation detail: the public API hands back plain
1636 /// `(id, toml_source)` pairs, so how the data is embedded can change without
1637 /// a breaking release.
1638 static EMBEDDED: include_dir::Dir<'static> =
1639 include_dir::include_dir!("$CARGO_MANIFEST_DIR/themes");
1640
1641 /// The themes this crate ships, as `(id, toml_source)` pairs.
1642 ///
1643 /// This is the path-free way to reach the bundled set, for consumers that
1644 /// cannot rely on a directory existing at runtime: a crate pulled from
1645 /// crates.io lives in a registry checkout whose location is not knowable at
1646 /// compile time, so `include_dir!` and asset-bundling globs in the depending
1647 /// crate have nothing stable to point at. Embedding here and re-exporting the
1648 /// contents gives them one source of truth without a path.
1649 ///
1650 /// Ordering follows the embedded directory and is not guaranteed; collect and
1651 /// sort by id where a stable order matters (a theme picker, say).
1652 pub fn embedded_themes() -> impl Iterator<Item = (&'static str, &'static str)> {
1653 EMBEDDED.files().filter_map(|file| {
1654 let path = file.path();
1655 if path.extension().and_then(|e| e.to_str()) != Some("toml") {
1656 return None;
1657 }
1658 let id = path.file_stem()?.to_str()?;
1659 Some((id, file.contents_utf8()?))
1660 })
1661 }
1662
1663 /// The theme directory this crate ships, for use as a build-from-source
1664 /// fallback.
1665 ///
1666 /// Resolves against `makeover`'s own manifest directory, fixed at compile
1667 /// time, so it works from a path dependency and from a cargo git checkout
1668 /// alike. Installed systems should put their packaged theme directory ahead
1669 /// of this in the search path; this is the entry that keeps `cargo run` in a
1670 /// fresh clone from coming up with no themes at all.
1671 ///
1672 /// Returns `None` when the directory is absent — a cargo cache that has been
1673 /// cleaned, or a vendored copy that dropped the data — so callers degrade to
1674 /// their remaining search path rather than failing.
1675 pub fn bundled_themes_dir() -> Option<PathBuf> {
1676 let themes = Path::new(env!("CARGO_MANIFEST_DIR")).join("themes");
1677 if themes.is_dir() { Some(themes) } else { None }
1678 }
1679
1680 #[cfg(test)]
1681 mod tests {
1682 use super::*;
1683 use std::fs;
1684
1685 // ---- id validation ----
1686
1687 #[test]
1688 fn validate_theme_id_alphanumeric() {
1689 assert!(validate_theme_id("darkmode").is_ok());
1690 assert!(validate_theme_id("Theme123").is_ok());
1691 }
1692
1693 #[test]
1694 fn validate_theme_id_hyphens_underscores() {
1695 assert!(validate_theme_id("dark-mode").is_ok());
1696 assert!(validate_theme_id("my_theme_v2").is_ok());
1697 }
1698
1699 #[test]
1700 fn validate_theme_id_rejects_path_traversal() {
1701 assert!(validate_theme_id("../etc/passwd").is_err());
1702 assert!(validate_theme_id("foo/bar").is_err());
1703 assert!(validate_theme_id("theme.toml").is_err());
1704 }
1705
1706 // ---- low-color terminals ----
1707
1708 #[test]
1709 fn the_ansi_palette_is_sixteen_distinct_colors() {
1710 let mut seen: Vec<(u8, u8, u8)> = ANSI_16.iter().map(|c| c.tuple()).collect();
1711 seen.sort_unstable();
1712 seen.dedup();
1713 assert_eq!(seen.len(), 16);
1714 }
1715
1716 // ---- the intent-to-slot table ----
1717
1718 // Sixteen slots, every one of them answered. A caller filling a terminal
1719 // palette has no fallback for a hole: the slot would keep whatever the
1720 // emulator started with, and one raw ANSI colour in a themed table is more
1721 // obviously wrong than all sixteen would be.
1722 #[test]
1723 fn every_ansi_slot_names_an_intent_on_either_polarity() {
1724 for variant in ["light", "dark", "high-contrast"] {
1725 for index in 0..16 {
1726 assert!(
1727 ansi_intent(index, variant).is_some(),
1728 "slot {index} unanswered on {variant}"
1729 );
1730 }
1731 assert_eq!(ansi_intent(16, variant), None);
1732 }
1733 }
1734
1735 // The property the four achromatic slots exist to hold: 0 is the darkest
1736 // tone the theme offers and 15 the lightest, in either polarity. A table
1737 // that pins slot 0 to `content.primary` passes this on a light theme and
1738 // inverts on a dark one, which is the bug the polarity split fixes.
1739 #[test]
1740 fn ansi_zero_is_darker_than_ansi_fifteen_on_either_polarity() {
1741 for id in ["akari-dawn", "akari-night"] {
1742 let theme = bundled(id);
1743 let slot = |i: usize| -> Rgb {
1744 let key = ansi_intent(i, &theme.meta.variant).expect("in range");
1745 Rgb::from_hex(theme.colors.get(key).expect("theme carries it")).expect("valid hex")
1746 };
1747 assert!(
1748 rel_luminance(slot(0)) < rel_luminance(slot(15)),
1749 "{id}: ANSI 0 {} should be darker than ANSI 15 {}",
1750 slot(0).to_hex(),
1751 slot(15).to_hex(),
1752 );
1753 }
1754 }
1755
1756 // The pair a greeter draws with: its container on 7, its text on 0. If
1757 // those collapse the login screen is one flat block, and slot 7 being a
1758 // surface rather than a text tone is what keeps them apart.
1759 #[test]
1760 fn the_container_slot_and_the_text_slot_stay_legible() {
1761 for id in ["akari-dawn", "akari-night"] {
1762 let theme = bundled(id);
1763 let slot = |i: usize| -> Rgb {
1764 let key = ansi_intent(i, &theme.meta.variant).expect("in range");
1765 Rgb::from_hex(theme.colors.get(key).expect("theme carries it")).expect("valid hex")
1766 };
1767 let contrast = wcag_contrast(slot(0), slot(7));
1768 assert!(contrast >= 4.5, "{id}: ANSI 0 on ANSI 7 is {contrast:.2}:1");
1769 }
1770 }
1771
1772 // The hues do not move with polarity. Red is the theme's danger tone on a
1773 // light theme and on a dark one, which is why only four slots are in the
1774 // polarity table at all.
1775 #[test]
1776 fn the_chromatic_slots_do_not_vary_with_polarity() {
1777 for index in [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14] {
1778 assert_eq!(
1779 ansi_intent(index, "light"),
1780 ansi_intent(index, "dark"),
1781 "slot {index} moved with polarity"
1782 );
1783 }
1784 }
1785
1786 fn bundled(id: &str) -> ThemeColors {
1787 let dir = bundled_themes_dir().expect("makeover ships its themes");
1788 load_theme(&[(dir, false)], id).expect("the akari pair ships")
1789 }
1790
1791 #[test]
1792 fn quantize_picks_the_obvious_entry() {
1793 let black = Rgb { r: 0, g: 0, b: 0 };
1794 let white = Rgb {
1795 r: 255,
1796 g: 255,
1797 b: 255,
1798 };
1799 assert_eq!(quantize(black, &ANSI_16), 0);
1800 assert_eq!(quantize(white, &ANSI_16), 15);
1801 }
1802
1803 // Nearest-entry quantization is per-color, so two colors a theme keeps
1804 // apart can arrive as one. These two are both closest to the palette's
1805 // light gray, and a border drawn in one on a page painted the other is not
1806 // drawn at all.
1807 #[test]
1808 fn two_colors_can_quantize_to_one_entry() {
1809 let page = Rgb::from_hex("#a8a8a8").unwrap();
1810 let border = Rgb::from_hex("#b4b4b4").unwrap();
1811
1812 assert_eq!(quantize(page, &ANSI_16), quantize(border, &ANSI_16));
1813 assert_ne!(
1814 quantize_against(border, page, &ANSI_16),
1815 quantize(page, &ANSI_16)
1816 );
1817 }
1818
1819 #[test]
1820 fn quantize_against_keeps_the_border_off_the_page() {
1821 let page = Rgb::from_hex("#e4ded6").unwrap();
1822 let border = Rgb::from_hex("#7f786d").unwrap();
1823
1824 let shown_page = ANSI_16[quantize(page, &ANSI_16)];
1825 let shown_border = ANSI_16[quantize_against(border, page, &ANSI_16)];
1826
1827 assert!(
1828 wcag_contrast(shown_border, shown_page) >= DISTINCT,
1829 "border {} on page {} is {:.2}:1",
1830 shown_border.to_hex(),
1831 shown_page.to_hex(),
1832 wcag_contrast(shown_border, shown_page)
1833 );
1834 }
1835
1836 // A color that already reads against its background is left where it is,
1837 // so this can be applied without redesigning what already worked.
1838 #[test]
1839 fn quantize_against_leaves_a_readable_color_alone() {
1840 let page = Rgb::from_hex("#e4ded6").unwrap();
1841 let text = Rgb::from_hex("#1a1816").unwrap();
1842
1843 assert_eq!(
1844 quantize_against(text, page, &ANSI_16),
1845 quantize(text, &ANSI_16)
1846 );
1847 }
1848
1849 // With nothing in the palette to satisfy the request, the most legible
1850 // entry is the answer. Returning the nearest one would return the
1851 // background itself, which is the failure this function exists to avoid.
1852 #[test]
1853 fn an_impossible_palette_gets_the_most_legible_entry() {
1854 let page = Rgb::from_hex("#ffffff").unwrap();
1855 let border = Rgb::from_hex("#fefefe").unwrap();
1856 let palette = [
1857 Rgb::from_hex("#ffffff").unwrap(),
1858 Rgb::from_hex("#fdfdfd").unwrap(),
1859 ];
1860
1861 let chosen = palette[quantize_against(border, page, &palette)];
1862 assert_eq!(chosen.to_hex(), "#fdfdfd");
1863 }
1864
1865 // ---- meta ----
1866
1867 #[test]
1868 fn parse_meta_with_name_and_variant() {
1869 let table: toml::Table = "[meta]\nname = \"Nord\"\nvariant = \"light\"\n"
1870 .parse()
1871 .unwrap();
1872 let meta = parse_meta("nord", &table, false);
1873 assert_eq!(meta.id, "nord");
1874 assert_eq!(meta.name, "Nord");
1875 assert_eq!(meta.variant, "light");
1876 assert!(!meta.is_custom);
1877 }
1878
1879 #[test]
1880 fn parse_meta_defaults_to_id_and_dark() {
1881 let table: toml::Table = "".parse().unwrap();
1882 let meta = parse_meta("fallback", &table, true);
1883 assert_eq!(meta.name, "fallback");
1884 assert_eq!(meta.variant, "dark");
1885 assert!(meta.is_custom);
1886 }
1887
1888 // ---- color math (formulas must match the apps they came from) ----
1889
1890 #[test]
1891 fn rgb_hex_roundtrip() {
1892 assert_eq!(
1893 Rgb::from_hex("#6196FF").unwrap(),
1894 Rgb {
1895 r: 0x61,
1896 g: 0x96,
1897 b: 0xff
1898 }
1899 );
1900 assert_eq!(
1901 Rgb::from_hex("#abc").unwrap(),
1902 Rgb {
1903 r: 0xaa,
1904 g: 0xbb,
1905 b: 0xcc
1906 }
1907 );
1908 assert_eq!(
1909 Rgb {
1910 r: 0x61,
1911 g: 0x96,
1912 b: 0xff
1913 }
1914 .to_hex(),
1915 "#6196ff"
1916 );
1917 assert!(Rgb::from_hex("not-a-color").is_none());
1918 }
1919
1920 #[test]
1921 fn oklab_roundtrips_within_tolerance() {
1922 for hex in ["#6196ff", "#2e3440", "#ffffff", "#000000", "#c0392b"] {
1923 let c = Rgb::from_hex(hex).unwrap();
1924 let back = Rgb::from_oklab(c.to_oklab());
1925 // Gamut round-trip is near-exact (±1 per channel from rounding).
1926 assert!((c.r as i16 - back.r as i16).abs() <= 1, "{hex} r");
1927 assert!((c.g as i16 - back.g as i16).abs() <= 1, "{hex} g");
1928 assert!((c.b as i16 - back.b as i16).abs() <= 1, "{hex} b");
1929 }
1930 }
1931
1932 #[test]
1933 fn wcag_contrast_known_pairs() {
1934 let white = Rgb {
1935 r: 255,
1936 g: 255,
1937 b: 255,
1938 };
1939 let black = Rgb { r: 0, g: 0, b: 0 };
1940 assert!((wcag_contrast(white, black) - 21.0).abs() < 0.01);
1941 assert!((wcag_contrast(white, white) - 1.0).abs() < 0.01);
1942 }
1943
1944 #[test]
1945 fn readable_on_picks_by_wcag() {
1946 assert_eq!(
1947 readable_on(Rgb {
1948 r: 255,
1949 g: 255,
1950 b: 255
1951 }),
1952 Rgb { r: 0, g: 0, b: 0 }
1953 );
1954 assert_eq!(
1955 readable_on(Rgb { r: 0, g: 0, b: 0 }),
1956 Rgb {
1957 r: 255,
1958 g: 255,
1959 b: 255
1960 }
1961 );
1962 // A light blue action -> black text reads better.
1963 let action = Rgb::from_hex("#6196ff").unwrap();
1964 assert_eq!(readable_on(action), Rgb { r: 0, g: 0, b: 0 });
1965 }
1966
1967 #[test]
1968 fn lighten_darken_move_oklab_lightness() {
1969 let c = Rgb::from_hex("#6196ff").unwrap();
1970 let l0 = c.to_oklab().l;
1971 assert!(lighten(c, 0.05).to_oklab().l > l0);
1972 assert!(darken(c, 0.05).to_oklab().l < l0);
1973 }
1974
1975 #[test]
1976 fn mix_endpoints_and_midpoint() {
1977 let a = Rgb::from_hex("#000000").unwrap();
1978 let b = Rgb::from_hex("#6196ff").unwrap();
1979 assert_eq!(mix(a, b, 0.0), a);
1980 assert_eq!(mix(a, b, 1.0), b);
1981 // Midpoint sits between the endpoints in OKLab lightness.
1982 let mid = mix(a, b, 0.5).to_oklab().l;
1983 assert!(mid > a.to_oklab().l && mid < b.to_oklab().l);
1984 }
1985
1986 // ---- extract + resolve ----
1987
1988 fn nord_toml() -> &'static str {
1989 r##"
1990 [meta]
1991 name = "Nord"
1992 variant = "dark"
1993
1994 [surface]
1995 page = "#2e3440"
1996 raised = "#3b4252"
1997 sunken = "#434c5e"
1998 overlay = "#3b4252"
1999
2000 [content]
2001 primary = "#d8dee9"
2002 secondary = "#e5e9f0"
2003 muted = "#616e88"
2004
2005 [action]
2006 primary = "#81a1c1"
2007
2008 [status]
2009 danger = "#bf616a"
2010 success = "#a3be8c"
2011 warning = "#ebcb8b"
2012 info = "#88c0d0"
2013
2014 [line]
2015 border = "#4c566a"
2016
2017 [category]
2018 one = "#bf616a"
2019 two = "#a3be8c"
2020 three = "#81a1c1"
2021 four = "#ebcb8b"
2022 five = "#b48ead"
2023 six = "#88c0d0"
2024 "##
2025 }
2026
2027 #[test]
2028 fn extract_colors_reads_intent_sections() {
2029 let table: toml::Table = nord_toml().parse().unwrap();
2030 let colors = extract_colors(&table);
2031 assert_eq!(colors.get("surface.page").unwrap(), "#2e3440");
2032 assert_eq!(colors.get("content.primary").unwrap(), "#d8dee9");
2033 assert_eq!(colors.get("action.primary").unwrap(), "#81a1c1");
2034 assert_eq!(colors.get("status.danger").unwrap(), "#bf616a");
2035 assert_eq!(colors.get("line.border").unwrap(), "#4c566a");
2036 assert_eq!(colors.get("category.five").unwrap(), "#b48ead");
2037 assert_eq!(colors.len(), 19);
2038 }
2039
2040 #[test]
2041 fn resolve_base_intents_passthrough() {
2042 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2043 let t = resolve(&theme);
2044 assert_eq!(t.hex("surface-page"), Some("#2e3440"));
2045 assert_eq!(t.hex("content"), Some("#d8dee9")); // content.primary -> content
2046 // Not a passthrough: a tonal step of the ink, whatever the file said.
2047 assert_eq!(
2048 t.hex("content-muted").unwrap(),
2049 emphasized(
2050 Rgb::from_hex("#d8dee9").unwrap(),
2051 Rgb::from_hex("#2e3440").unwrap(),
2052 Emphasis::Muted
2053 )
2054 .to_hex()
2055 );
2056 assert_eq!(t.hex("action"), Some("#81a1c1"));
2057 assert_eq!(t.hex("danger"), Some("#bf616a"));
2058 assert_eq!(t.hex("border"), Some("#4c566a"));
2059 assert_eq!(t.hex("category-five"), Some("#b48ead"));
2060 }
2061
2062 #[test]
2063 fn a_tonal_step_lands_between_its_base_and_its_ground() {
2064 let ink = Rgb::from_hex("#d8dee9").unwrap();
2065 let page = Rgb::from_hex("#2e3440").unwrap();
2066 for step in [Emphasis::Full, Emphasis::Secondary, Emphasis::Muted] {
2067 let out = emphasized(ink, page, step).to_oklab().l;
2068 assert!(
2069 out <= ink.to_oklab().l && out >= page.to_oklab().l,
2070 "{step:?} left the interval between the ink and the page"
2071 );
2072 }
2073 assert_eq!(emphasized(ink, page, Emphasis::Full).to_hex(), ink.to_hex());
2074 }
2075
2076 #[test]
2077 fn tonal_steps_compose_rather_than_compound() {
2078 // Two steps toward one ground are one step toward it, which is what
2079 // makes deriving a family recursively well-defined. Within a rounding
2080 // step, since each hop lands back in 8-bit sRGB.
2081 let ink = Rgb::from_hex("#d8dee9").unwrap();
2082 let page = Rgb::from_hex("#2e3440").unwrap();
2083 let (a, b) = (0.12f32, 0.42f32);
2084 let twice = tonal(tonal(ink, page, a), page, b);
2085 let once = tonal(ink, page, a + b - a * b);
2086 let (x, y) = (twice.tuple(), once.tuple());
2087 for (l, r) in [(x.0, y.0), (x.1, y.1), (x.2, y.2)] {
2088 assert!(l.abs_diff(r) <= 1, "{twice:?} is not {once:?}");
2089 }
2090 }
2091
2092 #[test]
2093 fn a_ratio_outside_the_interval_is_clamped_rather_than_extrapolated() {
2094 let ink = Rgb::from_hex("#d8dee9").unwrap();
2095 let page = Rgb::from_hex("#2e3440").unwrap();
2096 assert_eq!(tonal(ink, page, -1.0).to_hex(), ink.to_hex());
2097 assert_eq!(tonal(ink, page, 2.0).to_hex(), page.to_hex());
2098 }
2099
2100 #[test]
2101 fn a_derived_token_key_is_the_family_plus_the_step() {
2102 assert_eq!(Emphasis::Muted.token("content"), "content-muted");
2103 assert_eq!(Emphasis::Secondary.token("content"), "content-secondary");
2104 assert_eq!(Emphasis::Full.token("content"), "content");
2105 // The point of the suffix being a property of the step: any family can
2106 // be grouped the same way without a second table saying what it means.
2107 assert_eq!(Emphasis::Muted.token("danger"), "danger-muted");
2108 }
2109
2110 #[test]
2111 fn every_shipped_theme_ramps_one_way() {
2112 // The property authoring the steps separately could not hold: three
2113 // themes had shipped a secondary lighter than their own primary, so a
2114 // renderer reading the emphasis order got the reverse of it.
2115 for (id, toml) in embedded_themes() {
2116 let theme = parse_theme_str(id, toml, false).unwrap();
2117 let t = resolve(&theme);
2118 let page = Rgb::from_hex(t.hex("surface-page").unwrap()).unwrap();
2119 let steps = ["content", "content-secondary", "content-muted"]
2120 .map(|k| wcag_contrast(Rgb::from_hex(t.hex(k).unwrap()).unwrap(), page));
2121 assert!(
2122 steps[0] > steps[1] && steps[1] > steps[2],
2123 "{id}: emphasis does not fall monotonically: {steps:?}"
2124 );
2125 }
2126 }
2127
2128 #[test]
2129 fn an_authored_emphasis_step_does_not_survive_loading() {
2130 // `nord_toml` still authors both, because a user's theme file might and
2131 // the answer has to be the same one.
2132 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2133 assert_ne!(theme.colors.get("content.muted").unwrap(), "#616e88");
2134 assert_ne!(theme.colors.get("content.secondary").unwrap(), "#e5e9f0");
2135 }
2136
2137 #[test]
2138 fn a_theme_with_no_page_keeps_what_it_authored() {
2139 // Skip-missing: there is nothing to read the step against, so the step
2140 // is not taken and a half-written theme does not lose a colour.
2141 let mut colors = HashMap::new();
2142 colors.insert("content.primary".to_string(), "#d8dee9".to_string());
2143 colors.insert("content.muted".to_string(), "#616e88".to_string());
2144 derive_tonal_steps(&mut colors);
2145 assert_eq!(colors.get("content.muted").unwrap(), "#616e88");
2146 }
2147
2148 #[test]
2149 fn resolve_derived_intents() {
2150 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2151 let t = resolve(&theme);
2152 let action = Rgb::from_hex("#81a1c1").unwrap();
2153 let page = Rgb::from_hex("#2e3440").unwrap();
2154 let _ = page;
2155 assert_eq!(
2156 t.hex("action-hover").unwrap(),
2157 lighten(action, 0.05).to_hex()
2158 );
2159 assert_eq!(
2160 t.hex("content-on-action").unwrap(),
2161 readable_on(action).to_hex()
2162 );
2163 assert_eq!(t.hex("focus-ring"), Some("#81a1c1"));
2164 assert_eq!(t.hex("hover-surface"), Some("#434c5e")); // = surface.sunken
2165 // Pruned by the usage audit (0 consumers): action-active, the *-surface
2166 // tints, selection, row-stripe. Apps that need them derive inline via
2167 // the shared mix().
2168 assert!(t.hex("action-active").is_none());
2169 assert!(t.hex("danger-surface").is_none());
2170 assert!(t.hex("selection").is_none());
2171 assert!(t.hex("row-stripe").is_none());
2172 }
2173
2174 #[test]
2175 fn resolve_bevel_intents() {
2176 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2177 let t = resolve(&theme);
2178 let raised = Rgb::from_hex("#3b4252").unwrap();
2179 assert_eq!(
2180 t.hex("bevel-light").unwrap(),
2181 lighten(raised, 0.14).to_hex()
2182 );
2183 assert_eq!(t.hex("bevel-dark").unwrap(), darken(raised, 0.18).to_hex());
2184 }
2185
2186 // A bevel is two edges around one face, so both edges have to be visibly off
2187 // that face or the control never resolves as lit. The lightening clamps at
2188 // the top of the ramp, which means a theme authoring a white raised surface
2189 // gets a highlight identical to the surface it is meant to sit on.
2190 //
2191 // The list is asserted rather than merely reported so that changing a theme
2192 // has to come here and say so. Shrinking it is the fix; growing it is a
2193 // regression in the theme, not in this derivation.
2194 #[test]
2195 fn bevel_edges_are_distinct_from_their_face() {
2196 const CANNOT_BEVEL: &[&str] = &["neobrute", "oxocarbon-light"];
2197
2198 let mut degenerate: Vec<String> = Vec::new();
2199 for (id, source) in embedded_themes() {
2200 let theme = parse_theme_str(id, source, false).unwrap();
2201 let t = resolve(&theme);
2202 let Some(raised) = t.hex("surface-raised") else {
2203 continue;
2204 };
2205 let light = t.hex("bevel-light").expect("raised implies bevel-light");
2206 let dark = t.hex("bevel-dark").expect("raised implies bevel-dark");
2207 if light == raised || dark == raised {
2208 degenerate.push(id.to_string());
2209 }
2210 }
2211 degenerate.sort();
2212
2213 assert_eq!(
2214 degenerate, CANNOT_BEVEL,
2215 "themes whose raised surface cannot hold both bevel edges"
2216 );
2217 }
2218
2219 // The well inverts by theme, so assert both directions explicitly rather
2220 // than only the one the light themes happen to take.
2221 #[test]
2222 fn resolve_well_intent_follows_the_content_direction() {
2223 // nord is dark: light text on a dark raised surface, so the well goes
2224 // down and away from the text.
2225 let dark = resolve(&parse_theme_str("nord", nord_toml(), false).unwrap());
2226 let dark_raised = Rgb::from_hex("#3b4252").unwrap();
2227 assert_eq!(
2228 dark.hex("surface-well").unwrap(),
2229 darken(dark_raised, 0.09).to_hex()
2230 );
2231
2232 // The shipped light themes take the other branch.
2233 let goingson = embedded_themes()
2234 .into_iter()
2235 .find(|(id, _)| *id == "goingson")
2236 .expect("goingson is embedded")
2237 .1;
2238 let light = resolve(&parse_theme_str("goingson", goingson, false).unwrap());
2239 let light_raised = light
2240 .hex("surface-raised")
2241 .and_then(Rgb::from_hex)
2242 .expect("goingson authors a raised surface");
2243 assert_eq!(
2244 light.hex("surface-well").unwrap(),
2245 lighten(light_raised, 0.07).to_hex()
2246 );
2247 }
2248
2249 // A well is a fill, not an edge, so the only thing that makes it read is
2250 // being a different color from the surface it is cut into.
2251 //
2252 // Same shape and the same asserted-list discipline as
2253 // `bevel_edges_are_distinct_from_their_face`, and it bites the same two
2254 // themes for the same reason: a raised surface already at the top of the
2255 // ramp has nothing lighter to go to.
2256 #[test]
2257 fn well_is_distinct_from_its_face() {
2258 const CANNOT_WELL: &[&str] = &["neobrute", "oxocarbon-light"];
2259
2260 let mut degenerate: Vec<String> = Vec::new();
2261 for (id, source) in embedded_themes() {
2262 let theme = parse_theme_str(id, source, false).unwrap();
2263 let t = resolve(&theme);
2264 let Some(raised) = t.hex("surface-raised") else {
2265 continue;
2266 };
2267 let well = t.hex("surface-well").expect("raised implies surface-well");
2268 if well == raised {
2269 degenerate.push(id.to_string());
2270 }
2271 }
2272 degenerate.sort();
2273
2274 assert_eq!(
2275 degenerate, CANNOT_WELL,
2276 "themes whose raised surface cannot hold a well"
2277 );
2278 }
2279
2280 // Distinct is not the same as visible. A face near the top of the ramp
2281 // clamps partway rather than exactly, which yields a well that differs from
2282 // its face by a hex digit and by nothing the eye can find. `rosepine-dawn`
2283 // authors raised at L=0.987 and gets 0.009 of the 0.07 it asked for.
2284 //
2285 // Worth a separate test from the one above because the fix differs: an
2286 // exactly-degenerate theme needs its raised surface off the ramp end, while
2287 // these need it merely lowered. Both fixes are the theme's, not this
2288 // derivation's, which is why the list is asserted rather than warned about.
2289 #[test]
2290 fn well_is_visible_against_its_face() {
2291 // Below this, the well and its face are the same surface to a reader.
2292 const MIN_DELTA_L: f32 = 0.02;
2293 const CANNOT_HOLD_A_VISIBLE_WELL: &[&str] =
2294 &["neobrute", "oxocarbon-light", "rosepine-dawn"];
2295
2296 let mut invisible: Vec<String> = Vec::new();
2297 for (id, source) in embedded_themes() {
2298 let theme = parse_theme_str(id, source, false).unwrap();
2299 let t = resolve(&theme);
2300 let (Some(raised), Some(well)) = (
2301 t.hex("surface-raised").and_then(Rgb::from_hex),
2302 t.hex("surface-well").and_then(Rgb::from_hex),
2303 ) else {
2304 continue;
2305 };
2306 if (well.to_oklab().l - raised.to_oklab().l).abs() < MIN_DELTA_L {
2307 invisible.push(id.to_string());
2308 }
2309 }
2310 invisible.sort();
2311
2312 assert_eq!(
2313 invisible, CANNOT_HOLD_A_VISIBLE_WELL,
2314 "themes whose well is too close to its face to read as one"
2315 );
2316 }
2317
2318 // The three tests above each measure a derived color against the face it was
2319 // derived from, so a theme can pass all of them and still have nothing lift
2320 // off anything: the face itself sits on the page, and that relationship is
2321 // the one a bevel needs in order to read as an object rather than as a
2322 // rectangle with decorated edges. makenot.work passed all three and could
2323 // not hold a bevel, which is what this covers.
2324 //
2325 // The threshold is picked against the ramps already ruled on rather than
2326 // against a round number. makenot.work shipped at 0.024 and was invisible,
2327 // was tried at 0.036 and rejected as marginal on badges and chips, and was
2328 // accepted at 0.058; goingson and audiofiles sit at 0.119 and 0.065. Every
2329 // ramp judged inadequate is below 0.036 and every one judged adequate is
2330 // above 0.058, so the line goes in the gap between them. Note the unit: this
2331 // is oklab L on 0 to 1, not the CIE L* on 0 to 100 that the theme files quote
2332 // in their comments, and the two are not interchangeable.
2333 //
2334 // Most of the list is imported palettes, which were authored for syntax
2335 // highlighting and owe our depth model nothing. Failing here says a theme
2336 // cannot hold a bevel, not that it is wrong. Shrinking the list is the fix;
2337 // growing it is a regression in the theme, not in this derivation.
2338 //
2339 // tokyonight left the list on 2026-08-15, and it is the only entry that could
2340 // leave without a judgment call about someone else's palette. Its page and
2341 // raised were the identical hex, so it had no ramp at all rather than a
2342 // shallow one, and the fix is upstream's own `bg_highlight` (#292e42, 0.079
2343 // above the page) rather than a color we picked. The other nineteen are
2344 // shallow ramps in published palettes, which is a different claim, and they
2345 // stay deferred until every app is migrated and eyeballed.
2346 #[test]
2347 fn raised_is_distinct_from_page() {
2348 // Below this, a raised surface and the page under it are one surface to
2349 // a reader, whichever direction the theme ramps in.
2350 const MIN_DELTA_L: f32 = 0.05;
2351 const CANNOT_LIFT_OFF_THE_PAGE: &[&str] = &[
2352 "akari-dawn",
2353 "akari-night",
2354 "ayu-light",
2355 "ayu-mirage",
2356 "catppuccin-latte",
2357 "catppuccin-mocha",
2358 "dawnfox",
2359 "dracula",
2360 "everforest",
2361 "flatwhite",
2362 "gruvbox-light",
2363 "neobrute",
2364 "one-dark",
2365 "oxocarbon-dark",
2366 "oxocarbon-light",
2367 "poimandres",
2368 "rosepine",
2369 "rosepine-dawn",
2370 "solarized-dark",
2371 ];
2372
2373 let mut flat: Vec<String> = Vec::new();
2374 for (id, source) in embedded_themes() {
2375 let theme = parse_theme_str(id, source, false).unwrap();
2376 let t = resolve(&theme);
2377 let (Some(page), Some(raised)) = (
2378 t.hex("surface-page").and_then(Rgb::from_hex),
2379 t.hex("surface-raised").and_then(Rgb::from_hex),
2380 ) else {
2381 continue;
2382 };
2383 if (raised.to_oklab().l - page.to_oklab().l).abs() < MIN_DELTA_L {
2384 flat.push(id.to_string());
2385 }
2386 }
2387 flat.sort();
2388
2389 assert_eq!(
2390 flat, CANNOT_LIFT_OFF_THE_PAGE,
2391 "themes whose raised surface is too close to the page to lift off it"
2392 );
2393 }
2394
2395 // What the bevel pair does on a sixteen-color terminal, measured across the
2396 // shipped set rather than assumed. Two results, both load-bearing for a
2397 // consumer that has to render one there.
2398 //
2399 // Exactly one edge survives, never both. A raised face quantizes onto one of
2400 // the palette's three grays, and the palette is too coarse to hold anything
2401 // between that entry and its neighbour, so whichever edge is pushed toward
2402 // the end of the ramp the face already sits on lands back on the face. Light
2403 // themes and most dark ones keep the shadow and lose the highlight; a face
2404 // that quantizes to black keeps the highlight and loses the shadow.
2405 //
2406 // So a low-color consumer draws the single edge it can render, on the side
2407 // the palette left it, rather than a bevel that resolves on two sides.
2408 //
2409 // And `quantize_against` is the wrong function for this pair, though it is
2410 // the right one for a border. It answers "nearest entry that clears DISTINCT
2411 // against the background", which has no notion of direction, so both edges
2412 // are pushed onto the same contrasting entry and the bevel inverts on one
2413 // side. Plain `quantize` keeps them apart and in the right order.
2414 #[test]
2415 fn a_sixteen_color_terminal_gets_one_bevel_edge_and_not_two() {
2416 for (id, source) in embedded_themes() {
2417 let theme = parse_theme_str(id, source, false).unwrap();
2418 let t = resolve(&theme);
2419 let (Some(face), Some(light), Some(dark)) = (
2420 t.hex("surface-raised").and_then(Rgb::from_hex),
2421 t.hex("bevel-light").and_then(Rgb::from_hex),
2422 t.hex("bevel-dark").and_then(Rgb::from_hex),
2423 ) else {
2424 continue;
2425 };
2426
2427 let face_index = quantize(face, &ANSI_16);
2428 let light_survives = quantize(light, &ANSI_16) != face_index;
2429 let dark_survives = quantize(dark, &ANSI_16) != face_index;
2430 assert!(
2431 light_survives != dark_survives,
2432 "{id}: expected exactly one bevel edge to survive 16 colors, \
2433 highlight {light_survives} shadow {dark_survives}"
2434 );
2435
2436 // Direction-blind, so it collapses the pair it is asked to separate.
2437 assert_eq!(
2438 quantize_against(light, face, &ANSI_16),
2439 quantize_against(dark, face, &ANSI_16),
2440 "{id}: quantize_against is expected to be unusable for a bevel pair"
2441 );
2442 }
2443 }
2444
2445 // 256 colors is where the bevel starts working. At 16 every shipped theme
2446 // loses an edge; here all but the five whose raised surface sits at the very
2447 // top of the ramp keep both, and those five fail for the reason they fail in
2448 // truecolor rather than for a palette reason.
2449 //
2450 // Three of them cannot bevel at any depth, so they are the
2451 // `bevel_edges_are_distinct_from_their_face` set. The other two are new here:
2452 // they hold a highlight in 24-bit, but not one wide enough to survive
2453 // rounding onto the cube.
2454 #[test]
2455 fn two_hundred_fifty_six_colors_keep_both_bevel_edges() {
2456 const LOSES_AN_EDGE: &[&str] = &[
2457 "gruvbox-light",
2458 "neobrute",
2459 "oxocarbon-light",
2460 "rosepine-dawn",
2461 ];
2462
2463 let mut lost: Vec<String> = Vec::new();
2464 for (id, source) in embedded_themes() {
2465 let theme = parse_theme_str(id, source, false).unwrap();
2466 let t = resolve(&theme);
2467 let (Some(face), Some(light), Some(dark)) = (
2468 t.hex("surface-raised").and_then(Rgb::from_hex),
2469 t.hex("bevel-light").and_then(Rgb::from_hex),
2470 t.hex("bevel-dark").and_then(Rgb::from_hex),
2471 ) else {
2472 continue;
2473 };
2474
2475 // Against the fixed region, which is what a consumer should use: a
2476 // match in the low sixteen is a match against a repaintable color.
2477 let f = quantize(face, ANSI_240);
2478 let l = quantize(light, ANSI_240);
2479 let d = quantize(dark, ANSI_240);
2480 if l == f || d == f || l == d {
2481 lost.push(id.to_string());
2482 }
2483 }
2484 lost.sort();
2485
2486 assert_eq!(
2487 lost, LOSES_AN_EDGE,
2488 "themes that cannot hold a two-tone bevel on a 256-color terminal"
2489 );
2490 }
2491
2492 #[test]
2493 fn the_256_table_has_its_three_regions() {
2494 // Index is the escape-sequence index, so the low sixteen must match.
2495 assert_eq!(ANSI_256[..16], ANSI_16);
2496 // The cube's corners, at both ends and one interior level.
2497 assert_eq!(ANSI_256[16].tuple(), (0, 0, 0));
2498 assert_eq!(ANSI_256[231].tuple(), (255, 255, 255));
2499 assert_eq!(ANSI_256[16 + 36 * 2 + 6 * 3 + 4].tuple(), (135, 175, 215));
2500 // The gray ramp runs 8 to 238 and contains neither black nor white.
2501 assert_eq!(ANSI_256[232].tuple(), (8, 8, 8));
2502 assert_eq!(ANSI_256[255].tuple(), (238, 238, 238));
2503 // The fixed region is the table minus the repaintable colors.
2504 assert_eq!(ANSI_240.len(), 240);
2505 assert_eq!(ANSI_240[0], ANSI_256[ANSI_240_OFFSET]);
2506 }
2507
2508 #[test]
2509 fn resolve_overlay_is_dark_translucent_scrim() {
2510 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2511 let t = resolve(&theme);
2512 let overlay = t.hex("overlay").unwrap();
2513 assert!(
2514 overlay.starts_with("rgba("),
2515 "overlay is translucent: {overlay}"
2516 );
2517 assert!(overlay.ends_with(", 0.5)"));
2518 // The scrim tone is anchored very dark regardless of theme.
2519 let inner = overlay
2520 .trim_start_matches("rgba(")
2521 .trim_end_matches(", 0.5)");
2522 let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
2523 let scrim = Rgb {
2524 r: parts[0],
2525 g: parts[1],
2526 b: parts[2],
2527 };
2528 assert!(scrim.to_oklab().l < 0.2, "scrim must be near-black");
2529 }
2530
2531 /// Every shipped theme derives it, on both polarities, and it is always a
2532 /// near-black translucent tone. A shadow tinted to a dark theme's own
2533 /// lightness would not read as one.
2534 #[test]
2535 fn elevation_is_a_near_black_cast_on_every_theme() {
2536 for (id, source) in embedded_themes() {
2537 let theme = parse_theme_str(id, source, false).unwrap();
2538 let t = resolve(&theme);
2539 let Some(elevation) = t.hex("elevation") else {
2540 panic!("{id} derives no elevation");
2541 };
2542 assert!(
2543 elevation.starts_with("rgba(") && elevation.ends_with(", 0.18)"),
2544 "{id}: elevation is translucent: {elevation}"
2545 );
2546 let inner = elevation
2547 .trim_start_matches("rgba(")
2548 .trim_end_matches(", 0.18)");
2549 let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
2550 let cast = Rgb {
2551 r: parts[0],
2552 g: parts[1],
2553 b: parts[2],
2554 };
2555 assert!(
2556 cast.to_oklab().l < 0.2,
2557 "{id}: a cast shadow must be near-black, got {elevation}"
2558 );
2559 }
2560 }
2561
2562 /// The scrim and the cast share an anchor and differ only in weight. Stated
2563 /// as a test because the two are easy to drift apart, and a scrim that
2564 /// stopped matching the shadow under the thing it dims would show.
2565 #[test]
2566 fn elevation_and_the_scrim_are_the_same_tone() {
2567 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2568 let t = resolve(&theme);
2569 let scrim = t.hex("overlay").unwrap();
2570 let cast = t.hex("elevation").unwrap();
2571 assert_eq!(
2572 scrim.trim_end_matches(", 0.5)"),
2573 cast.trim_end_matches(", 0.18)"),
2574 );
2575 }
2576
2577 /// The accessor that makes a translucent intent reachable from something
2578 /// that is not a stylesheet. Both spellings, and an opaque token answers
2579 /// 255 so a caller need not know which kind it asked for.
2580 #[test]
2581 fn rgba_reads_both_spellings() {
2582 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2583 let t = resolve(&theme);
2584
2585 let (_, _, _, opaque) = t.rgba("surface-page").expect("page is a hex token");
2586 assert_eq!(opaque, 255);
2587
2588 let (r, g, b, alpha) = t.rgba("elevation").expect("elevation is translucent");
2589 assert_eq!(alpha, 46, "0.18 of 255");
2590 assert_eq!(t.rgb("elevation"), None, "rgb declines to drop the alpha");
2591
2592 let (sr, sg, sb, scrim) = t.rgba("overlay").expect("overlay is translucent");
2593 assert_eq!((sr, sg, sb), (r, g, b), "one tone, two weights");
2594 assert_eq!(scrim, 128);
2595 }
2596
2597 #[test]
2598 fn resolve_drops_non_hex_base_intent() {
2599 // A base intent that isn't a hex color must never reach the resolved
2600 // token set (it would otherwise be inlined verbatim into a <style>
2601 // block). Skipped like a missing intent; valid siblings survive.
2602 let theme = parse_theme_str(
2603 "x",
2604 "[surface]\npage = \"</style><script>alert(1)</script>\"\n[content]\nprimary = \"#111111\"\n",
2605 false,
2606 )
2607 .unwrap();
2608 let t = resolve(&theme);
2609 assert!(
2610 t.hex("surface-page").is_none(),
2611 "non-hex base intent leaked"
2612 );
2613 assert_eq!(t.hex("content").unwrap(), "#111111");
2614 // The injected markup appears in no resolved value.
2615 assert!(!t.intents.values().any(|v| v.contains('<')));
2616 }
2617
2618 #[test]
2619 fn resolve_skips_derived_when_source_missing() {
2620 // No [action] => no action-derived tokens.
2621 let theme = parse_theme_str(
2622 "x",
2623 "[surface]\npage = \"#000000\"\n[line]\nborder = \"#222222\"\n",
2624 false,
2625 )
2626 .unwrap();
2627 let t = resolve(&theme);
2628 assert!(t.hex("action").is_none());
2629 assert!(t.hex("action-hover").is_none());
2630 assert!(t.hex("selection").is_none());
2631 assert_eq!(
2632 t.hex("border-strong").unwrap(),
2633 darken(Rgb::from_hex("#222222").unwrap(), 0.05).to_hex()
2634 );
2635 }
2636
2637 #[test]
2638 fn rgb_accessor_for_native_consumers() {
2639 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2640 let t = resolve(&theme);
2641 assert_eq!(t.rgb("action"), Some((0x81, 0xa1, 0xc1)));
2642 assert_eq!(t.rgb("nonexistent"), None);
2643 }
2644
2645 // ---- css emit ----
2646
2647 #[test]
2648 fn intent_css_vars_wraps_root_and_includes_tokens() {
2649 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2650 let css = intent_css_vars(&resolve(&theme));
2651 assert!(css.starts_with(":root {\n"));
2652 assert!(css.contains(" --surface-page: #2e3440;\n"));
2653 assert!(css.contains(" --danger: #bf616a;\n"));
2654 assert!(css.contains(" --action-hover: "));
2655 assert!(css.trim_end().ends_with('}'));
2656 }
2657
2658 // ---- typography ----
2659
2660 #[test]
2661 fn the_font_tokens_are_two_names_and_each_ends_at_a_system_generic() {
2662 let css = typography_css_vars();
2663 assert!(css.starts_with(":root {\n"));
2664 assert!(css.contains(" --font-mono: \"Quasi Mono\", monospace;\n"));
2665 assert!(css.contains(" --font-sans: \"Quasi Body\", sans-serif;\n"));
2666
2667 // Layer 2 is one hop and no further. A third entry in either stack is
2668 // the shape the standard exists to delete: a chain nobody can predict
2669 // the metrics of, which is what `--font-sans: -apple-system,
2670 // BlinkMacSystemFont, 'Segoe UI', Roboto, ...` was in three apps.
2671 for stack in [FONT_MONO, FONT_SANS] {
2672 assert_eq!(stack.split(',').count(), 2, "{stack} is not one hop");
2673 }
2674
2675 // Two tokens, and no others. `--font-body`, `--font-heading` and
2676 // `--font-display` are gone or out of scope; a token appearing here
2677 // is a fifth answer to a question that has two.
2678 assert_eq!(css.matches("--font-").count(), 2);
2679 }
2680
2681 #[test]
2682 fn every_font_face_names_the_weight_range_because_the_mono_opens_at_200() {
2683 let css = font_face_css("/static/fonts");
2684
2685 assert_eq!(css.matches("@font-face").count(), 2);
2686 assert!(css.contains("src: url(\"/static/fonts/QuasiMono.woff2\") format(\"woff2\");"));
2687 assert!(css.contains("src: url(\"/static/fonts/QuasiBody.woff2\") format(\"woff2\");"));
2688
2689 // The trap. Atkinson Hyperlegible Mono's default instance is
2690 // ExtraLight and the cut keeps the axis, so a `@font-face` that omits
2691 // the range draws the whole UI at 200.
2692 assert_eq!(css.matches("font-weight: 200 800;").count(), 2);
2693
2694 // The families have to be exactly what the tokens ask for, or the
2695 // stack falls through to the generic and the face is dead weight.
2696 for family in [FONT_MONO, FONT_SANS] {
2697 let quoted = family.split(',').next().unwrap();
2698 assert!(css.contains(&format!("font-family: {quoted};")));
2699 }
2700 }
2701
2702 #[test]
2703 fn a_trailing_slash_on_the_base_url_does_not_double_it() {
2704 assert_eq!(font_face_css("fonts/"), font_face_css("fonts"));
2705 assert!(font_face_css("fonts").contains("url(\"fonts/QuasiMono.woff2\")"));
2706 }
2707
2708 // ---- loading / fs ----
2709
2710 #[test]
2711 fn load_and_resolve_round_trip() {
2712 let dir = tempfile::tempdir().unwrap();
2713 fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
2714 let dirs = vec![(dir.path().to_path_buf(), false)];
2715 let t = load_semantic(&dirs, "nord").unwrap();
2716 assert_eq!(t.meta.name, "Nord");
2717 assert_eq!(t.hex("action"), Some("#81a1c1"));
2718 }
2719
2720 #[test]
2721 fn load_theme_rejects_invalid_id() {
2722 assert!(load_theme(&[], "../evil").is_err());
2723 }
2724
2725 fn meta(id: &str, variant: &str) -> ThemeMeta {
2726 ThemeMeta {
2727 id: id.to_string(),
2728 name: id.to_string(),
2729 variant: variant.to_string(),
2730 is_custom: false,
2731 }
2732 }
2733
2734 fn defaults() -> ThemeDefaults {
2735 ThemeDefaults::new("flatwhite", "nord")
2736 }
2737
2738 // The three the shipped themes actually declare.
2739 #[test]
2740 fn every_shipped_variant_parses() {
2741 assert_eq!(Variant::parse("light"), Some(Variant::Light));
2742 assert_eq!(Variant::parse("dark"), Some(Variant::Dark));
2743 assert_eq!(Variant::parse("high-contrast"), Some(Variant::HighContrast));
2744 assert_eq!(Variant::parse("sepia"), None);
2745 }
2746
2747 // parse_meta already defaults a *missing* variant to dark, so an
2748 // unrecognized one reading as light would have the crate disagreeing with
2749 // itself. alloy_tui did exactly that before this existed.
2750 #[test]
2751 fn an_unrecognized_variant_reads_the_way_a_missing_one_does() {
2752 assert_eq!(Variant::from("sepia"), Variant::Dark);
2753 assert_eq!(Variant::from(""), Variant::Dark);
2754
2755 let missing: toml::Table = "[meta]\nname = \"X\"\n".parse().unwrap();
2756 assert_eq!(parse_meta("x", &missing, false).kind(), Variant::Dark);
2757 }
2758
2759 #[test]
2760 fn a_selection_round_trips_through_any_store() {
2761 for (stored, expect) in [
2762 (Some("system"), ThemeSelection::Follow),
2763 (None, ThemeSelection::Follow),
2764 (Some(""), ThemeSelection::Follow),
2765 (Some(" "), ThemeSelection::Follow),
2766 (Some("nord"), ThemeSelection::Fixed("nord".into())),
2767 ] {
2768 let parsed = ThemeSelection::parse(stored);
2769 assert_eq!(parsed, expect, "{stored:?}");
2770 assert_eq!(
2771 ThemeSelection::parse(Some(parsed.as_str())),
2772 expect,
2773 "what is written reads back as what was meant",
2774 );
2775 }
2776 }
2777
2778 // Nothing saved is follow-the-system, which is what Balanced Breakfast
2779 // expressed as an absent value and GoingsOn as a sentinel. Both are now the
2780 // same thing.
2781 #[test]
2782 fn nothing_chosen_yet_is_follow() {
2783 assert_eq!(ThemeSelection::default(), ThemeSelection::Follow);
2784 }
2785
2786 #[test]
2787 fn a_fixed_selection_wins_when_its_theme_is_installed() {
2788 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
2789 let fixed = ThemeSelection::Fixed("nord".into());
2790 assert_eq!(
2791 fixed.resolve(Variant::Light, &defaults(), &available),
2792 "nord",
2793 "a chosen theme is not overridden by the ambient mode",
2794 );
2795 }
2796
2797 // Themes are deletable in three of the four apps. Handing back an id that
2798 // will fail to load only moves the error somewhere less helpful.
2799 #[test]
2800 fn a_fixed_selection_whose_theme_is_gone_falls_back() {
2801 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
2802 let fixed = ThemeSelection::Fixed("deleted".into());
2803 assert_eq!(
2804 fixed.resolve(Variant::Light, &defaults(), &available),
2805 "flatwhite",
2806 );
2807 }
2808
2809 #[test]
2810 fn follow_picks_the_apps_default_for_the_ambient_mode() {
2811 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
2812 let follow = ThemeSelection::Follow;
2813 assert_eq!(
2814 follow.resolve(Variant::Dark, &defaults(), &available),
2815 "nord",
2816 );
2817 assert_eq!(
2818 follow.resolve(Variant::Light, &defaults(), &available),
2819 "flatwhite",
2820 );
2821 }
2822
2823 // The behaviour Balanced Breakfast could not have: following the system
2824 // into a theme the user installed, when the app's own default is absent.
2825 #[test]
2826 fn follow_uses_any_installed_theme_of_the_right_variant() {
2827 let available = [meta("solarized-light", "light"), meta("mine", "dark")];
2828 assert_eq!(
2829 ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &available),
2830 "mine",
2831 "the app's `nord` is not installed, but a dark theme is",
2832 );
2833 }
2834
2835 // Always returns something: an app with no theme directory gets the id it
2836 // ships with, and the load error it would have had anyway.
2837 #[test]
2838 fn an_empty_catalog_still_names_the_apps_default() {
2839 assert_eq!(
2840 ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &[]),
2841 "nord",
2842 );
2843 }
2844
2845 #[test]
2846 fn high_contrast_falls_back_to_dark_unless_named() {
2847 let plain = defaults();
2848 assert_eq!(plain.for_variant(Variant::HighContrast), "nord");
2849
2850 let named = defaults().high_contrast("sharp");
2851 assert_eq!(named.for_variant(Variant::HighContrast), "sharp");
2852 }
2853
2854 // The bug this builder exists to prevent: the Alloy console pushed the
2855 // user's directory first under a comment reading "highest precedence
2856 // first", when both consumers of this vector resolve last-wins. A custom
2857 // theme lost to the packaged one of the same id.
2858 #[test]
2859 fn the_users_own_themes_outrank_everything() {
2860 let root = tempfile::tempdir().unwrap();
2861 let make = |name: &str| {
2862 let dir = root.path().join(name);
2863 std::fs::create_dir_all(&dir).unwrap();
2864 dir
2865 };
2866 let (bundled, system, custom) = (make("bundled"), make("system"), make("custom"));
2867
2868 let dirs = ThemeDirs::new()
2869 .custom(Some(custom.clone()))
2870 .bundled(Some(bundled.clone()))
2871 .system(Some(system.clone()))
2872 .build();
2873
2874 assert_eq!(
2875 dirs,
2876 vec![(bundled, false), (system, false), (custom.clone(), true)],
2877 "lowest precedence first, whatever order the tiers were added in",
2878 );
2879 assert!(dirs.last().unwrap().1, "only the user's tier is custom");
2880
2881 // And the ordering means what the consumers think it means.
2882 for dir in dirs.iter().map(|(dir, _)| dir) {
2883 std::fs::write(dir.join("shared.toml"), "[meta]\nname = \"x\"\n").unwrap();
2884 }
2885 assert_eq!(
2886 find_theme_path(&dirs, "shared").unwrap().0,
2887 custom.join("shared.toml"),
2888 "the user's copy is the one that loads",
2889 );
2890 }
2891
2892 #[test]
2893 fn a_directory_that_does_not_exist_is_dropped() {
2894 let root = tempfile::tempdir().unwrap();
2895 let real = root.path().join("real");
2896 std::fs::create_dir_all(&real).unwrap();
2897
2898 let dirs = ThemeDirs::new()
2899 .bundled(Some(root.path().join("nope")))
2900 .system(None)
2901 .custom(Some(real.clone()))
2902 .build();
2903
2904 assert_eq!(dirs, vec![(real, true)]);
2905 }
2906
2907 // A Tauri app has two bundled tiers: the resource dir in production and the
2908 // tree build.rs materialized for a dev run with no resource dir.
2909 #[test]
2910 fn more_than_one_bundled_tier_is_allowed() {
2911 let root = tempfile::tempdir().unwrap();
2912 let (first, second) = (root.path().join("a"), root.path().join("b"));
2913 std::fs::create_dir_all(&first).unwrap();
2914 std::fs::create_dir_all(&second).unwrap();
2915
2916 let dirs = ThemeDirs::new()
2917 .bundled(Some(first.clone()))
2918 .bundled(Some(second.clone()))
2919 .build();
2920 assert_eq!(dirs, vec![(first, false), (second, false)]);
2921 }
2922
2923 #[test]
2924 fn list_themes_from_dirs_finds_toml_files() {
2925 let dir = tempfile::tempdir().unwrap();
2926 fs::write(dir.path().join("t.toml"), "[meta]\nname = \"T\"\n").unwrap();
2927 fs::write(dir.path().join("x.txt"), "ignored").unwrap();
2928 let dirs = vec![(dir.path().to_path_buf(), false)];
2929 let themes = list_themes_from_dirs(&dirs);
2930 assert_eq!(themes.len(), 1);
2931 assert_eq!(themes[0].id, "t");
2932 }
2933
2934 #[test]
2935 fn find_theme_path_reverse_priority() {
2936 let d1 = tempfile::tempdir().unwrap();
2937 let d2 = tempfile::tempdir().unwrap();
2938 fs::write(d1.path().join("s.toml"), "[meta]\n").unwrap();
2939 fs::write(d2.path().join("s.toml"), "[meta]\n").unwrap();
2940 let dirs = vec![
2941 (d1.path().to_path_buf(), false),
2942 (d2.path().to_path_buf(), true),
2943 ];
2944 let (path, is_custom) = find_theme_path(&dirs, "s").unwrap();
2945 assert!(is_custom);
2946 assert_eq!(path, d2.path().join("s.toml"));
2947 }
2948
2949 #[test]
2950 fn import_theme_valid_and_rejects_empty() {
2951 let src_dir = tempfile::tempdir().unwrap();
2952 let custom_dir = tempfile::tempdir().unwrap();
2953
2954 let good = src_dir.path().join("my-theme.toml");
2955 fs::write(&good, "[surface]\npage = \"#1a1b26\"\n").unwrap();
2956 let meta = import_theme(&good, custom_dir.path()).unwrap();
2957 assert_eq!(meta.id, "my-theme");
2958 assert!(custom_dir.path().join("my-theme.toml").exists());
2959
2960 let empty = src_dir.path().join("empty.toml");
2961 fs::write(&empty, "[meta]\nname = \"E\"\n").unwrap();
2962 assert!(import_theme(&empty, custom_dir.path()).is_err());
2963 }
2964
2965 #[test]
2966 fn import_theme_rejects_invalid_toml() {
2967 let src_dir = tempfile::tempdir().unwrap();
2968 let custom_dir = tempfile::tempdir().unwrap();
2969 let src = src_dir.path().join("bad.toml");
2970 fs::write(&src, "this is not [valid toml [[[").unwrap();
2971 assert!(import_theme(&src, custom_dir.path()).is_err());
2972 }
2973
2974 #[test]
2975 fn delete_theme_removes_and_guards() {
2976 let custom = tempfile::tempdir().unwrap();
2977 let path = custom.path().join("doomed.toml");
2978 fs::write(&path, "[surface]\npage = \"#000\"\n").unwrap();
2979 delete_theme(custom.path(), "doomed").unwrap();
2980 assert!(!path.exists());
2981 assert!(delete_theme(custom.path(), "../etc/passwd").is_err());
2982 assert!(delete_theme(custom.path(), "ghost").is_err());
2983 }
2984
2985 #[test]
2986 fn export_theme_copies_file() {
2987 let src_dir = tempfile::tempdir().unwrap();
2988 let dest_dir = tempfile::tempdir().unwrap();
2989 let content = "[meta]\nname = \"E\"\n[surface]\npage = \"#ffffff\"\n";
2990 fs::write(src_dir.path().join("e.toml"), content).unwrap();
2991 let dirs = vec![(src_dir.path().to_path_buf(), false)];
2992 let dest = dest_dir.path().join("out.toml");
2993 export_theme(&dirs, "e", &dest).unwrap();
2994 assert_eq!(fs::read_to_string(&dest).unwrap(), content);
2995 assert!(export_theme(&dirs, "missing", &dest).is_err());
2996 }
2997
2998 #[test]
2999 fn load_theme_preview_returns_role_swatches() {
3000 let dir = tempfile::tempdir().unwrap();
3001 fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
3002 let dirs = vec![(dir.path().to_path_buf(), false)];
3003 let p = load_theme_preview(&dirs, "nord").unwrap();
3004 assert_eq!(p.background.as_deref(), Some("#2e3440")); // surface.page
3005 assert_eq!(p.foreground.as_deref(), Some("#d8dee9")); // content.primary
3006 assert_eq!(p.accent.as_deref(), Some("#81a1c1")); // action.primary
3007 assert_eq!(p.border.as_deref(), Some("#4c566a")); // line.border
3008 }
3009
3010 #[test]
3011 fn bundled_themes_dir_resolves_to_shipped_themes() {
3012 // The crate ships its themes, so this must resolve in-tree and the
3013 // Akari defaults the console falls back to must be present.
3014 let dir = bundled_themes_dir().expect("makeover ships a themes/ directory");
3015 assert!(dir.join("akari-dawn.toml").is_file());
3016 assert!(dir.join("akari-night.toml").is_file());
3017 }
3018
3019 #[test]
3020 fn every_theme_is_accounted_for_in_third_party_notices() {
3021 // Attribution is a redistribution obligation, not a nicety: adding a
3022 // theme without a notice entry silently ships someone's work
3023 // uncredited. Fail here instead.
3024 let notices = std::fs::read_to_string(
3025 Path::new(env!("CARGO_MANIFEST_DIR")).join("THIRD-PARTY-NOTICES.md"),
3026 )
3027 .expect("THIRD-PARTY-NOTICES.md must exist");
3028 let missing: Vec<&str> = embedded_themes()
3029 .map(|(id, _)| id)
3030 .filter(|id| !notices.contains(*id))
3031 .collect();
3032 assert!(
3033 missing.is_empty(),
3034 "themes missing from THIRD-PARTY-NOTICES.md: {missing:?}"
3035 );
3036 }
3037
3038 #[test]
3039 fn adapted_themes_carry_inline_attribution() {
3040 // Each adapted file must name its upstream in-file, so the credit
3041 // survives someone copying a single .toml out of the crate.
3042 const ORIGINALS: [&str; 5] = [
3043 "makenotwork",
3044 "goingson",
3045 "audiofiles",
3046 "high-contrast",
3047 "neobrute",
3048 ];
3049 for (id, source) in embedded_themes() {
3050 if ORIGINALS.contains(&id) {
3051 continue;
3052 }
3053 assert!(
3054 source.contains("adapted from"),
3055 "adapted theme `{id}` is missing its inline attribution header"
3056 );
3057 }
3058 }
3059
3060 #[test]
3061 fn embedded_themes_match_the_directory() {
3062 // The embedded copy and themes/ are two views of one source. If they
3063 // ever disagree, path-based and path-free consumers render different
3064 // theme sets, which is exactly the drift shipping the data was meant
3065 // to prevent.
3066 let dir = bundled_themes_dir().unwrap();
3067 let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
3068 .unwrap()
3069 .filter_map(|e| {
3070 let path = e.ok()?.path();
3071 if path.extension()? != "toml" {
3072 return None;
3073 }
3074 Some(path.file_stem()?.to_str()?.to_string())
3075 })
3076 .collect();
3077 let mut embedded: Vec<String> = embedded_themes().map(|(id, _)| id.to_string()).collect();
3078 on_disk.sort();
3079 embedded.sort();
3080 assert_eq!(embedded, on_disk, "embedded theme set drifted from themes/");
3081 }
3082
3083 #[test]
3084 fn every_embedded_theme_parses() {
3085 // Guards the path-free consumers (MNW server, the Tauri build steps)
3086 // the same way every_shipped_theme_loads guards the path-based ones.
3087 let mut count = 0;
3088 for (id, source) in embedded_themes() {
3089 parse_theme_str(id, source, false)
3090 .unwrap_or_else(|e| panic!("embedded theme `{id}` failed to parse: {e}"));
3091 count += 1;
3092 }
3093 assert!(count >= 30, "expected the full theme set, got {count}");
3094 }
3095
3096 #[test]
3097 fn every_shipped_theme_loads() {
3098 // Guards the data, not just the loader: a malformed or truncated
3099 // .toml in themes/ is a shipping bug, and it should fail here rather
3100 // than at a user's first launch.
3101 let dir = bundled_themes_dir().unwrap();
3102 let dirs = vec![(dir.clone(), false)];
3103 let themes = list_themes_from_dirs(&dirs);
3104 assert!(
3105 themes.len() >= 30,
3106 "expected the full theme set, got {}",
3107 themes.len()
3108 );
3109 for meta in &themes {
3110 load_theme(&dirs, &meta.id)
3111 .unwrap_or_else(|e| panic!("shipped theme `{}` failed to load: {e}", meta.id));
3112 }
3113 }
3114 }
3115