Skip to main content

pitchfork_cli/tui/
theme.rs

1//! Colors of the TUI.
2//!
3//! The UI never names a color directly: it asks for a role (`theme().red`,
4//! `theme().selection`, …). The default `auto` theme only uses the terminal's
5//! own palette (ANSI names, `reset` and text modifiers), so it follows any
6//! terminal theme, light or dark. Other themes are built in (`catppuccin_*`)
7//! or declared by the user under `[themes.<name>]`.
8
9use indexmap::IndexMap;
10use ratatui::style::{Color, Modifier, Style};
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13use std::str::FromStr;
14use std::sync::OnceLock;
15
16pub const AUTO: &str = "auto";
17
18/// Resolved theme: every color the TUI draws with.
19#[derive(Debug, Clone, PartialEq)]
20pub struct Theme {
21    /// Default text.
22    pub fg: Color,
23    /// Secondary text (placeholders, "-" cells).
24    pub muted: Color,
25    /// Borders and empty parts of bars.
26    pub faint: Color,
27    pub red: Color,
28    pub orange: Color,
29    pub green: Color,
30    pub yellow: Color,
31    /// Daemons that are only declared in a config (not started yet).
32    pub cyan: Color,
33    /// Completed oneshot tasks.
34    pub dim_green: Color,
35    /// Whole-screen background. Unset in `auto`: the terminal's own is kept.
36    pub background: Style,
37    /// Row under the cursor.
38    pub selection: Style,
39    /// Row ticked with `Space`.
40    pub marked: Style,
41    /// Current search match.
42    pub match_current: Style,
43    /// Other search matches.
44    pub match_other: Style,
45    /// Background of overlays (help, details, editor, …).
46    pub overlay: Style,
47    /// Background of the confirmation overlay.
48    pub danger: Style,
49}
50
51impl Theme {
52    /// The default theme: no RGB, no whole-screen background, so every color
53    /// is the terminal's own and follows its light or dark theme.
54    ///
55    /// The cursor row is bold and underlined rather than colored: no ANSI
56    /// color is guaranteed to contrast with the text under every terminal theme.
57    pub fn auto() -> Self {
58        Self {
59            fg: Color::Reset,
60            muted: Color::DarkGray,
61            faint: Color::DarkGray,
62            red: Color::Red,
63            orange: Color::LightRed,
64            green: Color::Green,
65            yellow: Color::Yellow,
66            cyan: Color::Cyan,
67            dim_green: Color::Green,
68            // No background: ANSI colors are remapped by the terminal theme, so
69            // no one of them is guaranteed to contrast with the text. Reverse
70            // video is out too, it would fill colored empty cells (error column).
71            background: Style::new(),
72            selection: Style::new().add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
73            marked: Style::new().add_modifier(Modifier::ITALIC),
74            match_current: Style::new().add_modifier(Modifier::REVERSED),
75            match_other: Style::new().add_modifier(Modifier::UNDERLINED),
76            overlay: Style::new(),
77            danger: Style::new(),
78        }
79    }
80
81    /// Theme of one Catppuccin flavor. It paints its own background and text
82    /// color, so it reads the same whatever the terminal's background is.
83    fn catppuccin(p: &Palette) -> Self {
84        let bg = |c: u32| Style::new().bg(hex(c));
85        let panel = Style::new().fg(hex(p.text)).bg(hex(p.base));
86        Self {
87            fg: hex(p.text),
88            muted: hex(p.subtext),
89            faint: hex(p.surface),
90            red: hex(p.red),
91            orange: hex(p.peach),
92            green: hex(p.green),
93            yellow: hex(p.yellow),
94            cyan: hex(p.sky),
95            dim_green: hex(p.teal),
96            background: panel,
97            selection: bg(p.surface_alt),
98            marked: bg(p.surface),
99            match_current: bg(p.yellow_dim),
100            match_other: bg(p.surface),
101            overlay: panel,
102            danger: panel,
103        }
104    }
105
106    /// Replaces the roles `def` sets, keeping the others.
107    ///
108    /// Fails on a color that does not parse, naming `name` and the key. The
109    /// full-area styles (`background`, `overlay`, `danger`) always end up with
110    /// the final `fg`. A new `bg` also colors the overlays that were following
111    /// the screen background (same `bg` in `self`), unless `def` sets them;
112    /// overlays that `self` colored differently keep their own color.
113    fn apply(mut self, name: &str, def: &ThemeDef) -> miette::Result<Self> {
114        let color = |key: &str, v: &Option<String>| -> miette::Result<Option<Color>> {
115            v.as_deref()
116                .map(|s| {
117                    Color::from_str(s).map_err(|_| {
118                        miette::miette!(
119                            "theme '{name}': invalid color '{s}' for '{key}' \
120                             (use #rrggbb, an ANSI name such as bright_black, or reset)"
121                        )
122                    })
123                })
124                .transpose()
125        };
126        let overlay_follows_bg = self.overlay.bg == self.background.bg;
127        let danger_follows_bg = self.danger.bg == self.background.bg;
128        macro_rules! fg {
129            ($($f:ident),*) => {$(
130                if let Some(c) = color(stringify!($f), &def.$f)? { self.$f = c; }
131            )*};
132        }
133        macro_rules! bg {
134            ($($f:ident => $key:ident),*) => {$(
135                if let Some(c) = color(stringify!($key), &def.$key)? {
136                    self.$f = Style::new().bg(c);
137                }
138            )*};
139        }
140        fg!(
141            fg, muted, faint, red, orange, green, yellow, cyan, dim_green
142        );
143        bg!(
144            background => bg,
145            selection => selection_bg,
146            marked => marked_bg,
147            match_current => match_current_bg,
148            match_other => match_other_bg,
149            overlay => overlay_bg,
150            danger => danger_bg
151        );
152        // Cells are merged onto the buffer and `Clear` wipes it, so every
153        // full-area style must carry the foreground itself.
154        if def.bg.is_some() {
155            if overlay_follows_bg && def.overlay_bg.is_none() {
156                self.overlay = self.background;
157            }
158            if danger_follows_bg && def.danger_bg.is_none() {
159                self.danger = self.background;
160            }
161        }
162        for panel in [&mut self.background, &mut self.overlay, &mut self.danger] {
163            *panel = panel.fg(self.fg);
164        }
165        Ok(self)
166    }
167}
168
169/// A theme declared in `[themes.<name>]`. Only the roles set here differ from
170/// `base`; colors are `#rrggbb`, ANSI names (`red`, `bright_black`, …),
171/// `reset` (the terminal's own color) or a 0-255 palette index.
172#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
173#[serde(deny_unknown_fields)]
174pub struct ThemeDef {
175    /// Theme to start from: `auto`, a built-in theme or another custom theme.
176    /// Defaults to `auto`.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub base: Option<String>,
179    /// Default text color.
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub fg: Option<String>,
182    /// Secondary text color.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub muted: Option<String>,
185    /// Borders and empty parts of bars.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub faint: Option<String>,
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub red: Option<String>,
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub orange: Option<String>,
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub green: Option<String>,
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub yellow: Option<String>,
196    /// Daemons declared in a config but not started yet.
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub cyan: Option<String>,
199    /// Completed oneshot tasks.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub dim_green: Option<String>,
202    /// Background of the whole screen.
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub bg: Option<String>,
205    /// Background of the row under the cursor.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub selection_bg: Option<String>,
208    /// Background of rows ticked with `Space`.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub marked_bg: Option<String>,
211    /// Background of the current search match.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub match_current_bg: Option<String>,
214    /// Background of the other search matches.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub match_other_bg: Option<String>,
217    /// Background of overlays.
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub overlay_bg: Option<String>,
220    /// Background of the confirmation overlay.
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub danger_bg: Option<String>,
223}
224
225/// Resolves `name` against the built-in themes and the user's `themes`.
226///
227/// A custom theme shadows a built-in one of the same name, and a custom
228/// `auto` without `base` customizes the built-in `auto`. Fails, listing the
229/// available names, if `name` is unknown; also fails on a `base` cycle or an
230/// invalid color.
231pub fn resolve(name: &str, custom: &IndexMap<String, ThemeDef>) -> miette::Result<Theme> {
232    resolve_inner(name, custom, &mut Vec::new())
233}
234
235/// `seen` is the chain of themes being resolved, to detect `base` cycles.
236fn resolve_inner<'a>(
237    name: &'a str,
238    custom: &'a IndexMap<String, ThemeDef>,
239    seen: &mut Vec<&'a str>,
240) -> miette::Result<Theme> {
241    if seen.contains(&name) {
242        miette::bail!("theme '{name}' is its own base ({})", seen.join(" -> "));
243    }
244    seen.push(name);
245    // A custom theme shadows a built-in one of the same name.
246    if let Some(def) = custom.get(name) {
247        let base = match def.base.as_deref() {
248            Some(base) => resolve_inner(base, custom, seen)?,
249            // `[themes.auto]` customizes the built-in `auto`, not itself.
250            None if name == AUTO => Theme::auto(),
251            None => resolve_inner(AUTO, custom, seen)?,
252        };
253        return base.apply(name, def);
254    }
255    if name == AUTO {
256        return Ok(Theme::auto());
257    }
258    if let Some(p) = PALETTES.iter().find(|p| p.name == name) {
259        return Ok(Theme::catppuccin(p));
260    }
261    let builtin = PALETTES.iter().map(|p| p.name).chain([AUTO]);
262    let known: Vec<_> = builtin.chain(custom.keys().map(String::as_str)).collect();
263    miette::bail!(
264        "unknown TUI theme '{name}' (available: {})",
265        known.join(", ")
266    );
267}
268
269/// Name of the theme to use: `theme` unless it is `auto` and a
270/// `light`/`dark` variant is configured for the terminal's background.
271///
272/// `is_dark` is only called when it matters, as it queries the terminal.
273pub fn pick_name<'a>(
274    theme: &'a str,
275    light: &'a str,
276    dark: &'a str,
277    is_dark: impl FnOnce() -> Option<bool>,
278) -> &'a str {
279    if theme != AUTO || (light.is_empty() && dark.is_empty()) {
280        return theme;
281    }
282    let variant = match is_dark() {
283        Some(true) => dark,
284        Some(false) => light,
285        None => "",
286    };
287    if variant.is_empty() { theme } else { variant }
288}
289
290/// Whether the terminal has a dark background, `None` if it does not say.
291///
292/// Asks the terminal (OSC 11) and waits for its answer, up to one second when
293/// it stays silent, so only call it when the answer is needed. It handles the
294/// terminal mode itself: call it before entering raw mode.
295pub fn terminal_is_dark() -> Option<bool> {
296    use terminal_colorsaurus::{QueryOptions, ThemeMode, theme_mode};
297    match theme_mode(QueryOptions::default()) {
298        Ok(ThemeMode::Dark) => Some(true),
299        Ok(ThemeMode::Light) => Some(false),
300        Err(_) => None,
301    }
302}
303
304static THEME: OnceLock<Theme> = OnceLock::new();
305
306/// Installs the theme for this process. Later calls are ignored.
307///
308/// Call it before the first frame is drawn: [`theme`] falls back to `auto` and
309/// keeps it if it runs first.
310pub fn init(theme: Theme) {
311    let _ = THEME.set(theme);
312}
313
314/// The active theme; `auto` until [`init`] is called.
315pub fn theme() -> &'static Theme {
316    THEME.get_or_init(Theme::auto)
317}
318
319/// `0xRRGGBB` to a color.
320fn hex(c: u32) -> Color {
321    Color::Rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)
322}
323
324struct Palette {
325    name: &'static str,
326    text: u32,
327    /// Subtext0: secondary text, which must stay readable on `surface_alt`.
328    subtext: u32,
329    /// Surface1: borders, marked rows, secondary matches.
330    surface: u32,
331    /// Surface0: cursor row.
332    surface_alt: u32,
333    base: u32,
334    red: u32,
335    peach: u32,
336    green: u32,
337    yellow: u32,
338    sky: u32,
339    teal: u32,
340    /// Current search match: yellow blended into the background.
341    yellow_dim: u32,
342}
343
344const PALETTES: &[Palette] = &[
345    Palette {
346        name: "catppuccin_latte",
347        text: 0x4c4f69,
348        subtext: 0x6c6f85,
349        surface: 0xbcc0cc,
350        surface_alt: 0xccd0da,
351        base: 0xeff1f5,
352        red: 0xd20f39,
353        peach: 0xfe640b,
354        green: 0x40a02b,
355        yellow: 0xdf8e1d,
356        sky: 0x04a5e5,
357        teal: 0x179299,
358        yellow_dim: 0xf2d8a6,
359    },
360    Palette {
361        name: "catppuccin_frappe",
362        text: 0xc6d0f5,
363        subtext: 0xa5adce,
364        surface: 0x51576d,
365        surface_alt: 0x414559,
366        base: 0x303446,
367        red: 0xe78284,
368        peach: 0xef9f76,
369        green: 0xa6d189,
370        yellow: 0xe5c890,
371        sky: 0x99d1db,
372        teal: 0x81c8be,
373        yellow_dim: 0x6b624a,
374    },
375    Palette {
376        name: "catppuccin_macchiato",
377        text: 0xcad3f5,
378        subtext: 0xa5adcb,
379        surface: 0x494d64,
380        surface_alt: 0x363a4f,
381        base: 0x24273a,
382        red: 0xed8796,
383        peach: 0xf5a97f,
384        green: 0xa6da95,
385        yellow: 0xeed49f,
386        sky: 0x91d7e3,
387        teal: 0x8bd5ca,
388        yellow_dim: 0x645a41,
389    },
390    Palette {
391        name: "catppuccin_mocha",
392        text: 0xcdd6f4,
393        subtext: 0xa6adc8,
394        surface: 0x45475a,
395        surface_alt: 0x313244,
396        base: 0x1e1e2e,
397        red: 0xf38ba8,
398        peach: 0xfab387,
399        green: 0xa6e3a1,
400        yellow: 0xf9e2af,
401        sky: 0x89dceb,
402        teal: 0x94e2d5,
403        yellow_dim: 0x5f573f,
404    },
405];
406
407#[cfg(test)]
408mod tests {
409    use super::*;
410
411    fn custom(toml: &str) -> IndexMap<String, ThemeDef> {
412        toml::from_str(toml).unwrap()
413    }
414
415    #[test]
416    fn auto_only_uses_the_terminal_palette() {
417        let t = resolve(AUTO, &IndexMap::new()).unwrap();
418        assert_eq!(t.fg, Color::Reset);
419        assert_eq!(t.selection.bg, None);
420        assert!(t.selection.add_modifier.contains(Modifier::UNDERLINED));
421    }
422
423    #[test]
424    fn builtin_catppuccin_is_available() {
425        let t = resolve("catppuccin_mocha", &IndexMap::new()).unwrap();
426        assert_eq!(t.fg, Color::Rgb(0xcd, 0xd6, 0xf4));
427        assert_eq!(t.selection.bg, Some(Color::Rgb(0x31, 0x32, 0x44)));
428        assert_eq!(t.background.bg, Some(Color::Rgb(0x1e, 0x1e, 0x2e)));
429        assert_eq!(Theme::auto().background.bg, None);
430    }
431
432    #[test]
433    fn custom_theme_overrides_only_what_it_sets() {
434        let c = custom(
435            r##"
436            [mine]
437            base = "catppuccin_latte"
438            red = "bright_red"
439            selection_bg = "#ff0000"
440            "##,
441        );
442        let t = resolve("mine", &c).unwrap();
443        assert_eq!(t.red, Color::LightRed);
444        assert_eq!(t.selection.bg, Some(Color::Rgb(255, 0, 0)));
445        assert_eq!(t.green, Color::Rgb(0x40, 0xa0, 0x2b));
446    }
447
448    #[test]
449    fn custom_theme_without_base_starts_from_auto() {
450        let c = custom(r#"mine = { yellow = "reset" }"#);
451        let t = resolve("mine", &c).unwrap();
452        assert_eq!(t.yellow, Color::Reset);
453        assert_eq!(t.red, Color::Red);
454    }
455
456    #[test]
457    fn custom_themes_can_chain_bases() {
458        let c = custom(
459            r#"
460            a = { red = "blue" }
461            b = { base = "a", green = "magenta" }
462            "#,
463        );
464        let t = resolve("b", &c).unwrap();
465        assert_eq!((t.red, t.green), (Color::Blue, Color::Magenta));
466    }
467
468    #[test]
469    fn a_custom_auto_without_base_customizes_the_builtin() {
470        let c = custom(r#"auto = { red = "magenta" }"#);
471        let t = resolve(AUTO, &c).unwrap();
472        assert_eq!((t.red, t.green), (Color::Magenta, Color::Green));
473    }
474
475    #[test]
476    fn full_area_styles_carry_the_foreground() {
477        let t = resolve("catppuccin_latte", &IndexMap::new()).unwrap();
478        for s in [t.background, t.overlay, t.danger] {
479            assert_eq!(s.fg, Some(t.fg));
480        }
481        let c = custom(r##"mine = { fg = "#111111", bg = "#eeeeee" }"##);
482        let t = resolve("mine", &c).unwrap();
483        for s in [t.background, t.overlay, t.danger] {
484            assert_eq!((s.fg, s.bg), (Some(t.fg), t.background.bg));
485        }
486    }
487
488    #[test]
489    fn a_new_bg_keeps_the_dialog_colors_the_base_chose_apart_from_it() {
490        let c = custom(
491            r##"
492            a = { bg = "#101010", overlay_bg = "#202020" }
493            b = { base = "a", bg = "#303030" }
494            "##,
495        );
496        let t = resolve("b", &c).unwrap();
497        assert_eq!(t.background.bg, Some(Color::Rgb(0x30, 0x30, 0x30)));
498        assert_eq!(t.overlay.bg, Some(Color::Rgb(0x20, 0x20, 0x20)));
499        // The confirmation overlay was following the screen, so it still does.
500        assert_eq!(t.danger.bg, t.background.bg);
501    }
502
503    #[test]
504    fn base_cycles_are_rejected() {
505        let c = custom(
506            r#"
507            a = { base = "b" }
508            b = { base = "a" }
509            "#,
510        );
511        let err = resolve("a", &c).unwrap_err().to_string();
512        assert!(err.contains("own base"), "{err}");
513    }
514
515    #[test]
516    fn unknown_theme_lists_the_available_ones() {
517        let c = custom(r#"mine = {}"#);
518        let err = resolve("nope", &c).unwrap_err().to_string();
519        assert!(
520            err.contains("catppuccin_mocha") && err.contains("mine"),
521            "{err}"
522        );
523    }
524
525    #[test]
526    fn invalid_color_names_the_theme_and_key() {
527        let c = custom(r#"mine = { red = "blurple" }"#);
528        let err = resolve("mine", &c).unwrap_err().to_string();
529        assert!(err.contains("'mine'") && err.contains("'red'"), "{err}");
530    }
531
532    #[test]
533    fn pick_name_follows_the_terminal_only_for_auto() {
534        let pick = |theme, light, dark, is_dark| pick_name(theme, light, dark, || is_dark);
535        assert_eq!(pick("auto", "l", "d", Some(false)), "l");
536        assert_eq!(pick("auto", "l", "d", Some(true)), "d");
537        assert_eq!(pick("auto", "l", "", Some(true)), "auto");
538        assert_eq!(pick("auto", "l", "d", None), "auto");
539        assert_eq!(pick("mine", "l", "d", Some(true)), "mine");
540    }
541
542    #[test]
543    fn pick_name_does_not_query_the_terminal_when_unneeded() {
544        let never = || -> Option<bool> { panic!("terminal queried") };
545        assert_eq!(pick_name("auto", "", "", never), "auto");
546        assert_eq!(pick_name("mine", "l", "d", never), "mine");
547    }
548
549    #[test]
550    fn unknown_keys_are_rejected() {
551        assert!(toml::from_str::<IndexMap<String, ThemeDef>>("a = { blue = \"red\" }").is_err());
552    }
553}