Skip to main content

retch_cli/
theme.rs

1// SPDX-License-Identifier: GPL-3.0-or-later
2// Copyright (C) 2026 l1a
3
4//! Color theming and styling.
5//!
6//! Defines color palettes and provides functionality for applying
7//! colors to the output text.
8
9use owo_colors::{OwoColorize, Rgb};
10
11/// Parse a color name or hex string into an RGB value.
12///
13/// Supports named colors (e.g., "blue", "bright_red") and hex values
14/// (e.g., "#ff6432" or "ff6432").
15pub fn parse_color(input: &str) -> Option<Rgb> {
16    let s = input.trim();
17
18    // Hex color support
19    if s.starts_with('#') || s.len() == 6 {
20        let hex = s.strip_prefix('#').unwrap_or(s);
21        if hex.len() == 6 {
22            if let (Ok(r), Ok(g), Ok(b)) = (
23                u8::from_str_radix(&hex[0..2], 16),
24                u8::from_str_radix(&hex[2..4], 16),
25                u8::from_str_radix(&hex[4..6], 16),
26            ) {
27                return Some(Rgb(r, g, b));
28            }
29        }
30    }
31
32    // Named colors
33    match s.to_lowercase().as_str() {
34        "black" => Some(Rgb(0, 0, 0)),
35        "red" => Some(Rgb(255, 0, 0)),
36        "green" => Some(Rgb(0, 255, 0)),
37        "yellow" => Some(Rgb(255, 255, 0)),
38        "blue" => Some(Rgb(0, 0, 255)),
39        "magenta" => Some(Rgb(255, 0, 255)),
40        "cyan" => Some(Rgb(0, 255, 255)),
41        "white" => Some(Rgb(255, 255, 255)),
42        "bright_black" | "grey" | "gray" => Some(Rgb(128, 128, 128)),
43        "bright_red" => Some(Rgb(255, 128, 128)),
44        "bright_green" => Some(Rgb(128, 255, 128)),
45        "bright_yellow" => Some(Rgb(255, 255, 128)),
46        "bright_blue" => Some(Rgb(128, 128, 255)),
47        "bright_magenta" => Some(Rgb(255, 128, 255)),
48        "bright_cyan" => Some(Rgb(128, 255, 255)),
49        "bright_white" => Some(Rgb(255, 255, 255)),
50        _ => None,
51    }
52}
53
54/// A collection of colors used for terminal output.
55///
56/// Themes define how various parts of the system information fetch
57/// (labels, values, titles, etc.) are colored in the terminal.
58#[derive(Debug, Clone)]
59pub struct Theme {
60    /// The unique name of the theme.
61    pub name: String,
62    /// Color for field labels (e.g., "OS", "CPU").
63    pub label_color: Rgb,
64    /// Color for field values (e.g., "Fedora Linux", "Intel i7").
65    pub value_color: Rgb,
66    /// Color for accents and highlights.
67    pub accent_color: Rgb,
68    /// Color for the title/username line.
69    pub title_color: Rgb,
70    /// Color for separators like ":" or "---".
71    pub separator_color: Rgb,
72}
73
74impl Default for Theme {
75    fn default() -> Self {
76        Self {
77            name: "neutral".to_string(),
78            label_color: Rgb(0, 255, 255),       // Cyan
79            value_color: Rgb(255, 255, 255),     // White
80            accent_color: Rgb(0, 255, 0),        // Green
81            title_color: Rgb(255, 255, 0),       // Yellow
82            separator_color: Rgb(128, 128, 128), // BrightBlack / Gray
83        }
84    }
85}
86
87impl Theme {
88    /// Returns the built-in neutral theme.
89    pub fn neutral() -> Self {
90        Self::default()
91    }
92
93    /// Alias for `neutral()` for backward compatibility.
94    pub fn new_default() -> Self {
95        Self::neutral()
96    }
97
98    /// Returns the built-in dark theme.
99    pub fn dark() -> Self {
100        Self {
101            name: "dark".to_string(),
102            label_color: Rgb(128, 128, 255),     // Bright Blue
103            value_color: Rgb(255, 255, 255),     // Bright White
104            accent_color: Rgb(128, 255, 128),    // Bright Green
105            title_color: Rgb(255, 255, 128),     // Bright Yellow
106            separator_color: Rgb(128, 128, 128), // Bright Black / Gray
107        }
108    }
109
110    /// Returns the built-in light theme.
111    pub fn light() -> Self {
112        Self {
113            name: "light".to_string(),
114            label_color: Rgb(0, 0, 255),     // Blue
115            value_color: Rgb(0, 0, 0),       // Black
116            accent_color: Rgb(0, 255, 0),    // Green
117            title_color: Rgb(255, 255, 128), // Bright Yellow
118            separator_color: Rgb(0, 0, 0),   // Black
119        }
120    }
121
122    // === Popular Community Themes ===
123
124    /// Returns the Catppuccin Latte (light) theme.
125    pub fn catppuccin_latte() -> Self {
126        Self {
127            name: "catppuccin-latte".to_string(),
128            label_color: Rgb(30, 102, 245),      // Blue      #1e66f5
129            value_color: Rgb(76, 79, 105),       // Text      #4c4f69
130            accent_color: Rgb(64, 160, 43),      // Green     #40a02b
131            title_color: Rgb(223, 142, 29),      // Yellow    #df8e1d
132            separator_color: Rgb(140, 143, 161), // Overlay0  #8c8fa1
133        }
134    }
135
136    /// Returns the Catppuccin Frappe theme.
137    pub fn catppuccin_frappe() -> Self {
138        Self {
139            name: "catppuccin-frappe".to_string(),
140            label_color: Rgb(137, 180, 250),    // Blue      #89b4fa
141            value_color: Rgb(198, 208, 245),    // Text      #c6d0f5
142            accent_color: Rgb(166, 227, 161),   // Green     #a6e3a1
143            title_color: Rgb(249, 226, 175),    // Yellow    #f9e2af
144            separator_color: Rgb(98, 104, 128), // Overlay0  #626880
145        }
146    }
147
148    /// Returns the Catppuccin Macchiato theme.
149    pub fn catppuccin_macchiato() -> Self {
150        Self {
151            name: "catppuccin-macchiato".to_string(),
152            label_color: Rgb(138, 173, 244),   // Blue      #8aadf4
153            value_color: Rgb(202, 211, 245),   // Text      #cad3f5
154            accent_color: Rgb(166, 218, 149),  // Green     #a6da95
155            title_color: Rgb(238, 212, 159),   // Yellow    #eed6af
156            separator_color: Rgb(91, 96, 120), // Overlay0  #5b6078
157        }
158    }
159
160    /// Returns the Catppuccin Mocha theme.
161    pub fn catppuccin_mocha() -> Self {
162        Self {
163            name: "catppuccin-mocha".to_string(),
164            label_color: Rgb(137, 180, 250),     // Blue      #89b4fa
165            value_color: Rgb(205, 214, 244),     // Text      #cdd6f4
166            accent_color: Rgb(245, 194, 231),    // Pink      #f5c2e7
167            title_color: Rgb(249, 226, 175),     // Yellow    #f9e2af
168            separator_color: Rgb(108, 112, 134), // Overlay0  #6c7086
169        }
170    }
171
172    /// Returns the Solarized Light theme.
173    pub fn solarized_light() -> Self {
174        Self {
175            name: "solarized-light".to_string(),
176            label_color: Rgb(38, 139, 210),      // blue      #268bd2
177            value_color: Rgb(101, 123, 131),     // base00    #657b83
178            accent_color: Rgb(181, 137, 0),      // yellow    #b58900
179            title_color: Rgb(203, 75, 22),       // orange    #cb4b16
180            separator_color: Rgb(147, 161, 161), // base1     #93a1a1
181        }
182    }
183
184    /// Returns the Solarized Dark theme.
185    pub fn solarized_dark() -> Self {
186        Self {
187            name: "solarized-dark".to_string(),
188            label_color: Rgb(38, 139, 210),      // blue      #268bd2
189            value_color: Rgb(131, 148, 150),     // base0     #839496
190            accent_color: Rgb(181, 137, 0),      // yellow    #b58900
191            title_color: Rgb(203, 75, 22),       // orange    #cb4b16
192            separator_color: Rgb(147, 161, 161), // base1     #93a1a1
193        }
194    }
195
196    /// Look up a built-in theme by its name.
197    pub fn from_name(name: &str) -> Self {
198        match name.to_lowercase().replace('_', "-").as_str() {
199            "dark" => Self::dark(),
200            "light" => Self::light(),
201            "neutral" | "default" => Self::neutral(), // "default" kept for backward compat
202            "custom" => Self::default(),
203            "auto" => Self::detect_system_theme(),
204            "catppuccin-latte" | "catppuccin_latte" | "latte" => Self::catppuccin_latte(),
205            "catppuccin-frappe" | "catppuccin_frappe" | "frappe" => Self::catppuccin_frappe(),
206            "catppuccin-macchiato" | "catppuccin_macchiato" | "macchiato" => {
207                Self::catppuccin_macchiato()
208            }
209            "catppuccin-mocha" | "catppuccin_mocha" | "mocha" => Self::catppuccin_mocha(),
210            "solarized-light" | "solarized_light" => Self::solarized_light(),
211            "solarized-dark" | "solarized_dark" => Self::solarized_dark(),
212            _ => Self::default(),
213        }
214    }
215
216    /// Detect system dark/light preference (currently supports GTK settings).
217    ///
218    /// Falls back to `Self::dark()` if detection fails.
219    pub fn detect_system_theme() -> Self {
220        // Try to read GTK settings
221        if let Some(config_dir) = dirs::config_dir() {
222            let gtk_settings = config_dir.join("gtk-3.0").join("settings.ini");
223            if gtk_settings.exists() {
224                if let Ok(contents) = std::fs::read_to_string(&gtk_settings) {
225                    for line in contents.lines() {
226                        if line.to_lowercase().contains("prefer-dark-theme") {
227                            if line.to_lowercase().contains("true") {
228                                return Self::dark();
229                            } else {
230                                return Self::light();
231                            }
232                        }
233                    }
234                }
235            }
236        }
237        // Default fallback
238        Self::dark()
239    }
240
241    /// Build a new theme by applying custom color overrides to an existing base theme.
242    pub fn with_custom_overrides(base: Self, custom: &crate::config::CustomTheme) -> Self {
243        let mut theme = base;
244
245        if let Some(color) = &custom.label_color {
246            if let Some(c) = parse_color(color) {
247                theme.label_color = c;
248            }
249        }
250        if let Some(color) = &custom.value_color {
251            if let Some(c) = parse_color(color) {
252                theme.value_color = c;
253            }
254        }
255        if let Some(color) = &custom.accent_color {
256            if let Some(c) = parse_color(color) {
257                theme.accent_color = c;
258            }
259        }
260        if let Some(color) = &custom.title_color {
261            if let Some(c) = parse_color(color) {
262                theme.title_color = c;
263            }
264        }
265        if let Some(color) = &custom.separator_color {
266            if let Some(c) = parse_color(color) {
267                theme.separator_color = c;
268            }
269        }
270
271        theme
272    }
273
274    /// Apply the theme's label color to the given text.
275    pub fn color_label(&self, text: &str) -> String {
276        text.color(self.label_color).to_string()
277    }
278
279    /// Apply the theme's value color to the given text.
280    pub fn color_value(&self, text: &str) -> String {
281        text.color(self.value_color).to_string()
282    }
283
284    /// Apply the theme's accent color to the given text.
285    pub fn color_accent(&self, text: &str) -> String {
286        text.color(self.accent_color).to_string()
287    }
288
289    /// Apply the theme's separator color to the given text.
290    pub fn color_separator(&self, text: &str) -> String {
291        text.color(self.separator_color).to_string()
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn test_neutral_theme() {
301        let theme = Theme::neutral();
302        assert_eq!(theme.name, "neutral");
303        assert_eq!(theme.label_color, Rgb(0, 255, 255));
304        assert_eq!(theme.value_color, Rgb(255, 255, 255));
305        assert_eq!(theme.accent_color, Rgb(0, 255, 0));
306        assert_eq!(theme.title_color, Rgb(255, 255, 0));
307    }
308
309    #[test]
310    fn test_dark_theme() {
311        let theme = Theme::dark();
312        assert_eq!(theme.name, "dark");
313        assert_eq!(theme.label_color, Rgb(128, 128, 255));
314        assert_eq!(theme.title_color, Rgb(255, 255, 128));
315    }
316
317    #[test]
318    fn test_light_theme() {
319        let theme = Theme::light();
320        assert_eq!(theme.name, "light");
321        assert_eq!(theme.label_color, Rgb(0, 0, 255));
322        assert_eq!(theme.title_color, Rgb(255, 255, 128));
323    }
324
325    #[test]
326    fn test_new_default() {
327        let theme = Theme::new_default();
328        assert_eq!(theme.name, "neutral");
329    }
330
331    #[test]
332    fn test_parse_color() {
333        assert_eq!(parse_color("#ff0000"), Some(Rgb(255, 0, 0)));
334        assert_eq!(parse_color("00ff00"), Some(Rgb(0, 255, 0)));
335        assert_eq!(parse_color("blue"), Some(Rgb(0, 0, 255)));
336        assert_eq!(parse_color("invalid"), None);
337    }
338
339    #[test]
340    fn test_from_name() {
341        assert_eq!(Theme::from_name("dark").name, "dark");
342        assert_eq!(Theme::from_name("light").name, "light");
343        assert_eq!(Theme::from_name("mocha").name, "catppuccin-mocha");
344        assert_eq!(Theme::from_name("unknown").name, "neutral");
345    }
346
347    #[test]
348    fn test_with_custom_overrides_all_fields() {
349        let base = Theme::neutral();
350        let custom = crate::config::CustomTheme {
351            label_color: Some("#123456".to_string()),
352            value_color: Some("blue".to_string()),
353            accent_color: Some("#ff00ff".to_string()),
354            title_color: Some("green".to_string()),
355            separator_color: Some("#00ff00".to_string()),
356        };
357        let theme = Theme::with_custom_overrides(base, &custom);
358        assert_eq!(theme.label_color, Rgb(18, 52, 86));
359        assert_eq!(theme.value_color, Rgb(0, 0, 255));
360        assert_eq!(theme.accent_color, Rgb(255, 0, 255));
361        assert_eq!(theme.title_color, Rgb(0, 255, 0));
362        assert_eq!(theme.separator_color, Rgb(0, 255, 0));
363    }
364
365    #[test]
366    fn test_with_custom_overrides_invalid() {
367        let base = Theme::neutral();
368        let custom = crate::config::CustomTheme {
369            label_color: Some("invalid_color".to_string()),
370            value_color: Some("#123".to_string()), // invalid hex length
371            accent_color: Some("".to_string()),
372            title_color: None,
373            separator_color: Some("#ffg000".to_string()), // invalid hex char
374        };
375        let theme = Theme::with_custom_overrides(base.clone(), &custom);
376        // Should fallback to base theme colors
377        assert_eq!(theme.label_color, base.label_color);
378        assert_eq!(theme.value_color, base.value_color);
379        assert_eq!(theme.accent_color, base.accent_color);
380        assert_eq!(theme.title_color, base.title_color);
381        assert_eq!(theme.separator_color, base.separator_color);
382    }
383
384    #[test]
385    fn test_parse_color_hex_variants() {
386        // Upper case hex
387        assert_eq!(parse_color("#FF6432"), Some(Rgb(255, 100, 50)));
388        // Lower case hex
389        assert_eq!(parse_color("#ff6432"), Some(Rgb(255, 100, 50)));
390        // Mixed case hex
391        assert_eq!(parse_color("#Ff6432"), Some(Rgb(255, 100, 50)));
392        // Hex without # prefix
393        assert_eq!(parse_color("FF6432"), Some(Rgb(255, 100, 50)));
394        // Space padded hex
395        assert_eq!(parse_color("  #FF6432  "), Some(Rgb(255, 100, 50)));
396        // Invalid hex lengths
397        assert_eq!(parse_color("#fff"), None);
398        assert_eq!(parse_color("fff"), None);
399        assert_eq!(parse_color("#fffffff"), None);
400        // Invalid hex chars
401        assert_eq!(parse_color("#ff643g"), None);
402    }
403}