Skip to main content

arb/
theme.rs

1//! Color themes — the 31 storageshower palettes shared by the sibling `iftoprs`
2//! and `htoprs` HUD apps, ported verbatim, plus a user `custom` palette.
3//!
4//! A theme is a **6-color palette** of 256-color terminal indices
5//! `(c1..c6) = (primary, accent, alt, mid, dim, bg)`, exactly as the sibling apps
6//! store it. A [`Palette`] exposes those slots by role so arb's widgets recolor
7//! as one system when the active `theme` changes; a widget's `-color <slot>`
8//! (accent/primary/alt/mid/dim/bg) resolves through it. With no `theme` directive
9//! the palette is `None` and color resolution stays exactly as before (cyan
10//! default + the fixed named colors) — themes are purely additive.
11
12use ratatui::style::Color;
13
14/// A resolved 6-color theme palette (256-color terminal indices). `Copy` — 6
15/// bytes, passed by value into the render functions.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct Palette {
18    /// `(c1, c2, c3, c4, c5, c6)` = (primary, accent, alt, mid, dim, bg).
19    pub c: [u8; 6],
20}
21
22impl Palette {
23    /// `c2` — the bright accent (default widget border/fill, focused controls).
24    pub fn accent(&self) -> Color {
25        Color::Indexed(self.c[1])
26    }
27    /// `c1` — the primary label color.
28    pub fn primary(&self) -> Color {
29        Color::Indexed(self.c[0])
30    }
31    /// `c3` — a distinct alternate hue.
32    pub fn alt(&self) -> Color {
33        Color::Indexed(self.c[2])
34    }
35    /// `c4` — a mid tone.
36    pub fn mid(&self) -> Color {
37        Color::Indexed(self.c[3])
38    }
39    /// `c5` — a dim tone.
40    pub fn dim(&self) -> Color {
41        Color::Indexed(self.c[4])
42    }
43    /// `c6` — the darkest (backgrounds).
44    pub fn bg(&self) -> Color {
45        Color::Indexed(self.c[5])
46    }
47    /// Resolve a `-color <slot>` name to a palette color, if it names a slot.
48    pub fn slot(&self, name: &str) -> Option<Color> {
49        Some(match name {
50            "accent" => self.accent(),
51            "primary" => self.primary(),
52            "alt" => self.alt(),
53            "mid" => self.mid(),
54            "dim" => self.dim(),
55            "bg" | "dark" | "background" => self.bg(),
56            _ => return None,
57        })
58    }
59}
60
61/// The 31 built-in themes, in display order — `(kebab-name, [c1..c6])`. Palettes
62/// are the storageshower values ported verbatim from `iftoprs`/`htoprs`.
63pub const THEMES: &[(&str, [u8; 6])] = &[
64    ("neon-sprawl", [27, 48, 135, 141, 63, 99]),
65    ("acid-rain", [28, 46, 34, 40, 22, 35]),
66    ("ice-breaker", [19, 39, 25, 33, 21, 32]),
67    ("synth-wave", [91, 177, 128, 134, 93, 97]),
68    ("rust-belt", [172, 214, 178, 220, 166, 130]),
69    ("ghost-wire", [37, 50, 44, 87, 30, 23]),
70    ("red-sector", [160, 203, 196, 210, 124, 88]),
71    ("sakura-den", [175, 218, 182, 225, 169, 132]),
72    ("data-stream", [22, 46, 28, 119, 34, 22]),
73    ("solar-flare", [202, 220, 196, 213, 160, 125]),
74    ("neon-noir", [201, 231, 93, 219, 57, 53]),
75    ("chrome-heart", [250, 255, 246, 253, 243, 239]),
76    ("blade-runner", [208, 37, 166, 73, 130, 23]),
77    ("void-walker", [55, 99, 54, 141, 92, 17]),
78    ("toxic-waste", [118, 190, 154, 226, 82, 58]),
79    ("cyber-frost", [159, 195, 153, 189, 111, 67]),
80    ("plasma-core", [199, 213, 163, 207, 126, 89]),
81    ("steel-nerve", [68, 110, 60, 146, 24, 236]),
82    ("dark-signal", [30, 43, 23, 79, 29, 16]),
83    ("glitch-pop", [201, 51, 226, 47, 196, 21]),
84    ("holo-shift", [123, 219, 159, 183, 87, 133]),
85    ("night-city", [214, 227, 209, 223, 172, 94]),
86    ("deep-net", [19, 33, 17, 75, 26, 16]),
87    ("laser-grid", [46, 201, 51, 226, 196, 21]),
88    ("quantum-flux", [135, 75, 171, 111, 98, 61]),
89    ("bio-hazard", [148, 184, 106, 192, 64, 22]),
90    ("darkwave", [53, 140, 89, 176, 127, 52]),
91    ("overlock", [196, 208, 160, 214, 124, 52]),
92    ("megacorp", [252, 39, 245, 81, 242, 236]),
93    ("zaibatsu", [167, 216, 131, 224, 95, 52]),
94    ("iftopcolor", [21, 46, 28, 48, 33, 19]),
95];
96
97/// Normalize a theme name for lenient matching: lowercase, drop `-`/`_`/space so
98/// `neon-noir`, `NeonNoir`, `neon_noir` and `neonnoir` all resolve.
99fn norm(s: &str) -> String {
100    s.chars()
101        .filter(|c| c.is_alphanumeric())
102        .flat_map(char::to_lowercase)
103        .collect()
104}
105
106/// Resolve a theme name to its palette (lenient matching); `None` if unknown.
107pub fn by_name(name: &str) -> Option<Palette> {
108    let want = norm(name);
109    THEMES
110        .iter()
111        .find(|(n, _)| norm(n) == want)
112        .map(|&(_, c)| Palette { c })
113}
114
115/// A `theme custom c1 c2 c3 c4 c5 c6` palette from six 256-color indices.
116pub fn custom(c: [u8; 6]) -> Palette {
117    Palette { c }
118}
119
120/// The default palette when a spec sets no `theme` — `neon-sprawl`, matching the
121/// `#[default]` of the sibling `iftoprs`/`htoprs` apps. `theme off` opts out to
122/// the classic cyan look (`Spec.theme = None`).
123pub fn default_palette() -> Palette {
124    Palette { c: THEMES[0].1 }
125}
126
127/// The baked default theme's kebab name (`neon-sprawl`).
128pub fn default_name() -> &'static str {
129    THEMES[0].0
130}
131
132/// Index of a palette in [`THEMES`] (for the `c`/Ctrl-T cycle start point); `0`
133/// for a custom palette that matches no built-in.
134pub fn index_of(p: Palette) -> usize {
135    THEMES.iter().position(|&(_, c)| c == p.c).unwrap_or(0)
136}
137
138/// `~/.arb/config.toml` (honoring `HOME`; `ARB_LIB`-style relocation isn't used
139/// for config).
140fn config_path() -> Option<std::path::PathBuf> {
141    std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".arb/config.toml"))
142}
143
144/// The user's global default theme name from `~/.arb/config.toml` `[ui] theme`
145/// (or a top-level `theme`), if set to a valid theme. `None` when unset/invalid
146/// or `ARB_NO_CONFIG` is set — the caller then falls back to [`default_palette`].
147pub fn config_default() -> Option<Palette> {
148    if std::env::var_os("ARB_NO_CONFIG").is_some() {
149        return None;
150    }
151    let text = std::fs::read_to_string(config_path()?).ok()?;
152    let v: toml::Value = text.parse().ok()?;
153    let name = v
154        .get("ui")
155        .and_then(|u| u.get("theme"))
156        .and_then(|t| t.as_str())
157        .or_else(|| v.get("theme").and_then(|t| t.as_str()))?;
158    by_name(name)
159}
160
161/// Persist `name` as the global default theme in `~/.arb/config.toml` `[ui]
162/// theme` (used by `arb --set-theme NAME`). Rewrites an existing `theme =` line
163/// in place or appends a `[ui]` section; validates the name first.
164pub fn set_config_default(name: &str) -> Result<(), String> {
165    if std::env::var_os("ARB_NO_CONFIG").is_some() {
166        return Ok(()); // config writes disabled (tests / opt-out)
167    }
168    let canon = THEMES
169        .iter()
170        .find(|(n, _)| norm(n) == norm(name))
171        .map(|&(n, _)| n)
172        .ok_or_else(|| format!("unknown theme `{name}` (see `arb --list-themes`)"))?;
173    let path = config_path().ok_or("no HOME for ~/.arb/config.toml")?;
174    if let Some(parent) = path.parent() {
175        let _ = std::fs::create_dir_all(parent);
176    }
177    let existing = std::fs::read_to_string(&path).unwrap_or_default();
178    let out = upsert_ui_theme(&existing, canon);
179    std::fs::write(&path, out).map_err(|e| format!("{}: {e}", path.display()))
180}
181
182/// Rewrite the `theme =` line under `[ui]` (or append the section) to `name`.
183fn upsert_ui_theme(existing: &str, name: &str) -> String {
184    let line = format!("theme = \"{name}\"");
185    // Replace an existing active `theme = ...` (commented or not) if present.
186    let mut lines: Vec<String> = existing.lines().map(String::from).collect();
187    if let Some(i) = lines.iter().position(|l| {
188        l.trim_start()
189            .trim_start_matches('#')
190            .trim_start()
191            .starts_with("theme =")
192    }) {
193        lines[i] = line;
194        return lines.join("\n") + "\n";
195    }
196    // Insert after an existing `[ui]` header, else append a new section.
197    if let Some(i) = lines.iter().position(|l| l.trim() == "[ui]") {
198        lines.insert(i + 1, line);
199        return lines.join("\n") + "\n";
200    }
201    let mut out = existing.trim_end().to_string();
202    if !out.is_empty() {
203        out.push('\n');
204    }
205    out.push_str(&format!("\n[ui]\n{line}\n"));
206    out
207}
208
209/// Every theme's kebab-name, in display order (for `--list-themes` / cycling).
210pub fn names() -> impl Iterator<Item = &'static str> {
211    THEMES.iter().map(|&(n, _)| n)
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn thirty_one_themes_all_distinct() {
220        assert_eq!(THEMES.len(), 31);
221        let mut seen = std::collections::HashSet::new();
222        for (n, _) in THEMES {
223            assert!(seen.insert(*n), "duplicate theme name {n}");
224        }
225    }
226
227    #[test]
228    fn lenient_name_matching() {
229        let p = by_name("neon-noir").unwrap();
230        assert_eq!(by_name("NeonNoir"), Some(p));
231        assert_eq!(by_name("neon_noir"), Some(p));
232        assert_eq!(by_name("neonnoir"), Some(p));
233        assert_eq!(by_name("NEON NOIR"), Some(p));
234        assert_eq!(by_name("nope"), None);
235    }
236
237    #[test]
238    fn palette_slots_map_to_indices() {
239        // neon-noir = [201, 231, 93, 219, 57, 53]
240        let p = by_name("neon-noir").unwrap();
241        assert_eq!(p.accent(), Color::Indexed(231)); // c2
242        assert_eq!(p.primary(), Color::Indexed(201)); // c1
243        assert_eq!(p.bg(), Color::Indexed(53)); // c6
244        assert_eq!(p.slot("dim"), Some(Color::Indexed(57))); // c5
245        assert_eq!(p.slot("bogus"), None);
246    }
247
248    #[test]
249    fn upsert_ui_theme_appends_or_replaces() {
250        // Empty config -> a new [ui] section.
251        let out = upsert_ui_theme("", "neon-noir");
252        assert!(out.contains("[ui]") && out.contains("theme = \"neon-noir\""));
253        // An existing commented `# theme = ...` line is replaced in place.
254        let cfg = "[ui]\n# theme = \"neon-sprawl\"\n";
255        let out = upsert_ui_theme(cfg, "blade-runner");
256        assert!(out.contains("theme = \"blade-runner\""));
257        assert!(!out.contains("neon-sprawl"));
258        // Existing [repl] section is preserved when appending [ui].
259        let out = upsert_ui_theme("[repl]\nmode = \"vi\"\n", "megacorp");
260        assert!(out.contains("[repl]") && out.contains("mode = \"vi\""));
261        assert!(out.contains("[ui]") && out.contains("megacorp"));
262    }
263
264    #[test]
265    fn default_name_is_neon_sprawl() {
266        assert_eq!(default_name(), "neon-sprawl");
267        assert_eq!(default_palette(), by_name("neon-sprawl").unwrap());
268    }
269
270    #[test]
271    fn custom_palette_from_six_indices() {
272        let p = custom([1, 2, 3, 4, 5, 6]);
273        assert_eq!(p.accent(), Color::Indexed(2));
274        assert_eq!(p.bg(), Color::Indexed(6));
275    }
276}