Skip to main content

max / makeover

89.7 KB · 2483 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] # text/ink by emphasis
21 //! primary = "#d8dee9"; secondary = "#e5e9f0"; muted = "#616e88"
22 //!
23 //! [action] # interactive / brand color
24 //! primary = "#81a1c1"
25 //!
26 //! [status] # state semantics
27 //! danger = "#bf616a"; success = "#a3be8c"; warning = "#ebcb8b"; info = "#88c0d0"
28 //!
29 //! [line]
30 //! border = "#4c566a"
31 //!
32 //! [category] # distinct decorative colors for tags/badges/charts
33 //! one = "#bf616a"; two = "#a3be8c"; three = "#81a1c1"
34 //! four = "#ebcb8b"; five = "#b48ead"; six = "#88c0d0"
35 //! ```
36
37 // Color-space math: single-letter channel names (r/g/b/l/m/s) and the published
38 // high-precision OKLab/sRGB matrix constants are the domain vocabulary here.
39 #![allow(clippy::many_single_char_names, clippy::unreadable_literal)]
40
41 use serde::Serialize;
42 use std::collections::{BTreeMap, HashMap};
43 use std::path::{Path, PathBuf};
44
45 /// The color sections an authored theme may declare.
46 pub const COLOR_SECTIONS: &[&str] = &["surface", "content", "action", "status", "line", "category"];
47
48 /// Theme metadata parsed from the `[meta]` section.
49 #[derive(Debug, Clone, Serialize)]
50 #[serde(rename_all = "camelCase")]
51 pub struct ThemeMeta {
52 pub id: String,
53 pub name: String,
54 pub variant: String,
55 pub is_custom: bool,
56 }
57
58 /// A loaded theme: metadata plus the authored colors, flattened to dotted keys
59 /// (e.g. `"surface.page"`, `"status.danger"`, `"category.one"`).
60 #[derive(Debug, Serialize)]
61 #[serde(rename_all = "camelCase")]
62 pub struct ThemeColors {
63 pub meta: ThemeMeta,
64 pub colors: HashMap<String, String>,
65 }
66
67 // ============================================================================
68 // Color math — perceptual (OKLab) derivations + WCAG contrast.
69 //
70 // Interactive states (hover/active/selection/surfaces) are derived in OKLab so
71 // equal steps look equal across every theme's hues (Ottosson 2020; the modern
72 // CIELAB). Text-on-color is picked by the WCAG 2.x contrast ratio, not a naive
73 // luminance threshold, so the choice actually meets AA where achievable.
74 // This is the single source of truth shared by every product.
75 // ============================================================================
76
77 /// An sRGB color. Hex round-trips losslessly.
78 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
79 pub struct Rgb {
80 pub r: u8,
81 pub g: u8,
82 pub b: u8,
83 }
84
85 impl Rgb {
86 /// Parse `#rgb` or `#rrggbb` (case-insensitive). Returns `None` otherwise.
87 pub fn from_hex(s: &str) -> Option<Rgb> {
88 let h = s.strip_prefix('#')?;
89 let (r, g, b) = match h.len() {
90 6 => (
91 u8::from_str_radix(&h[0..2], 16).ok()?,
92 u8::from_str_radix(&h[2..4], 16).ok()?,
93 u8::from_str_radix(&h[4..6], 16).ok()?,
94 ),
95 3 => {
96 let d = |c: &str| u8::from_str_radix(c, 16).ok().map(|v| v * 17);
97 (d(&h[0..1])?, d(&h[1..2])?, d(&h[2..3])?)
98 }
99 _ => return None,
100 };
101 Some(Rgb { r, g, b })
102 }
103
104 /// Lowercase `#rrggbb`.
105 pub fn to_hex(self) -> String {
106 format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
107 }
108
109 pub fn tuple(self) -> (u8, u8, u8) {
110 (self.r, self.g, self.b)
111 }
112 }
113
114 /// A color in OKLab (perceptually uniform): `l` lightness in [0,1], `a`/`b` opponent axes.
115 #[derive(Clone, Copy, Debug)]
116 pub struct Oklab {
117 pub l: f32,
118 pub a: f32,
119 pub b: f32,
120 }
121
122 fn srgb_to_linear(c: u8) -> f32 {
123 let c = c as f32 / 255.0;
124 if c <= 0.04045 {
125 c / 12.92
126 } else {
127 ((c + 0.055) / 1.055).powf(2.4)
128 }
129 }
130
131 fn linear_to_srgb(c: f32) -> u8 {
132 let c = c.clamp(0.0, 1.0);
133 let v = if c <= 0.0031308 {
134 c * 12.92
135 } else {
136 1.055 * c.powf(1.0 / 2.4) - 0.055
137 };
138 (v * 255.0).round().clamp(0.0, 255.0) as u8
139 }
140
141 impl Rgb {
142 /// Convert to OKLab (Ottosson's sRGB matrices).
143 ///
144 /// The matrix coefficients are quoted at their published precision so they
145 /// can be diffed against the reference. `f32` rounds them at compile time;
146 /// truncating the literals would only make them harder to check.
147 #[allow(clippy::excessive_precision)]
148 pub fn to_oklab(self) -> Oklab {
149 let (r, g, b) = (
150 srgb_to_linear(self.r),
151 srgb_to_linear(self.g),
152 srgb_to_linear(self.b),
153 );
154 let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
155 let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
156 let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
157 let (l_, m_, s_) = (l.cbrt(), m.cbrt(), s.cbrt());
158 Oklab {
159 l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
160 a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
161 b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
162 }
163 }
164
165 /// Convert from OKLab back to the nearest in-gamut sRGB.
166 ///
167 /// Published precision, as in [`Rgb::to_oklab`].
168 #[allow(clippy::excessive_precision)]
169 pub fn from_oklab(c: Oklab) -> Rgb {
170 let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b;
171 let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b;
172 let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b;
173 let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
174 Rgb {
175 r: linear_to_srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
176 g: linear_to_srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
177 b: linear_to_srgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s),
178 }
179 }
180 }
181
182 /// WCAG 2.x relative luminance of an sRGB color.
183 fn rel_luminance(c: Rgb) -> f32 {
184 0.2126 * srgb_to_linear(c.r) + 0.7152 * srgb_to_linear(c.g) + 0.0722 * srgb_to_linear(c.b)
185 }
186
187 /// WCAG 2.x contrast ratio between two colors, in [1, 21].
188 pub fn wcag_contrast(a: Rgb, b: Rgb) -> f32 {
189 let (la, lb) = (rel_luminance(a), rel_luminance(b));
190 let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
191 (hi + 0.05) / (lo + 0.05)
192 }
193
194 /// Pick black or white for legible text on `bg`, by the higher WCAG contrast
195 /// ratio (so the choice meets AA wherever the background allows it).
196 pub fn readable_on(bg: Rgb) -> Rgb {
197 let white = Rgb {
198 r: 255,
199 g: 255,
200 b: 255,
201 };
202 let black = Rgb { r: 0, g: 0, b: 0 };
203 if wcag_contrast(white, bg) >= wcag_contrast(black, bg) {
204 white
205 } else {
206 black
207 }
208 }
209
210 /// Shift OKLab lightness by `delta` (perceptually uniform). Positive lightens.
211 pub fn lighten(c: Rgb, delta: f32) -> Rgb {
212 let mut lab = c.to_oklab();
213 lab.l = (lab.l + delta).clamp(0.0, 1.0);
214 Rgb::from_oklab(lab)
215 }
216
217 /// Shift OKLab lightness down by `delta` (perceptually uniform).
218 pub fn darken(c: Rgb, delta: f32) -> Rgb {
219 lighten(c, -delta)
220 }
221
222 /// Interpolate between `a` and `b` by `t` in [0,1] in OKLab (perceptual blend).
223 pub fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb {
224 let (x, y) = (a.to_oklab(), b.to_oklab());
225 Rgb::from_oklab(Oklab {
226 l: x.l + (y.l - x.l) * t,
227 a: x.a + (y.a - x.a) * t,
228 b: x.b + (y.b - x.b) * t,
229 })
230 }
231
232 // ============================================================================
233 // Low-color terminals
234 // ============================================================================
235
236 /// The 16 colors an ANSI terminal addresses by index, in the PC/VGA
237 /// arrangement the Linux console and most emulators start from.
238 ///
239 /// 0-7 are the normal colors and 8-15 the bright ones. Index 7 is a light gray
240 /// rather than white, which is the entry a themed surface usually lands on, and
241 /// index 15 is the true white.
242 ///
243 /// Emulators let the user repaint all sixteen, so this is the standard
244 /// arrangement rather than a promise about any one terminal. The Linux console
245 /// keeps it, which is the case that matters: a console app cannot fall back to
246 /// 24-bit color there.
247 pub const ANSI_16: [Rgb; 16] = [
248 Rgb {
249 r: 0x00,
250 g: 0x00,
251 b: 0x00,
252 },
253 Rgb {
254 r: 0xaa,
255 g: 0x00,
256 b: 0x00,
257 },
258 Rgb {
259 r: 0x00,
260 g: 0xaa,
261 b: 0x00,
262 },
263 Rgb {
264 r: 0xaa,
265 g: 0x55,
266 b: 0x00,
267 },
268 Rgb {
269 r: 0x00,
270 g: 0x00,
271 b: 0xaa,
272 },
273 Rgb {
274 r: 0xaa,
275 g: 0x00,
276 b: 0xaa,
277 },
278 Rgb {
279 r: 0x00,
280 g: 0xaa,
281 b: 0xaa,
282 },
283 Rgb {
284 r: 0xaa,
285 g: 0xaa,
286 b: 0xaa,
287 },
288 Rgb {
289 r: 0x55,
290 g: 0x55,
291 b: 0x55,
292 },
293 Rgb {
294 r: 0xff,
295 g: 0x55,
296 b: 0x55,
297 },
298 Rgb {
299 r: 0x55,
300 g: 0xff,
301 b: 0x55,
302 },
303 Rgb {
304 r: 0xff,
305 g: 0xff,
306 b: 0x55,
307 },
308 Rgb {
309 r: 0x55,
310 g: 0x55,
311 b: 0xff,
312 },
313 Rgb {
314 r: 0xff,
315 g: 0x55,
316 b: 0xff,
317 },
318 Rgb {
319 r: 0x55,
320 g: 0xff,
321 b: 0xff,
322 },
323 Rgb {
324 r: 0xff,
325 g: 0xff,
326 b: 0xff,
327 },
328 ];
329
330 /// The 256 colors an xterm-compatible terminal addresses by index, so that
331 /// entry `i` is what the terminal paints for `38;5;i`.
332 ///
333 /// Three regions, and they are not equally trustworthy. 0-15 are the [`ANSI_16`]
334 /// system colors, which every emulator lets the user repaint. 16-231 are a
335 /// 6x6x6 RGB cube and 232-255 a 24-step gray ramp, and those 240 are fixed.
336 ///
337 /// So a color whose whole job is to be told apart from another should quantize
338 /// against [`ANSI_240`] rather than against this table: a match landing in the
339 /// low sixteen is a match against a color the user may have moved.
340 pub const ANSI_256: [Rgb; 256] = build_ansi_256();
341
342 /// The fixed region of [`ANSI_256`]: the 6x6x6 cube and the gray ramp, without
343 /// the sixteen repaintable system colors.
344 ///
345 /// Quantizing against this returns an index into *this* slice; add
346 /// [`ANSI_240_OFFSET`] to get the index the terminal wants.
347 pub const ANSI_240: &[Rgb] = ANSI_256.split_at(16).1;
348
349 /// What to add to an [`ANSI_240`] index to get an [`ANSI_256`] one.
350 pub const ANSI_240_OFFSET: usize = 16;
351
352 /// The twelve chromatic ANSI slots, as the intents that paint them.
353 ///
354 /// Indexed 1-6 and 9-14. The hues do not depend on whether the theme is light
355 /// or dark, since red is the theme's danger tone either way, which is exactly
356 /// why the four achromatic slots are not in this table.
357 ///
358 /// Lifted from Alloy's `skelgen` on 2026-07-31, which had folded three
359 /// disagreeing hand-maintained copies into one and is the reason the
360 /// arrangement is trusted. It moved here so a program that paints its own
361 /// palette at runtime, rather than reading a generated config, resolves the
362 /// same slots. Slot 14 was the one the copies disagreed on and is
363 /// `category.six`, which both the Linux console table and the retired
364 /// `vtrgb.py` had.
365 const CHROMATIC: [(usize, &str); 12] = [
366 (1, "status.danger"),
367 (2, "status.success"),
368 (3, "status.warning"),
369 (4, "status.info"),
370 (5, "category.five"),
371 (6, "category.six"),
372 (9, "action.primary"), // bright red, the theme's warm accent
373 (10, "status.success"),
374 (11, "status.warning"),
375 (12, "status.info"),
376 (13, "category.five"),
377 (14, "category.six"),
378 ];
379
380 /// The four achromatic slots, 0, 7, 8 and 15, which invert with the theme.
381 ///
382 /// These are the slots a naive table gets wrong. ANSI 0 is "black" and 7 is
383 /// "white", but what a terminal wants there is *the darkest tone* and *the
384 /// lightest tone*, and which intent that is flips with the theme's polarity. A
385 /// light theme's darkest tone is its ink; a dark theme's is its deepest
386 /// surface. Pinning slot 0 to `content.primary` reads correctly on a light
387 /// theme and hands a dark one a pale cream as "black".
388 ///
389 /// Slot 7 is a surface and not a text tone, because it is what a program with
390 /// no way to name anything else draws its container on: a greeter's login card
391 /// is a light card on the darker field slot 0 paints.
392 ///
393 /// Anything that is not `dark`, including `high-contrast`, follows the light
394 /// anchors.
395 fn achromatic_slot(index: usize, variant: &str) -> Option<&'static str> {
396 let dark = variant == "dark";
397 Some(match (index, dark) {
398 (0, false) => "content.primary", // darkest text tone
399 (0, true) => "surface.sunken", // darkest surface
400 (7, false) => "surface.raised", // the login card
401 (7, true) => "content.secondary", // a readable light tone
402 (8, _) => "content.muted", // muted chrome, either way
403 (15, false) => "surface.overlay", // lightest surface
404 (15, true) => "content.primary", // lightest text tone
405 _ => return None,
406 })
407 }
408
409 /// The authored intent painting ANSI slot `index` under a theme of `variant`,
410 /// as a dotted key into [`ThemeColors::colors`].
411 ///
412 /// `None` for an index outside 0-15. Every slot in range resolves, so a caller
413 /// that has the intent can fill all sixteen.
414 ///
415 /// This is what makes a bare console, a terminal emulator and a generated
416 /// config agree on what red means. They disagreed for as long as each kept its
417 /// own table.
418 #[must_use]
419 pub fn ansi_intent(index: usize, variant: &str) -> Option<&'static str> {
420 achromatic_slot(index, variant).or_else(|| {
421 CHROMATIC
422 .iter()
423 .find(|(slot, _)| *slot == index)
424 .map(|(_, intent)| *intent)
425 })
426 }
427
428 const fn build_ansi_256() -> [Rgb; 256] {
429 let mut table = [Rgb { r: 0, g: 0, b: 0 }; 256];
430
431 let mut i = 0;
432 while i < 16 {
433 table[i] = ANSI_16[i];
434 i += 1;
435 }
436
437 // The cube's six levels are not evenly spaced. The step from black to the
438 // first is more than twice any later one, which is xterm's arrangement
439 // rather than a choice available here, and it is why the darkest tones a
440 // theme can reach on 256 colors come from the gray ramp instead.
441 const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
442 let mut r = 0;
443 while r < 6 {
444 let mut g = 0;
445 while g < 6 {
446 let mut b = 0;
447 while b < 6 {
448 table[16 + 36 * r + 6 * g + b] = Rgb {
449 r: LEVELS[r],
450 g: LEVELS[g],
451 b: LEVELS[b],
452 };
453 b += 1;
454 }
455 g += 1;
456 }
457 r += 1;
458 }
459
460 // 8 to 238 in steps of 10. Neither end is black or white; both of those are
461 // in the cube, so the ramp is 24 steps of gray between them rather than 24
462 // steps of the whole range.
463 let mut k = 0;
464 while k < 24 {
465 let v = 8 + 10 * k as u8;
466 table[232 + k as usize] = Rgb { r: v, g: v, b: v };
467 k += 1;
468 }
469
470 table
471 }
472
473 /// The contrast ratio two colors must clear to read as separate areas.
474 ///
475 /// WCAG 2.x asks 3:1 of user interface components and graphics, which is what
476 /// a border, a rule, or a focus ring is. Text wants more, and a caller drawing
477 /// text can ask for more by checking [`wcag_contrast`] itself.
478 pub const DISTINCT: f32 = 3.0;
479
480 /// Perceptual distance between two colors, for choosing the closest of a set.
481 fn oklab_distance(a: Rgb, b: Rgb) -> f32 {
482 let (x, y) = (a.to_oklab(), b.to_oklab());
483 ((x.l - y.l).powi(2) + (x.a - y.a).powi(2) + (x.b - y.b).powi(2)).sqrt()
484 }
485
486 /// Index of the entry in `palette` that looks most like `c`.
487 ///
488 /// OKLab distance rather than distance in sRGB, for the same reason [`mix`]
489 /// interpolates there: sRGB's numbers are not spaced the way seeing is, so a
490 /// nearest match computed in it picks visibly wrong entries in the mid tones.
491 ///
492 /// # Panics
493 ///
494 /// If `palette` is empty.
495 pub fn quantize(c: Rgb, palette: &[Rgb]) -> usize {
496 assert!(!palette.is_empty(), "a palette needs at least one color");
497 let mut best = 0;
498 let mut best_distance = f32::INFINITY;
499 for (index, entry) in palette.iter().enumerate() {
500 let distance = oklab_distance(c, *entry);
501 if distance < best_distance {
502 best = index;
503 best_distance = distance;
504 }
505 }
506 best
507 }
508
509 /// Index of the entry in `palette` closest to `fg` that still reads against
510 /// `bg`.
511 ///
512 /// [`quantize`] answers about one color at a time, and two colors that differ
513 /// can quantize to the same entry: a themed page and a border drawn on it are
514 /// often a few steps apart in a 24-bit theme and land together on a 16-color
515 /// terminal, leaving one flat area where there was a frame. Alloy's console
516 /// showed exactly this, and it is not a contrived pairing: a light page and the
517 /// mid-tone border derived from it both land on index 7.
518 ///
519 /// So the background is quantized first, because what the border must be
520 /// distinguished from is the entry the terminal will actually paint, not the
521 /// color the theme asked for. Then the nearest entry to `fg` clearing
522 /// [`DISTINCT`] against it wins. When nothing clears it, the entry that gets
523 /// furthest does: at that point the palette cannot honor the design, and the
524 /// most legible approximation beats the closest invisible one.
525 ///
526 /// Only for colors whose whole job is to be told apart from their background.
527 /// Applied to every token it would push a deliberately quiet one until it
528 /// shouted.
529 ///
530 /// # Panics
531 ///
532 /// If `palette` is empty.
533 pub fn quantize_against(fg: Rgb, bg: Rgb, palette: &[Rgb]) -> usize {
534 assert!(!palette.is_empty(), "a palette needs at least one color");
535 let shown = palette[quantize(bg, palette)];
536
537 let mut order: Vec<usize> = (0..palette.len()).collect();
538 order.sort_by(|a, b| {
539 oklab_distance(fg, palette[*a]).total_cmp(&oklab_distance(fg, palette[*b]))
540 });
541
542 order
543 .iter()
544 .copied()
545 .find(|index| wcag_contrast(palette[*index], shown) >= DISTINCT)
546 .unwrap_or_else(|| {
547 order
548 .iter()
549 .copied()
550 .max_by(|a, b| {
551 wcag_contrast(palette[*a], shown).total_cmp(&wcag_contrast(palette[*b], shown))
552 })
553 .expect("the palette is not empty")
554 })
555 }
556
557 // ============================================================================
558 // Intent resolution
559 // ============================================================================
560
561 /// Authored base intents: (TOML dotted source key, canonical token key).
562 /// These are read straight from the theme; the token key is the CSS-var stem
563 /// (`--{token}`) and the `rgb()` lookup key.
564 pub const BASE_INTENTS: &[(&str, &str)] = &[
565 ("surface.page", "surface-page"),
566 ("surface.raised", "surface-raised"),
567 ("surface.sunken", "surface-sunken"),
568 ("surface.overlay", "surface-overlay"),
569 ("content.primary", "content"),
570 ("content.secondary", "content-secondary"),
571 ("content.muted", "content-muted"),
572 ("action.primary", "action"),
573 ("status.danger", "danger"),
574 ("status.success", "success"),
575 ("status.warning", "warning"),
576 ("status.info", "info"),
577 ("line.border", "border"),
578 ("category.one", "category-one"),
579 ("category.two", "category-two"),
580 ("category.three", "category-three"),
581 ("category.four", "category-four"),
582 ("category.five", "category-five"),
583 ("category.six", "category-six"),
584 ];
585
586 /// A fully resolved intent layer: every token key → concrete `#rrggbb`.
587 /// Includes both authored base intents and the computed derived intents.
588 #[derive(Debug, Clone, Serialize)]
589 #[serde(rename_all = "camelCase")]
590 pub struct SemanticTokens {
591 pub meta: ThemeMeta,
592 /// token-key → resolved hex. Stable, deterministic ordering.
593 pub intents: BTreeMap<String, String>,
594 }
595
596 impl SemanticTokens {
597 /// Resolved hex for a token key, if present.
598 pub fn hex(&self, key: &str) -> Option<&str> {
599 self.intents.get(key).map(String::as_str)
600 }
601
602 /// Resolved RGB tuple for a token key (for egui / native consumers).
603 pub fn rgb(&self, key: &str) -> Option<(u8, u8, u8)> {
604 self.intents
605 .get(key)
606 .and_then(|h| Rgb::from_hex(h))
607 .map(Rgb::tuple)
608 }
609 }
610
611 /// Resolve an authored theme into the full intent token set.
612 ///
613 /// 1. Copy each present base intent from the authored colors.
614 /// 2. Compute the derived interactive states from the base intents, using the
615 /// same math the apps used to apply individually (so output is identical).
616 ///
617 /// Each derived token is emitted only when its source intents exist, mirroring
618 /// the skip-missing behavior of the rest of the crate.
619 pub fn resolve(theme: &ThemeColors) -> SemanticTokens {
620 let mut intents: BTreeMap<String, String> = BTreeMap::new();
621
622 // 1. Base intents (authored). Copy only values that parse as a hex color and
623 // re-emit them in canonical `#rrggbb` form, so an authored value can never
624 // carry arbitrary bytes into the emitted CSS (the resolved tokens are inlined
625 // raw into a `<style>` block by the web server). A malformed value is skipped,
626 // mirroring the skip-missing behavior for absent intents.
627 for (src, token) in BASE_INTENTS {
628 if let Some(rgb) = theme.colors.get(*src).and_then(|v| Rgb::from_hex(v)) {
629 intents.insert((*token).to_string(), rgb.to_hex());
630 }
631 }
632
633 // Helper: parse an already-resolved token to Rgb.
634 let get = |m: &BTreeMap<String, String>, k: &str| m.get(k).and_then(|h| Rgb::from_hex(h));
635
636 // 2. Derived intents — perceptual (OKLab) steps + WCAG-picked text.
637 // Lightness deltas are in OKLab L units; mix ratios interpolate in OKLab.
638 let mut derived: Vec<(String, Rgb)> = Vec::new();
639 if let Some(action) = get(&intents, "action") {
640 derived.push(("action-hover".into(), lighten(action, 0.05)));
641 derived.push(("content-on-action".into(), readable_on(action)));
642 derived.push(("focus-ring".into(), action));
643 }
644 if let Some(page) = get(&intents, "surface-page") {
645 // Modal scrim: a near-black tone carrying a faint hint of the theme's
646 // hue, at 50% alpha. Anchored very dark (OKLab L=0.08) so it dims the
647 // page on light *and* dark themes. Emitted as rgba (not a flat hex), so
648 // it is inserted directly rather than through the hex loop below.
649 let mut o = page.to_oklab();
650 o.l = 0.08;
651 let s = Rgb::from_oklab(o);
652 intents.insert(
653 "overlay".into(),
654 format!("rgba({}, {}, {}, 0.5)", s.r, s.g, s.b),
655 );
656 }
657 if let Some(raised) = get(&intents, "surface-raised") {
658 // The two edges of a bevel: a raised control is lit from the top left,
659 // so its top and left edges take `bevel-light` and its bottom and right
660 // edges `bevel-dark`. Inverting the pair gives a pressed state and an
661 // inset well, which is what makes the idiom cheap for a consumer.
662 //
663 // Derived here rather than composed per-app because the two webviews
664 // could do it in `color-mix()` and audiofiles, which is egui, could not.
665 // Geometry (thickness, radius, which side gets which) stays app-side.
666 //
667 // The deltas are asymmetric because the eye is: an equal step down reads
668 // as a smaller change than the same step up, so the shadow is cut deeper
669 // than the highlight is raised.
670 //
671 // A face already at the top of the ramp cannot hold a highlight — the
672 // lightening clamps and the control bevels on two sides without ever
673 // resolving as lit. That is a property of the theme, not of this
674 // derivation; `bevel_edges_are_distinct_from_their_face` names the
675 // shipped themes it currently bites.
676 derived.push(("bevel-light".into(), lighten(raised, 0.14)));
677 derived.push(("bevel-dark".into(), darken(raised, 0.18)));
678
679 // An inset well: the content surface inside a raised container, so a
680 // list reads as content in a container rather than as bands on a panel.
681 // `surface-sunken` cannot serve, because a theme is free to author it
682 // darker than raised (goingson does) and a well has to go the other way.
683 //
684 // Which way is "the other way" depends on the theme, and this is the one
685 // derivation here that inverts. A well is lighter than its face on a
686 // light theme and darker on a dark one, where the bevel pair sidesteps
687 // the question by emitting both directions at once.
688 //
689 // Read the direction off `content` rather than off `Variant`. A theme
690 // whose text is dark is a theme whose surfaces are light, whatever its
691 // `variant` field claims, so this resolves correctly even when that
692 // field is wrong and it keeps the branch on measured color rather than
693 // on metadata.
694 //
695 // Deltas are asymmetric for the same reason the bevel's are, and smaller
696 // than the bevel's because a well is an area rather than an edge. The
697 // step up is the specimen's, measured: #D9DDF4 to #F3F5FD is 0.069.
698 //
699 // A face at the top of its ramp cannot hold a lighter well, the same
700 // clamp `bevel-light` hits; `well_is_visible_against_its_face` names the
701 // shipped themes where it bites.
702 if let Some(content) = get(&intents, "content") {
703 let content_is_darker = content.to_oklab().l < raised.to_oklab().l;
704 let well = if content_is_darker {
705 lighten(raised, 0.07)
706 } else {
707 darken(raised, 0.09)
708 };
709 derived.push(("surface-well".into(), well));
710 }
711 }
712 if let Some(sunken) = get(&intents, "surface-sunken") {
713 derived.push(("hover-surface".into(), sunken));
714 }
715 if let Some(border) = get(&intents, "border") {
716 derived.push(("border-strong".into(), darken(border, 0.05)));
717 }
718
719 for (token, rgb) in derived {
720 intents.insert(token, rgb.to_hex());
721 }
722
723 SemanticTokens {
724 meta: theme.meta.clone(),
725 intents,
726 }
727 }
728
729 /// Emit the resolved intent layer as CSS declarations (no selector), one
730 /// ` --token: #hex;` line each, in deterministic (BTreeMap) order.
731 pub fn intent_css_declarations(tokens: &SemanticTokens) -> String {
732 let mut out = String::new();
733 for (token, hex) in &tokens.intents {
734 out.push_str(" --");
735 out.push_str(token);
736 out.push_str(": ");
737 out.push_str(hex);
738 out.push_str(";\n");
739 }
740 out
741 }
742
743 /// Emit the resolved intent layer as a `:root { … }` block — the single TOML →
744 /// CSS mapping every web surface injects.
745 pub fn intent_css_vars(tokens: &SemanticTokens) -> String {
746 format!(":root {{\n{}}}\n", intent_css_declarations(tokens))
747 }
748
749 // ============================================================================
750 // Loading / parsing
751 // ============================================================================
752
753 /// Validate a theme ID contains only safe characters (alphanumeric, hyphens, underscores).
754 pub fn validate_theme_id(id: &str) -> Result<(), String> {
755 if !id
756 .chars()
757 .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
758 {
759 return Err(format!("Invalid theme ID: {id}"));
760 }
761 Ok(())
762 }
763
764 /// Parse the `[meta]` section into `ThemeMeta`.
765 ///
766 /// Falls back to the file ID as the name and `"dark"` as the variant.
767 pub fn parse_meta(id: &str, table: &toml::Table, is_custom: bool) -> ThemeMeta {
768 let meta = table.get("meta").and_then(|m| m.as_table());
769 let name = meta
770 .and_then(|m| m.get("name"))
771 .and_then(|v| v.as_str())
772 .unwrap_or(id)
773 .to_string();
774 let variant = meta
775 .and_then(|m| m.get("variant"))
776 .and_then(|v| v.as_str())
777 .unwrap_or("dark")
778 .to_string();
779
780 ThemeMeta {
781 id: id.to_string(),
782 name,
783 variant,
784 is_custom,
785 }
786 }
787
788 // ============================================================================
789 // Choosing a theme.
790 //
791 // The file half of this crate was always shared; the *selection* half was not,
792 // and four apps re-rolled it four ways. GoingsOn stores a "system" sentinel in
793 // localStorage, Balanced Breakfast treats an absent value as follow-the-system
794 // and hardcodes two theme ids as its light/dark pair, audiofiles keeps the id
795 // in a synced SQLite table, and the Alloy console parses COLORFGBG. They also
796 // disagreed about what a variant string means: this crate defaults a missing
797 // one to "dark" while alloy_tui parsed an unrecognized one as light.
798 //
799 // What cannot be shared is the store — localStorage, a synced config table and
800 // a TOML file are genuinely different places. What can be shared, and is here,
801 // is the *meaning*: one vocabulary for variants, one encoding for "what did the
802 // user choose", and one rule for turning that into an id that exists.
803 // ============================================================================
804
805 /// A theme's kind, as declared by `meta.variant`.
806 ///
807 /// Three, not two: one shipped theme is `high-contrast`, and an app that
808 /// matched on light-or-dark alone would quietly file it under the wrong one.
809 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
810 #[serde(rename_all = "kebab-case")]
811 pub enum Variant {
812 Light,
813 Dark,
814 HighContrast,
815 }
816
817 impl Variant {
818 /// The spelling used in a theme file and in [`ThemeMeta::variant`].
819 #[must_use]
820 pub const fn as_str(self) -> &'static str {
821 match self {
822 Variant::Light => "light",
823 Variant::Dark => "dark",
824 Variant::HighContrast => "high-contrast",
825 }
826 }
827
828 /// Read a variant string, or `None` if it names none of them.
829 #[must_use]
830 pub fn parse(raw: &str) -> Option<Self> {
831 match raw {
832 "light" => Some(Variant::Light),
833 "dark" => Some(Variant::Dark),
834 "high-contrast" => Some(Variant::HighContrast),
835 _ => None,
836 }
837 }
838 }
839
840 impl std::fmt::Display for Variant {
841 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
842 f.write_str(self.as_str())
843 }
844 }
845
846 /// Anything unrecognized reads as dark, which is what [`parse_meta`] already
847 /// does with a missing one. Consumers that guessed light for an unknown string
848 /// were disagreeing with the crate that produced it.
849 impl From<&str> for Variant {
850 fn from(raw: &str) -> Self {
851 Variant::parse(raw).unwrap_or(Variant::Dark)
852 }
853 }
854
855 impl ThemeMeta {
856 /// This theme's variant as a value rather than a string.
857 #[must_use]
858 pub fn kind(&self) -> Variant {
859 Variant::from(self.variant.as_str())
860 }
861 }
862
863 /// The spelling of "follow whatever the system is doing", in every store.
864 pub const FOLLOW: &str = "system";
865
866 /// What the user chose, as opposed to what is being rendered.
867 ///
868 /// The distinction is the whole point: `Follow` is a standing instruction that
869 /// resolves differently as the ambient mode changes, and a `Fixed` id is an
870 /// answer that does not. An app that stored only the rendered id could not tell
871 /// the two apart the next time the system flipped to dark.
872 #[derive(Debug, Clone, PartialEq, Eq, Default)]
873 pub enum ThemeSelection {
874 /// Track the ambient light/dark mode.
875 #[default]
876 Follow,
877 /// Always this theme.
878 Fixed(String),
879 }
880
881 impl ThemeSelection {
882 /// Read a stored selection. An empty or absent value is [`Follow`], which
883 /// is what an app with nothing saved yet should do.
884 ///
885 /// [`Follow`]: ThemeSelection::Follow
886 #[must_use]
887 pub fn parse(raw: Option<&str>) -> Self {
888 match raw.map(str::trim) {
889 None | Some("" | FOLLOW) => ThemeSelection::Follow,
890 Some(id) => ThemeSelection::Fixed(id.to_string()),
891 }
892 }
893
894 /// The string to persist, whatever the store is.
895 #[must_use]
896 pub fn as_str(&self) -> &str {
897 match self {
898 ThemeSelection::Follow => FOLLOW,
899 ThemeSelection::Fixed(id) => id,
900 }
901 }
902
903 /// Turn a selection into a theme id that exists.
904 ///
905 /// `ambient` is the light/dark mode the app learned however it can: a
906 /// `prefers-color-scheme` media query, an OS appearance API, `COLORFGBG`
907 /// from a terminal. `available` is what [`list_themes_from_dirs`] found.
908 ///
909 /// A `Fixed` id that is no longer on disk falls through to the same path as
910 /// `Follow` rather than being returned anyway. Themes are deletable in
911 /// three of the four apps, and handing back an id that will fail to load
912 /// only moves the error somewhere less helpful.
913 ///
914 /// The fallback chain is: the app's own default for the ambient mode if it
915 /// is installed, then any installed theme of that variant, then the app's
916 /// default regardless. The last step means this always returns something,
917 /// and an app with no theme directory at all gets the id it ships with and
918 /// the load error it would have had anyway.
919 #[must_use]
920 pub fn resolve(
921 &self,
922 ambient: Variant,
923 defaults: &ThemeDefaults,
924 available: &[ThemeMeta],
925 ) -> String {
926 let installed = |id: &str| available.iter().any(|meta| meta.id == id);
927
928 if let ThemeSelection::Fixed(id) = self
929 && installed(id)
930 {
931 return id.clone();
932 }
933
934 let preferred = defaults.for_variant(ambient);
935 if installed(preferred) {
936 return preferred.to_string();
937 }
938 available
939 .iter()
940 .find(|meta| meta.kind() == ambient)
941 .map_or_else(|| preferred.to_string(), |meta| meta.id.clone())
942 }
943 }
944
945 impl std::fmt::Display for ThemeSelection {
946 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
947 f.write_str(self.as_str())
948 }
949 }
950
951 /// The themes an app falls back to, one per ambient mode.
952 ///
953 /// App-specific on purpose: which theme is "the app's own" is the app's
954 /// identity, not this crate's business. What is shared is everything around it.
955 #[derive(Debug, Clone)]
956 pub struct ThemeDefaults {
957 light: String,
958 dark: String,
959 high_contrast: Option<String>,
960 }
961
962 impl ThemeDefaults {
963 pub fn new(light: impl Into<String>, dark: impl Into<String>) -> Self {
964 Self {
965 light: light.into(),
966 dark: dark.into(),
967 high_contrast: None,
968 }
969 }
970
971 /// Name a theme for a high-contrast ambient mode. Without one, that mode
972 /// falls back to the dark default, which is the safer of the two to read.
973 #[must_use]
974 pub fn high_contrast(mut self, id: impl Into<String>) -> Self {
975 self.high_contrast = Some(id.into());
976 self
977 }
978
979 #[must_use]
980 pub fn for_variant(&self, variant: Variant) -> &str {
981 match variant {
982 Variant::Light => &self.light,
983 Variant::Dark => &self.dark,
984 Variant::HighContrast => self.high_contrast.as_ref().unwrap_or(&self.dark),
985 }
986 }
987 }
988
989 // ============================================================================
990 // Where themes are looked for.
991 //
992 // Four apps built this vector by hand, two of them byte-for-byte identically,
993 // and one of them built it backwards: the Alloy console pushed the user's own
994 // directory first, under a comment saying "highest precedence first", when both
995 // consumers of the vector resolve *last* wins. A user's custom theme lost to
996 // the packaged one of the same id.
997 //
998 // Hence a builder that names the tiers rather than a function taking a vector.
999 // The precedence is stated once, here, and a caller cannot express it backwards
1000 // because the order is not theirs to choose.
1001 // ============================================================================
1002
1003 /// Builds the search path [`load_theme`] and [`list_themes_from_dirs`] take.
1004 ///
1005 /// Tiers are added in whatever order is convenient and always end up in
1006 /// precedence order: the user's own themes win, then whatever the system
1007 /// ships, then whatever the app bundles.
1008 ///
1009 /// A directory that does not exist is dropped rather than carried, so callers
1010 /// can offer every tier they might have without checking each one.
1011 #[derive(Debug, Default, Clone)]
1012 pub struct ThemeDirs {
1013 bundled: Vec<PathBuf>,
1014 system: Vec<PathBuf>,
1015 custom: Option<PathBuf>,
1016 }
1017
1018 impl ThemeDirs {
1019 #[must_use]
1020 pub fn new() -> Self {
1021 Self::default()
1022 }
1023
1024 /// Themes the app ships with. Lowest precedence.
1025 ///
1026 /// Takes more than one because a Tauri app has two: the bundled resource
1027 /// directory in production, and the tree `build.rs` materialized for a
1028 /// `cargo run` that has no resource directory at all.
1029 #[must_use]
1030 pub fn bundled(mut self, dir: Option<PathBuf>) -> Self {
1031 self.bundled.extend(dir);
1032 self
1033 }
1034
1035 /// Themes the machine ships, from an image or a package. Overrides bundled.
1036 #[must_use]
1037 pub fn system(mut self, dir: Option<PathBuf>) -> Self {
1038 self.system.extend(dir);
1039 self
1040 }
1041
1042 /// The user's own themes. Highest precedence, and the only tier flagged
1043 /// custom, which is what makes them exportable and deletable.
1044 #[must_use]
1045 pub fn custom(mut self, dir: Option<PathBuf>) -> Self {
1046 self.custom = dir;
1047 self
1048 }
1049
1050 /// The search path, lowest precedence first.
1051 #[must_use]
1052 pub fn build(self) -> Vec<(PathBuf, bool)> {
1053 let mut dirs = Vec::new();
1054 for dir in self.bundled.into_iter().chain(self.system) {
1055 if dir.is_dir() {
1056 dirs.push((dir, false));
1057 }
1058 }
1059 if let Some(dir) = self.custom
1060 && dir.is_dir()
1061 {
1062 dirs.push((dir, true));
1063 }
1064 dirs
1065 }
1066 }
1067
1068 /// Extract the intent color sections into a flat `HashMap` with dotted keys
1069 /// like `"surface.page"`, `"status.danger"`, `"category.one"`.
1070 pub fn extract_colors(table: &toml::Table) -> HashMap<String, String> {
1071 let mut colors = HashMap::new();
1072 for section in COLOR_SECTIONS {
1073 if let Some(sect) = table.get(*section).and_then(|s| s.as_table()) {
1074 for (key, val) in sect {
1075 if let Some(color) = val.as_str() {
1076 colors.insert(format!("{section}.{key}"), color.to_string());
1077 }
1078 }
1079 }
1080 }
1081 colors
1082 }
1083
1084 /// Scan directories for `.toml` theme files and return metadata for each.
1085 ///
1086 /// Directories are checked in order; later entries override earlier ones by ID.
1087 /// Each entry in `dirs` is `(path, is_custom)`.
1088 pub fn list_themes_from_dirs(dirs: &[(PathBuf, bool)]) -> Vec<ThemeMeta> {
1089 let mut seen: HashMap<String, ThemeMeta> = HashMap::new();
1090
1091 for (dir, is_custom) in dirs {
1092 let Ok(entries) = std::fs::read_dir(dir) else {
1093 continue;
1094 };
1095
1096 for entry in entries {
1097 let Ok(entry) = entry else {
1098 continue;
1099 };
1100 let path = entry.path();
1101 if path.extension().and_then(|e| e.to_str()) != Some("toml") {
1102 continue;
1103 }
1104
1105 let id = path
1106 .file_stem()
1107 .and_then(|s| s.to_str())
1108 .unwrap_or_default()
1109 .to_string();
1110
1111 let Ok(content) = std::fs::read_to_string(&path) else {
1112 continue;
1113 };
1114 let table: toml::Table = match content.parse() {
1115 Ok(t) => t,
1116 Err(_) => continue,
1117 };
1118
1119 seen.insert(id.clone(), parse_meta(&id, &table, *is_custom));
1120 }
1121 }
1122
1123 let mut themes: Vec<ThemeMeta> = seen.into_values().collect();
1124 themes.sort_by(|a, b| a.name.cmp(&b.name));
1125 themes
1126 }
1127
1128 /// Find a theme file by ID in the given directories.
1129 ///
1130 /// Checks directories in reverse order so the highest-priority directory wins.
1131 /// Returns `(path, is_custom)` or `None` if not found.
1132 pub fn find_theme_path(dirs: &[(PathBuf, bool)], id: &str) -> Option<(PathBuf, bool)> {
1133 let filename = format!("{id}.toml");
1134
1135 for (dir, is_custom) in dirs.iter().rev() {
1136 let path = dir.join(&filename);
1137 if path.is_file() {
1138 return Some((path, *is_custom));
1139 }
1140 }
1141
1142 None
1143 }
1144
1145 /// Parse a complete theme (metadata + colors) from raw TOML content, with no
1146 /// filesystem access. For callers that embed themes at compile time.
1147 pub fn parse_theme_str(id: &str, content: &str, is_custom: bool) -> Result<ThemeColors, String> {
1148 validate_theme_id(id)?;
1149 let table: toml::Table = content
1150 .parse()
1151 .map_err(|e| format!("Failed to parse theme '{id}': {e}"))?;
1152 let meta = parse_meta(id, &table, is_custom);
1153 let colors = extract_colors(&table);
1154 Ok(ThemeColors { meta, colors })
1155 }
1156
1157 /// Load a complete theme (metadata + colors) by ID from the given directories.
1158 pub fn load_theme(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemeColors, String> {
1159 validate_theme_id(id)?;
1160
1161 let (path, is_custom) =
1162 find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
1163
1164 let content = std::fs::read_to_string(&path)
1165 .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
1166
1167 let table: toml::Table = content
1168 .parse()
1169 .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
1170
1171 let meta = parse_meta(id, &table, is_custom);
1172 let colors = extract_colors(&table);
1173
1174 Ok(ThemeColors { meta, colors })
1175 }
1176
1177 /// Load a theme and resolve it to the full intent token set in one step.
1178 pub fn load_semantic(dirs: &[(PathBuf, bool)], id: &str) -> Result<SemanticTokens, String> {
1179 Ok(resolve(&load_theme(dirs, id)?))
1180 }
1181
1182 /// Import a theme TOML file into the custom themes directory.
1183 ///
1184 /// Validates that the file is parseable TOML with at least one intent color
1185 /// section, then copies it to `custom_dir/{id}.toml`. Returns the theme metadata.
1186 pub fn import_theme(source_path: &Path, custom_dir: &Path) -> Result<ThemeMeta, String> {
1187 let content = std::fs::read_to_string(source_path)
1188 .map_err(|e| format!("Failed to read {}: {}", source_path.display(), e))?;
1189
1190 let table: toml::Table = content.parse().map_err(|e| format!("Invalid TOML: {e}"))?;
1191
1192 let has_colors = COLOR_SECTIONS
1193 .iter()
1194 .any(|s| table.get(*s).and_then(|v| v.as_table()).is_some());
1195 if !has_colors {
1196 return Err(format!(
1197 "Theme file must have at least one color section ({})",
1198 COLOR_SECTIONS.join(", ")
1199 ));
1200 }
1201
1202 let id = source_path
1203 .file_stem()
1204 .and_then(|s| s.to_str())
1205 .ok_or("Invalid file name")?
1206 .to_string();
1207 validate_theme_id(&id)?;
1208
1209 std::fs::create_dir_all(custom_dir)
1210 .map_err(|e| format!("Failed to create {}: {}", custom_dir.display(), e))?;
1211
1212 let dest = custom_dir.join(format!("{id}.toml"));
1213 std::fs::copy(source_path, &dest).map_err(|e| format!("Failed to copy theme: {e}"))?;
1214
1215 Ok(parse_meta(&id, &table, true))
1216 }
1217
1218 /// Delete a custom theme by ID.
1219 ///
1220 /// Only operates on `custom_dir` — bundled themes are not deletable through
1221 /// this entry point.
1222 pub fn delete_theme(custom_dir: &Path, id: &str) -> Result<(), String> {
1223 validate_theme_id(id)?;
1224
1225 let path = custom_dir.join(format!("{id}.toml"));
1226 if !path.is_file() {
1227 return Err(format!("Custom theme '{id}' not found"));
1228 }
1229
1230 std::fs::remove_file(&path).map_err(|e| format!("Failed to delete {}: {}", path.display(), e))
1231 }
1232
1233 /// A four-color preview for theme thumbnails: the representative swatch from
1234 /// each of the principal roles.
1235 #[derive(Debug, Clone, Serialize)]
1236 #[serde(rename_all = "camelCase")]
1237 pub struct ThemePreview {
1238 pub meta: ThemeMeta,
1239 /// Page background (`surface.page`).
1240 pub background: Option<String>,
1241 /// Body text (`content.primary`).
1242 pub foreground: Option<String>,
1243 /// Brand/interactive color (`action.primary`).
1244 pub accent: Option<String>,
1245 /// Divider/outline color (`line.border`).
1246 pub border: Option<String>,
1247 }
1248
1249 fn color_at(table: &toml::Table, section: &str, key: &str) -> Option<String> {
1250 table
1251 .get(section)
1252 .and_then(|s| s.as_table())
1253 .and_then(|s| s.get(key))
1254 .and_then(|v| v.as_str())
1255 .map(std::string::ToString::to_string)
1256 }
1257
1258 /// Load just the preview swatches for a theme — for UI thumbnails.
1259 pub fn load_theme_preview(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemePreview, String> {
1260 validate_theme_id(id)?;
1261
1262 let (path, is_custom) =
1263 find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
1264
1265 let content = std::fs::read_to_string(&path)
1266 .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
1267
1268 let table: toml::Table = content
1269 .parse()
1270 .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
1271
1272 Ok(ThemePreview {
1273 meta: parse_meta(id, &table, is_custom),
1274 background: color_at(&table, "surface", "page"),
1275 foreground: color_at(&table, "content", "primary"),
1276 accent: color_at(&table, "action", "primary"),
1277 border: color_at(&table, "line", "border"),
1278 })
1279 }
1280
1281 /// Export a theme to a user-chosen path.
1282 pub fn export_theme(dirs: &[(PathBuf, bool)], id: &str, dest_path: &Path) -> Result<(), String> {
1283 validate_theme_id(id)?;
1284
1285 let (source, _) = find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
1286
1287 std::fs::copy(&source, dest_path).map_err(|e| format!("Failed to export theme: {e}"))?;
1288
1289 Ok(())
1290 }
1291
1292 /// The themes this crate ships, embedded at compile time.
1293 ///
1294 /// `include_dir` is an implementation detail: the public API hands back plain
1295 /// `(id, toml_source)` pairs, so how the data is embedded can change without
1296 /// a breaking release.
1297 static EMBEDDED: include_dir::Dir<'static> =
1298 include_dir::include_dir!("$CARGO_MANIFEST_DIR/themes");
1299
1300 /// The themes this crate ships, as `(id, toml_source)` pairs.
1301 ///
1302 /// This is the path-free way to reach the bundled set, for consumers that
1303 /// cannot rely on a directory existing at runtime: a crate pulled from
1304 /// crates.io lives in a registry checkout whose location is not knowable at
1305 /// compile time, so `include_dir!` and asset-bundling globs in the depending
1306 /// crate have nothing stable to point at. Embedding here and re-exporting the
1307 /// contents gives them one source of truth without a path.
1308 ///
1309 /// Ordering follows the embedded directory and is not guaranteed; collect and
1310 /// sort by id where a stable order matters (a theme picker, say).
1311 pub fn embedded_themes() -> impl Iterator<Item = (&'static str, &'static str)> {
1312 EMBEDDED.files().filter_map(|file| {
1313 let path = file.path();
1314 if path.extension().and_then(|e| e.to_str()) != Some("toml") {
1315 return None;
1316 }
1317 let id = path.file_stem()?.to_str()?;
1318 Some((id, file.contents_utf8()?))
1319 })
1320 }
1321
1322 /// The theme directory this crate ships, for use as a build-from-source
1323 /// fallback.
1324 ///
1325 /// Resolves against `makeover`'s own manifest directory, fixed at compile
1326 /// time, so it works from a path dependency and from a cargo git checkout
1327 /// alike. Installed systems should put their packaged theme directory ahead
1328 /// of this in the search path; this is the entry that keeps `cargo run` in a
1329 /// fresh clone from coming up with no themes at all.
1330 ///
1331 /// Returns `None` when the directory is absent — a cargo cache that has been
1332 /// cleaned, or a vendored copy that dropped the data — so callers degrade to
1333 /// their remaining search path rather than failing.
1334 pub fn bundled_themes_dir() -> Option<PathBuf> {
1335 let themes = Path::new(env!("CARGO_MANIFEST_DIR")).join("themes");
1336 if themes.is_dir() { Some(themes) } else { None }
1337 }
1338
1339 #[cfg(test)]
1340 mod tests {
1341 use super::*;
1342 use std::fs;
1343
1344 // ---- id validation ----
1345
1346 #[test]
1347 fn validate_theme_id_alphanumeric() {
1348 assert!(validate_theme_id("darkmode").is_ok());
1349 assert!(validate_theme_id("Theme123").is_ok());
1350 }
1351
1352 #[test]
1353 fn validate_theme_id_hyphens_underscores() {
1354 assert!(validate_theme_id("dark-mode").is_ok());
1355 assert!(validate_theme_id("my_theme_v2").is_ok());
1356 }
1357
1358 #[test]
1359 fn validate_theme_id_rejects_path_traversal() {
1360 assert!(validate_theme_id("../etc/passwd").is_err());
1361 assert!(validate_theme_id("foo/bar").is_err());
1362 assert!(validate_theme_id("theme.toml").is_err());
1363 }
1364
1365 // ---- low-color terminals ----
1366
1367 #[test]
1368 fn the_ansi_palette_is_sixteen_distinct_colors() {
1369 let mut seen: Vec<(u8, u8, u8)> = ANSI_16.iter().map(|c| c.tuple()).collect();
1370 seen.sort_unstable();
1371 seen.dedup();
1372 assert_eq!(seen.len(), 16);
1373 }
1374
1375 // ---- the intent-to-slot table ----
1376
1377 // Sixteen slots, every one of them answered. A caller filling a terminal
1378 // palette has no fallback for a hole: the slot would keep whatever the
1379 // emulator started with, and one raw ANSI colour in a themed table is more
1380 // obviously wrong than all sixteen would be.
1381 #[test]
1382 fn every_ansi_slot_names_an_intent_on_either_polarity() {
1383 for variant in ["light", "dark", "high-contrast"] {
1384 for index in 0..16 {
1385 assert!(
1386 ansi_intent(index, variant).is_some(),
1387 "slot {index} unanswered on {variant}"
1388 );
1389 }
1390 assert_eq!(ansi_intent(16, variant), None);
1391 }
1392 }
1393
1394 // The property the four achromatic slots exist to hold: 0 is the darkest
1395 // tone the theme offers and 15 the lightest, in either polarity. A table
1396 // that pins slot 0 to `content.primary` passes this on a light theme and
1397 // inverts on a dark one, which is the bug the polarity split fixes.
1398 #[test]
1399 fn ansi_zero_is_darker_than_ansi_fifteen_on_either_polarity() {
1400 for id in ["akari-dawn", "akari-night"] {
1401 let theme = bundled(id);
1402 let slot = |i: usize| -> Rgb {
1403 let key = ansi_intent(i, &theme.meta.variant).expect("in range");
1404 Rgb::from_hex(theme.colors.get(key).expect("theme carries it")).expect("valid hex")
1405 };
1406 assert!(
1407 rel_luminance(slot(0)) < rel_luminance(slot(15)),
1408 "{id}: ANSI 0 {} should be darker than ANSI 15 {}",
1409 slot(0).to_hex(),
1410 slot(15).to_hex(),
1411 );
1412 }
1413 }
1414
1415 // The pair a greeter draws with: its container on 7, its text on 0. If
1416 // those collapse the login screen is one flat block, and slot 7 being a
1417 // surface rather than a text tone is what keeps them apart.
1418 #[test]
1419 fn the_container_slot_and_the_text_slot_stay_legible() {
1420 for id in ["akari-dawn", "akari-night"] {
1421 let theme = bundled(id);
1422 let slot = |i: usize| -> Rgb {
1423 let key = ansi_intent(i, &theme.meta.variant).expect("in range");
1424 Rgb::from_hex(theme.colors.get(key).expect("theme carries it")).expect("valid hex")
1425 };
1426 let contrast = wcag_contrast(slot(0), slot(7));
1427 assert!(contrast >= 4.5, "{id}: ANSI 0 on ANSI 7 is {contrast:.2}:1");
1428 }
1429 }
1430
1431 // The hues do not move with polarity. Red is the theme's danger tone on a
1432 // light theme and on a dark one, which is why only four slots are in the
1433 // polarity table at all.
1434 #[test]
1435 fn the_chromatic_slots_do_not_vary_with_polarity() {
1436 for index in [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14] {
1437 assert_eq!(
1438 ansi_intent(index, "light"),
1439 ansi_intent(index, "dark"),
1440 "slot {index} moved with polarity"
1441 );
1442 }
1443 }
1444
1445 fn bundled(id: &str) -> ThemeColors {
1446 let dir = bundled_themes_dir().expect("makeover ships its themes");
1447 load_theme(&[(dir, false)], id).expect("the akari pair ships")
1448 }
1449
1450 #[test]
1451 fn quantize_picks_the_obvious_entry() {
1452 let black = Rgb { r: 0, g: 0, b: 0 };
1453 let white = Rgb {
1454 r: 255,
1455 g: 255,
1456 b: 255,
1457 };
1458 assert_eq!(quantize(black, &ANSI_16), 0);
1459 assert_eq!(quantize(white, &ANSI_16), 15);
1460 }
1461
1462 // Nearest-entry quantization is per-color, so two colors a theme keeps
1463 // apart can arrive as one. These two are both closest to the palette's
1464 // light gray, and a border drawn in one on a page painted the other is not
1465 // drawn at all.
1466 #[test]
1467 fn two_colors_can_quantize_to_one_entry() {
1468 let page = Rgb::from_hex("#a8a8a8").unwrap();
1469 let border = Rgb::from_hex("#b4b4b4").unwrap();
1470
1471 assert_eq!(quantize(page, &ANSI_16), quantize(border, &ANSI_16));
1472 assert!(quantize_against(border, page, &ANSI_16) != quantize(page, &ANSI_16));
1473 }
1474
1475 #[test]
1476 fn quantize_against_keeps_the_border_off_the_page() {
1477 let page = Rgb::from_hex("#e4ded6").unwrap();
1478 let border = Rgb::from_hex("#7f786d").unwrap();
1479
1480 let shown_page = ANSI_16[quantize(page, &ANSI_16)];
1481 let shown_border = ANSI_16[quantize_against(border, page, &ANSI_16)];
1482
1483 assert!(
1484 wcag_contrast(shown_border, shown_page) >= DISTINCT,
1485 "border {} on page {} is {:.2}:1",
1486 shown_border.to_hex(),
1487 shown_page.to_hex(),
1488 wcag_contrast(shown_border, shown_page)
1489 );
1490 }
1491
1492 // A color that already reads against its background is left where it is,
1493 // so this can be applied without redesigning what already worked.
1494 #[test]
1495 fn quantize_against_leaves_a_readable_color_alone() {
1496 let page = Rgb::from_hex("#e4ded6").unwrap();
1497 let text = Rgb::from_hex("#1a1816").unwrap();
1498
1499 assert_eq!(
1500 quantize_against(text, page, &ANSI_16),
1501 quantize(text, &ANSI_16)
1502 );
1503 }
1504
1505 // With nothing in the palette to satisfy the request, the most legible
1506 // entry is the answer. Returning the nearest one would return the
1507 // background itself, which is the failure this function exists to avoid.
1508 #[test]
1509 fn an_impossible_palette_gets_the_most_legible_entry() {
1510 let page = Rgb::from_hex("#ffffff").unwrap();
1511 let border = Rgb::from_hex("#fefefe").unwrap();
1512 let palette = [
1513 Rgb::from_hex("#ffffff").unwrap(),
1514 Rgb::from_hex("#fdfdfd").unwrap(),
1515 ];
1516
1517 let chosen = palette[quantize_against(border, page, &palette)];
1518 assert_eq!(chosen.to_hex(), "#fdfdfd");
1519 }
1520
1521 // ---- meta ----
1522
1523 #[test]
1524 fn parse_meta_with_name_and_variant() {
1525 let table: toml::Table = "[meta]\nname = \"Nord\"\nvariant = \"light\"\n"
1526 .parse()
1527 .unwrap();
1528 let meta = parse_meta("nord", &table, false);
1529 assert_eq!(meta.id, "nord");
1530 assert_eq!(meta.name, "Nord");
1531 assert_eq!(meta.variant, "light");
1532 assert!(!meta.is_custom);
1533 }
1534
1535 #[test]
1536 fn parse_meta_defaults_to_id_and_dark() {
1537 let table: toml::Table = "".parse().unwrap();
1538 let meta = parse_meta("fallback", &table, true);
1539 assert_eq!(meta.name, "fallback");
1540 assert_eq!(meta.variant, "dark");
1541 assert!(meta.is_custom);
1542 }
1543
1544 // ---- color math (formulas must match the apps they came from) ----
1545
1546 #[test]
1547 fn rgb_hex_roundtrip() {
1548 assert_eq!(
1549 Rgb::from_hex("#6196FF").unwrap(),
1550 Rgb {
1551 r: 0x61,
1552 g: 0x96,
1553 b: 0xff
1554 }
1555 );
1556 assert_eq!(
1557 Rgb::from_hex("#abc").unwrap(),
1558 Rgb {
1559 r: 0xaa,
1560 g: 0xbb,
1561 b: 0xcc
1562 }
1563 );
1564 assert_eq!(
1565 Rgb {
1566 r: 0x61,
1567 g: 0x96,
1568 b: 0xff
1569 }
1570 .to_hex(),
1571 "#6196ff"
1572 );
1573 assert!(Rgb::from_hex("not-a-color").is_none());
1574 }
1575
1576 #[test]
1577 fn oklab_roundtrips_within_tolerance() {
1578 for hex in ["#6196ff", "#2e3440", "#ffffff", "#000000", "#c0392b"] {
1579 let c = Rgb::from_hex(hex).unwrap();
1580 let back = Rgb::from_oklab(c.to_oklab());
1581 // Gamut round-trip is near-exact (±1 per channel from rounding).
1582 assert!((c.r as i16 - back.r as i16).abs() <= 1, "{hex} r");
1583 assert!((c.g as i16 - back.g as i16).abs() <= 1, "{hex} g");
1584 assert!((c.b as i16 - back.b as i16).abs() <= 1, "{hex} b");
1585 }
1586 }
1587
1588 #[test]
1589 fn wcag_contrast_known_pairs() {
1590 let white = Rgb {
1591 r: 255,
1592 g: 255,
1593 b: 255,
1594 };
1595 let black = Rgb { r: 0, g: 0, b: 0 };
1596 assert!((wcag_contrast(white, black) - 21.0).abs() < 0.01);
1597 assert!((wcag_contrast(white, white) - 1.0).abs() < 0.01);
1598 }
1599
1600 #[test]
1601 fn readable_on_picks_by_wcag() {
1602 assert_eq!(
1603 readable_on(Rgb {
1604 r: 255,
1605 g: 255,
1606 b: 255
1607 }),
1608 Rgb { r: 0, g: 0, b: 0 }
1609 );
1610 assert_eq!(
1611 readable_on(Rgb { r: 0, g: 0, b: 0 }),
1612 Rgb {
1613 r: 255,
1614 g: 255,
1615 b: 255
1616 }
1617 );
1618 // A light blue action -> black text reads better.
1619 let action = Rgb::from_hex("#6196ff").unwrap();
1620 assert_eq!(readable_on(action), Rgb { r: 0, g: 0, b: 0 });
1621 }
1622
1623 #[test]
1624 fn lighten_darken_move_oklab_lightness() {
1625 let c = Rgb::from_hex("#6196ff").unwrap();
1626 let l0 = c.to_oklab().l;
1627 assert!(lighten(c, 0.05).to_oklab().l > l0);
1628 assert!(darken(c, 0.05).to_oklab().l < l0);
1629 }
1630
1631 #[test]
1632 fn mix_endpoints_and_midpoint() {
1633 let a = Rgb::from_hex("#000000").unwrap();
1634 let b = Rgb::from_hex("#6196ff").unwrap();
1635 assert_eq!(mix(a, b, 0.0), a);
1636 assert_eq!(mix(a, b, 1.0), b);
1637 // Midpoint sits between the endpoints in OKLab lightness.
1638 let mid = mix(a, b, 0.5).to_oklab().l;
1639 assert!(mid > a.to_oklab().l && mid < b.to_oklab().l);
1640 }
1641
1642 // ---- extract + resolve ----
1643
1644 fn nord_toml() -> &'static str {
1645 r##"
1646 [meta]
1647 name = "Nord"
1648 variant = "dark"
1649
1650 [surface]
1651 page = "#2e3440"
1652 raised = "#3b4252"
1653 sunken = "#434c5e"
1654 overlay = "#3b4252"
1655
1656 [content]
1657 primary = "#d8dee9"
1658 secondary = "#e5e9f0"
1659 muted = "#616e88"
1660
1661 [action]
1662 primary = "#81a1c1"
1663
1664 [status]
1665 danger = "#bf616a"
1666 success = "#a3be8c"
1667 warning = "#ebcb8b"
1668 info = "#88c0d0"
1669
1670 [line]
1671 border = "#4c566a"
1672
1673 [category]
1674 one = "#bf616a"
1675 two = "#a3be8c"
1676 three = "#81a1c1"
1677 four = "#ebcb8b"
1678 five = "#b48ead"
1679 six = "#88c0d0"
1680 "##
1681 }
1682
1683 #[test]
1684 fn extract_colors_reads_intent_sections() {
1685 let table: toml::Table = nord_toml().parse().unwrap();
1686 let colors = extract_colors(&table);
1687 assert_eq!(colors.get("surface.page").unwrap(), "#2e3440");
1688 assert_eq!(colors.get("content.primary").unwrap(), "#d8dee9");
1689 assert_eq!(colors.get("action.primary").unwrap(), "#81a1c1");
1690 assert_eq!(colors.get("status.danger").unwrap(), "#bf616a");
1691 assert_eq!(colors.get("line.border").unwrap(), "#4c566a");
1692 assert_eq!(colors.get("category.five").unwrap(), "#b48ead");
1693 assert_eq!(colors.len(), 19);
1694 }
1695
1696 #[test]
1697 fn resolve_base_intents_passthrough() {
1698 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1699 let t = resolve(&theme);
1700 assert_eq!(t.hex("surface-page"), Some("#2e3440"));
1701 assert_eq!(t.hex("content"), Some("#d8dee9")); // content.primary -> content
1702 assert_eq!(t.hex("content-muted"), Some("#616e88"));
1703 assert_eq!(t.hex("action"), Some("#81a1c1"));
1704 assert_eq!(t.hex("danger"), Some("#bf616a"));
1705 assert_eq!(t.hex("border"), Some("#4c566a"));
1706 assert_eq!(t.hex("category-five"), Some("#b48ead"));
1707 }
1708
1709 #[test]
1710 fn resolve_derived_intents() {
1711 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1712 let t = resolve(&theme);
1713 let action = Rgb::from_hex("#81a1c1").unwrap();
1714 let page = Rgb::from_hex("#2e3440").unwrap();
1715 let _ = page;
1716 assert_eq!(
1717 t.hex("action-hover").unwrap(),
1718 lighten(action, 0.05).to_hex()
1719 );
1720 assert_eq!(
1721 t.hex("content-on-action").unwrap(),
1722 readable_on(action).to_hex()
1723 );
1724 assert_eq!(t.hex("focus-ring"), Some("#81a1c1"));
1725 assert_eq!(t.hex("hover-surface"), Some("#434c5e")); // = surface.sunken
1726 // Pruned by the usage audit (0 consumers): action-active, the *-surface
1727 // tints, selection, row-stripe. Apps that need them derive inline via
1728 // the shared mix().
1729 assert!(t.hex("action-active").is_none());
1730 assert!(t.hex("danger-surface").is_none());
1731 assert!(t.hex("selection").is_none());
1732 assert!(t.hex("row-stripe").is_none());
1733 }
1734
1735 #[test]
1736 fn resolve_bevel_intents() {
1737 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1738 let t = resolve(&theme);
1739 let raised = Rgb::from_hex("#3b4252").unwrap();
1740 assert_eq!(
1741 t.hex("bevel-light").unwrap(),
1742 lighten(raised, 0.14).to_hex()
1743 );
1744 assert_eq!(t.hex("bevel-dark").unwrap(), darken(raised, 0.18).to_hex());
1745 }
1746
1747 // A bevel is two edges around one face, so both edges have to be visibly off
1748 // that face or the control never resolves as lit. The lightening clamps at
1749 // the top of the ramp, which means a theme authoring a white raised surface
1750 // gets a highlight identical to the surface it is meant to sit on.
1751 //
1752 // The list is asserted rather than merely reported so that changing a theme
1753 // has to come here and say so. Shrinking it is the fix; growing it is a
1754 // regression in the theme, not in this derivation.
1755 #[test]
1756 fn bevel_edges_are_distinct_from_their_face() {
1757 const CANNOT_BEVEL: &[&str] = &["neobrute", "oxocarbon-light"];
1758
1759 let mut degenerate: Vec<String> = Vec::new();
1760 for (id, source) in embedded_themes() {
1761 let theme = parse_theme_str(id, source, false).unwrap();
1762 let t = resolve(&theme);
1763 let Some(raised) = t.hex("surface-raised") else {
1764 continue;
1765 };
1766 let light = t.hex("bevel-light").expect("raised implies bevel-light");
1767 let dark = t.hex("bevel-dark").expect("raised implies bevel-dark");
1768 if light == raised || dark == raised {
1769 degenerate.push(id.to_string());
1770 }
1771 }
1772 degenerate.sort();
1773
1774 assert_eq!(
1775 degenerate, CANNOT_BEVEL,
1776 "themes whose raised surface cannot hold both bevel edges"
1777 );
1778 }
1779
1780 // The well inverts by theme, so assert both directions explicitly rather
1781 // than only the one the light themes happen to take.
1782 #[test]
1783 fn resolve_well_intent_follows_the_content_direction() {
1784 // nord is dark: light text on a dark raised surface, so the well goes
1785 // down and away from the text.
1786 let dark = resolve(&parse_theme_str("nord", nord_toml(), false).unwrap());
1787 let dark_raised = Rgb::from_hex("#3b4252").unwrap();
1788 assert_eq!(
1789 dark.hex("surface-well").unwrap(),
1790 darken(dark_raised, 0.09).to_hex()
1791 );
1792
1793 // The shipped light themes take the other branch.
1794 let goingson = embedded_themes()
1795 .into_iter()
1796 .find(|(id, _)| *id == "goingson")
1797 .expect("goingson is embedded")
1798 .1;
1799 let light = resolve(&parse_theme_str("goingson", goingson, false).unwrap());
1800 let light_raised = light
1801 .hex("surface-raised")
1802 .and_then(Rgb::from_hex)
1803 .expect("goingson authors a raised surface");
1804 assert_eq!(
1805 light.hex("surface-well").unwrap(),
1806 lighten(light_raised, 0.07).to_hex()
1807 );
1808 }
1809
1810 // A well is a fill, not an edge, so the only thing that makes it read is
1811 // being a different color from the surface it is cut into.
1812 //
1813 // Same shape and the same asserted-list discipline as
1814 // `bevel_edges_are_distinct_from_their_face`, and it bites the same two
1815 // themes for the same reason: a raised surface already at the top of the
1816 // ramp has nothing lighter to go to.
1817 #[test]
1818 fn well_is_distinct_from_its_face() {
1819 const CANNOT_WELL: &[&str] = &["neobrute", "oxocarbon-light"];
1820
1821 let mut degenerate: Vec<String> = Vec::new();
1822 for (id, source) in embedded_themes() {
1823 let theme = parse_theme_str(id, source, false).unwrap();
1824 let t = resolve(&theme);
1825 let Some(raised) = t.hex("surface-raised") else {
1826 continue;
1827 };
1828 let well = t.hex("surface-well").expect("raised implies surface-well");
1829 if well == raised {
1830 degenerate.push(id.to_string());
1831 }
1832 }
1833 degenerate.sort();
1834
1835 assert_eq!(
1836 degenerate, CANNOT_WELL,
1837 "themes whose raised surface cannot hold a well"
1838 );
1839 }
1840
1841 // Distinct is not the same as visible. A face near the top of the ramp
1842 // clamps partway rather than exactly, which yields a well that differs from
1843 // its face by a hex digit and by nothing the eye can find. `rosepine-dawn`
1844 // authors raised at L=0.987 and gets 0.009 of the 0.07 it asked for.
1845 //
1846 // Worth a separate test from the one above because the fix differs: an
1847 // exactly-degenerate theme needs its raised surface off the ramp end, while
1848 // these need it merely lowered. Both fixes are the theme's, not this
1849 // derivation's, which is why the list is asserted rather than warned about.
1850 #[test]
1851 fn well_is_visible_against_its_face() {
1852 // Below this, the well and its face are the same surface to a reader.
1853 const MIN_DELTA_L: f32 = 0.02;
1854 const CANNOT_HOLD_A_VISIBLE_WELL: &[&str] =
1855 &["neobrute", "oxocarbon-light", "rosepine-dawn"];
1856
1857 let mut invisible: Vec<String> = Vec::new();
1858 for (id, source) in embedded_themes() {
1859 let theme = parse_theme_str(id, source, false).unwrap();
1860 let t = resolve(&theme);
1861 let (Some(raised), Some(well)) = (
1862 t.hex("surface-raised").and_then(Rgb::from_hex),
1863 t.hex("surface-well").and_then(Rgb::from_hex),
1864 ) else {
1865 continue;
1866 };
1867 if (well.to_oklab().l - raised.to_oklab().l).abs() < MIN_DELTA_L {
1868 invisible.push(id.to_string());
1869 }
1870 }
1871 invisible.sort();
1872
1873 assert_eq!(
1874 invisible, CANNOT_HOLD_A_VISIBLE_WELL,
1875 "themes whose well is too close to its face to read as one"
1876 );
1877 }
1878
1879 // What the bevel pair does on a sixteen-color terminal, measured across the
1880 // shipped set rather than assumed. Two results, both load-bearing for a
1881 // consumer that has to render one there.
1882 //
1883 // Exactly one edge survives, never both. A raised face quantizes onto one of
1884 // the palette's three grays, and the palette is too coarse to hold anything
1885 // between that entry and its neighbour, so whichever edge is pushed toward
1886 // the end of the ramp the face already sits on lands back on the face. Light
1887 // themes and most dark ones keep the shadow and lose the highlight; a face
1888 // that quantizes to black keeps the highlight and loses the shadow.
1889 //
1890 // So a low-color consumer draws the single edge it can render, on the side
1891 // the palette left it, rather than a bevel that resolves on two sides.
1892 //
1893 // And `quantize_against` is the wrong function for this pair, though it is
1894 // the right one for a border. It answers "nearest entry that clears DISTINCT
1895 // against the background", which has no notion of direction, so both edges
1896 // are pushed onto the same contrasting entry and the bevel inverts on one
1897 // side. Plain `quantize` keeps them apart and in the right order.
1898 #[test]
1899 fn a_sixteen_color_terminal_gets_one_bevel_edge_and_not_two() {
1900 for (id, source) in embedded_themes() {
1901 let theme = parse_theme_str(id, source, false).unwrap();
1902 let t = resolve(&theme);
1903 let (Some(face), Some(light), Some(dark)) = (
1904 t.hex("surface-raised").and_then(Rgb::from_hex),
1905 t.hex("bevel-light").and_then(Rgb::from_hex),
1906 t.hex("bevel-dark").and_then(Rgb::from_hex),
1907 ) else {
1908 continue;
1909 };
1910
1911 let face_index = quantize(face, &ANSI_16);
1912 let light_survives = quantize(light, &ANSI_16) != face_index;
1913 let dark_survives = quantize(dark, &ANSI_16) != face_index;
1914 assert!(
1915 light_survives != dark_survives,
1916 "{id}: expected exactly one bevel edge to survive 16 colors, \
1917 highlight {light_survives} shadow {dark_survives}"
1918 );
1919
1920 // Direction-blind, so it collapses the pair it is asked to separate.
1921 assert_eq!(
1922 quantize_against(light, face, &ANSI_16),
1923 quantize_against(dark, face, &ANSI_16),
1924 "{id}: quantize_against is expected to be unusable for a bevel pair"
1925 );
1926 }
1927 }
1928
1929 // 256 colors is where the bevel starts working. At 16 every shipped theme
1930 // loses an edge; here all but the five whose raised surface sits at the very
1931 // top of the ramp keep both, and those five fail for the reason they fail in
1932 // truecolor rather than for a palette reason.
1933 //
1934 // Three of them cannot bevel at any depth, so they are the
1935 // `bevel_edges_are_distinct_from_their_face` set. The other two are new here:
1936 // they hold a highlight in 24-bit, but not one wide enough to survive
1937 // rounding onto the cube.
1938 #[test]
1939 fn two_hundred_fifty_six_colors_keep_both_bevel_edges() {
1940 const LOSES_AN_EDGE: &[&str] = &[
1941 "gruvbox-light",
1942 "neobrute",
1943 "oxocarbon-light",
1944 "rosepine-dawn",
1945 ];
1946
1947 let mut lost: Vec<String> = Vec::new();
1948 for (id, source) in embedded_themes() {
1949 let theme = parse_theme_str(id, source, false).unwrap();
1950 let t = resolve(&theme);
1951 let (Some(face), Some(light), Some(dark)) = (
1952 t.hex("surface-raised").and_then(Rgb::from_hex),
1953 t.hex("bevel-light").and_then(Rgb::from_hex),
1954 t.hex("bevel-dark").and_then(Rgb::from_hex),
1955 ) else {
1956 continue;
1957 };
1958
1959 // Against the fixed region, which is what a consumer should use: a
1960 // match in the low sixteen is a match against a repaintable color.
1961 let f = quantize(face, ANSI_240);
1962 let l = quantize(light, ANSI_240);
1963 let d = quantize(dark, ANSI_240);
1964 if l == f || d == f || l == d {
1965 lost.push(id.to_string());
1966 }
1967 }
1968 lost.sort();
1969
1970 assert_eq!(
1971 lost, LOSES_AN_EDGE,
1972 "themes that cannot hold a two-tone bevel on a 256-color terminal"
1973 );
1974 }
1975
1976 #[test]
1977 fn the_256_table_has_its_three_regions() {
1978 // Index is the escape-sequence index, so the low sixteen must match.
1979 assert_eq!(ANSI_256[..16], ANSI_16);
1980 // The cube's corners, at both ends and one interior level.
1981 assert_eq!(ANSI_256[16].tuple(), (0, 0, 0));
1982 assert_eq!(ANSI_256[231].tuple(), (255, 255, 255));
1983 assert_eq!(ANSI_256[16 + 36 * 2 + 6 * 3 + 4].tuple(), (135, 175, 215));
1984 // The gray ramp runs 8 to 238 and contains neither black nor white.
1985 assert_eq!(ANSI_256[232].tuple(), (8, 8, 8));
1986 assert_eq!(ANSI_256[255].tuple(), (238, 238, 238));
1987 // The fixed region is the table minus the repaintable colors.
1988 assert_eq!(ANSI_240.len(), 240);
1989 assert_eq!(ANSI_240[0], ANSI_256[ANSI_240_OFFSET]);
1990 }
1991
1992 #[test]
1993 fn resolve_overlay_is_dark_translucent_scrim() {
1994 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1995 let t = resolve(&theme);
1996 let overlay = t.hex("overlay").unwrap();
1997 assert!(
1998 overlay.starts_with("rgba("),
1999 "overlay is translucent: {overlay}"
2000 );
2001 assert!(overlay.ends_with(", 0.5)"));
2002 // The scrim tone is anchored very dark regardless of theme.
2003 let inner = overlay
2004 .trim_start_matches("rgba(")
2005 .trim_end_matches(", 0.5)");
2006 let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
2007 let scrim = Rgb {
2008 r: parts[0],
2009 g: parts[1],
2010 b: parts[2],
2011 };
2012 assert!(scrim.to_oklab().l < 0.2, "scrim must be near-black");
2013 }
2014
2015 #[test]
2016 fn resolve_drops_non_hex_base_intent() {
2017 // A base intent that isn't a hex color must never reach the resolved
2018 // token set (it would otherwise be inlined verbatim into a <style>
2019 // block). Skipped like a missing intent; valid siblings survive.
2020 let theme = parse_theme_str(
2021 "x",
2022 "[surface]\npage = \"</style><script>alert(1)</script>\"\n[content]\nprimary = \"#111111\"\n",
2023 false,
2024 )
2025 .unwrap();
2026 let t = resolve(&theme);
2027 assert!(
2028 t.hex("surface-page").is_none(),
2029 "non-hex base intent leaked"
2030 );
2031 assert_eq!(t.hex("content").unwrap(), "#111111");
2032 // The injected markup appears in no resolved value.
2033 assert!(!t.intents.values().any(|v| v.contains('<')));
2034 }
2035
2036 #[test]
2037 fn resolve_skips_derived_when_source_missing() {
2038 // No [action] => no action-derived tokens.
2039 let theme = parse_theme_str(
2040 "x",
2041 "[surface]\npage = \"#000000\"\n[line]\nborder = \"#222222\"\n",
2042 false,
2043 )
2044 .unwrap();
2045 let t = resolve(&theme);
2046 assert!(t.hex("action").is_none());
2047 assert!(t.hex("action-hover").is_none());
2048 assert!(t.hex("selection").is_none());
2049 assert_eq!(
2050 t.hex("border-strong").unwrap(),
2051 darken(Rgb::from_hex("#222222").unwrap(), 0.05).to_hex()
2052 );
2053 }
2054
2055 #[test]
2056 fn rgb_accessor_for_native_consumers() {
2057 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2058 let t = resolve(&theme);
2059 assert_eq!(t.rgb("action"), Some((0x81, 0xa1, 0xc1)));
2060 assert_eq!(t.rgb("nonexistent"), None);
2061 }
2062
2063 // ---- css emit ----
2064
2065 #[test]
2066 fn intent_css_vars_wraps_root_and_includes_tokens() {
2067 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2068 let css = intent_css_vars(&resolve(&theme));
2069 assert!(css.starts_with(":root {\n"));
2070 assert!(css.contains(" --surface-page: #2e3440;\n"));
2071 assert!(css.contains(" --danger: #bf616a;\n"));
2072 assert!(css.contains(" --action-hover: "));
2073 assert!(css.trim_end().ends_with('}'));
2074 }
2075
2076 // ---- loading / fs ----
2077
2078 #[test]
2079 fn load_and_resolve_round_trip() {
2080 let dir = tempfile::tempdir().unwrap();
2081 fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
2082 let dirs = vec![(dir.path().to_path_buf(), false)];
2083 let t = load_semantic(&dirs, "nord").unwrap();
2084 assert_eq!(t.meta.name, "Nord");
2085 assert_eq!(t.hex("action"), Some("#81a1c1"));
2086 }
2087
2088 #[test]
2089 fn load_theme_rejects_invalid_id() {
2090 assert!(load_theme(&[], "../evil").is_err());
2091 }
2092
2093 fn meta(id: &str, variant: &str) -> ThemeMeta {
2094 ThemeMeta {
2095 id: id.to_string(),
2096 name: id.to_string(),
2097 variant: variant.to_string(),
2098 is_custom: false,
2099 }
2100 }
2101
2102 fn defaults() -> ThemeDefaults {
2103 ThemeDefaults::new("flatwhite", "nord")
2104 }
2105
2106 // The three the shipped themes actually declare.
2107 #[test]
2108 fn every_shipped_variant_parses() {
2109 assert_eq!(Variant::parse("light"), Some(Variant::Light));
2110 assert_eq!(Variant::parse("dark"), Some(Variant::Dark));
2111 assert_eq!(Variant::parse("high-contrast"), Some(Variant::HighContrast));
2112 assert_eq!(Variant::parse("sepia"), None);
2113 }
2114
2115 // parse_meta already defaults a *missing* variant to dark, so an
2116 // unrecognized one reading as light would have the crate disagreeing with
2117 // itself. alloy_tui did exactly that before this existed.
2118 #[test]
2119 fn an_unrecognized_variant_reads_the_way_a_missing_one_does() {
2120 assert_eq!(Variant::from("sepia"), Variant::Dark);
2121 assert_eq!(Variant::from(""), Variant::Dark);
2122
2123 let missing: toml::Table = "[meta]\nname = \"X\"\n".parse().unwrap();
2124 assert_eq!(parse_meta("x", &missing, false).kind(), Variant::Dark);
2125 }
2126
2127 #[test]
2128 fn a_selection_round_trips_through_any_store() {
2129 for (stored, expect) in [
2130 (Some("system"), ThemeSelection::Follow),
2131 (None, ThemeSelection::Follow),
2132 (Some(""), ThemeSelection::Follow),
2133 (Some(" "), ThemeSelection::Follow),
2134 (Some("nord"), ThemeSelection::Fixed("nord".into())),
2135 ] {
2136 let parsed = ThemeSelection::parse(stored);
2137 assert_eq!(parsed, expect, "{stored:?}");
2138 assert_eq!(
2139 ThemeSelection::parse(Some(parsed.as_str())),
2140 expect,
2141 "what is written reads back as what was meant",
2142 );
2143 }
2144 }
2145
2146 // Nothing saved is follow-the-system, which is what Balanced Breakfast
2147 // expressed as an absent value and GoingsOn as a sentinel. Both are now the
2148 // same thing.
2149 #[test]
2150 fn nothing_chosen_yet_is_follow() {
2151 assert_eq!(ThemeSelection::default(), ThemeSelection::Follow);
2152 }
2153
2154 #[test]
2155 fn a_fixed_selection_wins_when_its_theme_is_installed() {
2156 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
2157 let fixed = ThemeSelection::Fixed("nord".into());
2158 assert_eq!(
2159 fixed.resolve(Variant::Light, &defaults(), &available),
2160 "nord",
2161 "a chosen theme is not overridden by the ambient mode",
2162 );
2163 }
2164
2165 // Themes are deletable in three of the four apps. Handing back an id that
2166 // will fail to load only moves the error somewhere less helpful.
2167 #[test]
2168 fn a_fixed_selection_whose_theme_is_gone_falls_back() {
2169 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
2170 let fixed = ThemeSelection::Fixed("deleted".into());
2171 assert_eq!(
2172 fixed.resolve(Variant::Light, &defaults(), &available),
2173 "flatwhite",
2174 );
2175 }
2176
2177 #[test]
2178 fn follow_picks_the_apps_default_for_the_ambient_mode() {
2179 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
2180 let follow = ThemeSelection::Follow;
2181 assert_eq!(
2182 follow.resolve(Variant::Dark, &defaults(), &available),
2183 "nord",
2184 );
2185 assert_eq!(
2186 follow.resolve(Variant::Light, &defaults(), &available),
2187 "flatwhite",
2188 );
2189 }
2190
2191 // The behaviour Balanced Breakfast could not have: following the system
2192 // into a theme the user installed, when the app's own default is absent.
2193 #[test]
2194 fn follow_uses_any_installed_theme_of_the_right_variant() {
2195 let available = [meta("solarized-light", "light"), meta("mine", "dark")];
2196 assert_eq!(
2197 ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &available),
2198 "mine",
2199 "the app's `nord` is not installed, but a dark theme is",
2200 );
2201 }
2202
2203 // Always returns something: an app with no theme directory gets the id it
2204 // ships with, and the load error it would have had anyway.
2205 #[test]
2206 fn an_empty_catalog_still_names_the_apps_default() {
2207 assert_eq!(
2208 ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &[]),
2209 "nord",
2210 );
2211 }
2212
2213 #[test]
2214 fn high_contrast_falls_back_to_dark_unless_named() {
2215 let plain = defaults();
2216 assert_eq!(plain.for_variant(Variant::HighContrast), "nord");
2217
2218 let named = defaults().high_contrast("sharp");
2219 assert_eq!(named.for_variant(Variant::HighContrast), "sharp");
2220 }
2221
2222 // The bug this builder exists to prevent: the Alloy console pushed the
2223 // user's directory first under a comment reading "highest precedence
2224 // first", when both consumers of this vector resolve last-wins. A custom
2225 // theme lost to the packaged one of the same id.
2226 #[test]
2227 fn the_users_own_themes_outrank_everything() {
2228 let root = tempfile::tempdir().unwrap();
2229 let make = |name: &str| {
2230 let dir = root.path().join(name);
2231 std::fs::create_dir_all(&dir).unwrap();
2232 dir
2233 };
2234 let (bundled, system, custom) = (make("bundled"), make("system"), make("custom"));
2235
2236 let dirs = ThemeDirs::new()
2237 .custom(Some(custom.clone()))
2238 .bundled(Some(bundled.clone()))
2239 .system(Some(system.clone()))
2240 .build();
2241
2242 assert_eq!(
2243 dirs,
2244 vec![(bundled, false), (system, false), (custom.clone(), true)],
2245 "lowest precedence first, whatever order the tiers were added in",
2246 );
2247 assert!(dirs.last().unwrap().1, "only the user's tier is custom");
2248
2249 // And the ordering means what the consumers think it means.
2250 for dir in dirs.iter().map(|(dir, _)| dir) {
2251 std::fs::write(dir.join("shared.toml"), "[meta]\nname = \"x\"\n").unwrap();
2252 }
2253 assert_eq!(
2254 find_theme_path(&dirs, "shared").unwrap().0,
2255 custom.join("shared.toml"),
2256 "the user's copy is the one that loads",
2257 );
2258 }
2259
2260 #[test]
2261 fn a_directory_that_does_not_exist_is_dropped() {
2262 let root = tempfile::tempdir().unwrap();
2263 let real = root.path().join("real");
2264 std::fs::create_dir_all(&real).unwrap();
2265
2266 let dirs = ThemeDirs::new()
2267 .bundled(Some(root.path().join("nope")))
2268 .system(None)
2269 .custom(Some(real.clone()))
2270 .build();
2271
2272 assert_eq!(dirs, vec![(real, true)]);
2273 }
2274
2275 // A Tauri app has two bundled tiers: the resource dir in production and the
2276 // tree build.rs materialized for a dev run with no resource dir.
2277 #[test]
2278 fn more_than_one_bundled_tier_is_allowed() {
2279 let root = tempfile::tempdir().unwrap();
2280 let (first, second) = (root.path().join("a"), root.path().join("b"));
2281 std::fs::create_dir_all(&first).unwrap();
2282 std::fs::create_dir_all(&second).unwrap();
2283
2284 let dirs = ThemeDirs::new()
2285 .bundled(Some(first.clone()))
2286 .bundled(Some(second.clone()))
2287 .build();
2288 assert_eq!(dirs, vec![(first, false), (second, false)]);
2289 }
2290
2291 #[test]
2292 fn list_themes_from_dirs_finds_toml_files() {
2293 let dir = tempfile::tempdir().unwrap();
2294 fs::write(dir.path().join("t.toml"), "[meta]\nname = \"T\"\n").unwrap();
2295 fs::write(dir.path().join("x.txt"), "ignored").unwrap();
2296 let dirs = vec![(dir.path().to_path_buf(), false)];
2297 let themes = list_themes_from_dirs(&dirs);
2298 assert_eq!(themes.len(), 1);
2299 assert_eq!(themes[0].id, "t");
2300 }
2301
2302 #[test]
2303 fn find_theme_path_reverse_priority() {
2304 let d1 = tempfile::tempdir().unwrap();
2305 let d2 = tempfile::tempdir().unwrap();
2306 fs::write(d1.path().join("s.toml"), "[meta]\n").unwrap();
2307 fs::write(d2.path().join("s.toml"), "[meta]\n").unwrap();
2308 let dirs = vec![
2309 (d1.path().to_path_buf(), false),
2310 (d2.path().to_path_buf(), true),
2311 ];
2312 let (path, is_custom) = find_theme_path(&dirs, "s").unwrap();
2313 assert!(is_custom);
2314 assert_eq!(path, d2.path().join("s.toml"));
2315 }
2316
2317 #[test]
2318 fn import_theme_valid_and_rejects_empty() {
2319 let src_dir = tempfile::tempdir().unwrap();
2320 let custom_dir = tempfile::tempdir().unwrap();
2321
2322 let good = src_dir.path().join("my-theme.toml");
2323 fs::write(&good, "[surface]\npage = \"#1a1b26\"\n").unwrap();
2324 let meta = import_theme(&good, custom_dir.path()).unwrap();
2325 assert_eq!(meta.id, "my-theme");
2326 assert!(custom_dir.path().join("my-theme.toml").exists());
2327
2328 let empty = src_dir.path().join("empty.toml");
2329 fs::write(&empty, "[meta]\nname = \"E\"\n").unwrap();
2330 assert!(import_theme(&empty, custom_dir.path()).is_err());
2331 }
2332
2333 #[test]
2334 fn import_theme_rejects_invalid_toml() {
2335 let src_dir = tempfile::tempdir().unwrap();
2336 let custom_dir = tempfile::tempdir().unwrap();
2337 let src = src_dir.path().join("bad.toml");
2338 fs::write(&src, "this is not [valid toml [[[").unwrap();
2339 assert!(import_theme(&src, custom_dir.path()).is_err());
2340 }
2341
2342 #[test]
2343 fn delete_theme_removes_and_guards() {
2344 let custom = tempfile::tempdir().unwrap();
2345 let path = custom.path().join("doomed.toml");
2346 fs::write(&path, "[surface]\npage = \"#000\"\n").unwrap();
2347 delete_theme(custom.path(), "doomed").unwrap();
2348 assert!(!path.exists());
2349 assert!(delete_theme(custom.path(), "../etc/passwd").is_err());
2350 assert!(delete_theme(custom.path(), "ghost").is_err());
2351 }
2352
2353 #[test]
2354 fn export_theme_copies_file() {
2355 let src_dir = tempfile::tempdir().unwrap();
2356 let dest_dir = tempfile::tempdir().unwrap();
2357 let content = "[meta]\nname = \"E\"\n[surface]\npage = \"#ffffff\"\n";
2358 fs::write(src_dir.path().join("e.toml"), content).unwrap();
2359 let dirs = vec![(src_dir.path().to_path_buf(), false)];
2360 let dest = dest_dir.path().join("out.toml");
2361 export_theme(&dirs, "e", &dest).unwrap();
2362 assert_eq!(fs::read_to_string(&dest).unwrap(), content);
2363 assert!(export_theme(&dirs, "missing", &dest).is_err());
2364 }
2365
2366 #[test]
2367 fn load_theme_preview_returns_role_swatches() {
2368 let dir = tempfile::tempdir().unwrap();
2369 fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
2370 let dirs = vec![(dir.path().to_path_buf(), false)];
2371 let p = load_theme_preview(&dirs, "nord").unwrap();
2372 assert_eq!(p.background.as_deref(), Some("#2e3440")); // surface.page
2373 assert_eq!(p.foreground.as_deref(), Some("#d8dee9")); // content.primary
2374 assert_eq!(p.accent.as_deref(), Some("#81a1c1")); // action.primary
2375 assert_eq!(p.border.as_deref(), Some("#4c566a")); // line.border
2376 }
2377
2378 #[test]
2379 fn bundled_themes_dir_resolves_to_shipped_themes() {
2380 // The crate ships its themes, so this must resolve in-tree and the
2381 // Akari defaults the console falls back to must be present.
2382 let dir = bundled_themes_dir().expect("makeover ships a themes/ directory");
2383 assert!(dir.join("akari-dawn.toml").is_file());
2384 assert!(dir.join("akari-night.toml").is_file());
2385 }
2386
2387 #[test]
2388 fn every_theme_is_accounted_for_in_third_party_notices() {
2389 // Attribution is a redistribution obligation, not a nicety: adding a
2390 // theme without a notice entry silently ships someone's work
2391 // uncredited. Fail here instead.
2392 let notices = std::fs::read_to_string(
2393 Path::new(env!("CARGO_MANIFEST_DIR")).join("THIRD-PARTY-NOTICES.md"),
2394 )
2395 .expect("THIRD-PARTY-NOTICES.md must exist");
2396 let missing: Vec<&str> = embedded_themes()
2397 .map(|(id, _)| id)
2398 .filter(|id| !notices.contains(*id))
2399 .collect();
2400 assert!(
2401 missing.is_empty(),
2402 "themes missing from THIRD-PARTY-NOTICES.md: {missing:?}"
2403 );
2404 }
2405
2406 #[test]
2407 fn adapted_themes_carry_inline_attribution() {
2408 // Each adapted file must name its upstream in-file, so the credit
2409 // survives someone copying a single .toml out of the crate.
2410 const ORIGINALS: [&str; 5] = [
2411 "makenotwork",
2412 "goingson",
2413 "audiofiles",
2414 "high-contrast",
2415 "neobrute",
2416 ];
2417 for (id, source) in embedded_themes() {
2418 if ORIGINALS.contains(&id) {
2419 continue;
2420 }
2421 assert!(
2422 source.contains("adapted from"),
2423 "adapted theme `{id}` is missing its inline attribution header"
2424 );
2425 }
2426 }
2427
2428 #[test]
2429 fn embedded_themes_match_the_directory() {
2430 // The embedded copy and themes/ are two views of one source. If they
2431 // ever disagree, path-based and path-free consumers render different
2432 // theme sets, which is exactly the drift shipping the data was meant
2433 // to prevent.
2434 let dir = bundled_themes_dir().unwrap();
2435 let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
2436 .unwrap()
2437 .filter_map(|e| {
2438 let path = e.ok()?.path();
2439 if path.extension()? != "toml" {
2440 return None;
2441 }
2442 Some(path.file_stem()?.to_str()?.to_string())
2443 })
2444 .collect();
2445 let mut embedded: Vec<String> = embedded_themes().map(|(id, _)| id.to_string()).collect();
2446 on_disk.sort();
2447 embedded.sort();
2448 assert_eq!(embedded, on_disk, "embedded theme set drifted from themes/");
2449 }
2450
2451 #[test]
2452 fn every_embedded_theme_parses() {
2453 // Guards the path-free consumers (MNW server, the Tauri build steps)
2454 // the same way every_shipped_theme_loads guards the path-based ones.
2455 let mut count = 0;
2456 for (id, source) in embedded_themes() {
2457 parse_theme_str(id, source, false)
2458 .unwrap_or_else(|e| panic!("embedded theme `{id}` failed to parse: {e}"));
2459 count += 1;
2460 }
2461 assert!(count >= 30, "expected the full theme set, got {count}");
2462 }
2463
2464 #[test]
2465 fn every_shipped_theme_loads() {
2466 // Guards the data, not just the loader: a malformed or truncated
2467 // .toml in themes/ is a shipping bug, and it should fail here rather
2468 // than at a user's first launch.
2469 let dir = bundled_themes_dir().unwrap();
2470 let dirs = vec![(dir.clone(), false)];
2471 let themes = list_themes_from_dirs(&dirs);
2472 assert!(
2473 themes.len() >= 30,
2474 "expected the full theme set, got {}",
2475 themes.len()
2476 );
2477 for meta in &themes {
2478 load_theme(&dirs, &meta.id)
2479 .unwrap_or_else(|e| panic!("shipped theme `{}` failed to load: {e}", meta.id));
2480 }
2481 }
2482 }
2483