1use ratatui::style::Color;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct Palette {
18 pub c: [u8; 6],
20}
21
22impl Palette {
23 pub fn accent(&self) -> Color {
25 Color::Indexed(self.c[1])
26 }
27 pub fn primary(&self) -> Color {
29 Color::Indexed(self.c[0])
30 }
31 pub fn alt(&self) -> Color {
33 Color::Indexed(self.c[2])
34 }
35 pub fn mid(&self) -> Color {
37 Color::Indexed(self.c[3])
38 }
39 pub fn dim(&self) -> Color {
41 Color::Indexed(self.c[4])
42 }
43 pub fn bg(&self) -> Color {
45 Color::Indexed(self.c[5])
46 }
47 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
61pub 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
97fn norm(s: &str) -> String {
100 s.chars()
101 .filter(|c| c.is_alphanumeric())
102 .flat_map(char::to_lowercase)
103 .collect()
104}
105
106pub 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
115pub fn custom(c: [u8; 6]) -> Palette {
117 Palette { c }
118}
119
120pub fn default_palette() -> Palette {
124 Palette { c: THEMES[0].1 }
125}
126
127pub fn default_name() -> &'static str {
129 THEMES[0].0
130}
131
132pub fn index_of(p: Palette) -> usize {
135 THEMES.iter().position(|&(_, c)| c == p.c).unwrap_or(0)
136}
137
138fn 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
144pub 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
161pub fn set_config_default(name: &str) -> Result<(), String> {
165 if std::env::var_os("ARB_NO_CONFIG").is_some() {
166 return Ok(()); }
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
182fn upsert_ui_theme(existing: &str, name: &str) -> String {
184 let line = format!("theme = \"{name}\"");
185 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 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
209pub 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 let p = by_name("neon-noir").unwrap();
241 assert_eq!(p.accent(), Color::Indexed(231)); assert_eq!(p.primary(), Color::Indexed(201)); assert_eq!(p.bg(), Color::Indexed(53)); assert_eq!(p.slot("dim"), Some(Color::Indexed(57))); assert_eq!(p.slot("bogus"), None);
246 }
247
248 #[test]
249 fn upsert_ui_theme_appends_or_replaces() {
250 let out = upsert_ui_theme("", "neon-noir");
252 assert!(out.contains("[ui]") && out.contains("theme = \"neon-noir\""));
253 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 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}