vtcode_core/ui/
theme.rs

1use anstyle::{Color, Effects, RgbColor, Style};
2use anyhow::{Context, Result, anyhow};
3use catppuccin::PALETTE;
4use once_cell::sync::Lazy;
5use parking_lot::RwLock;
6use std::collections::HashMap;
7
8/// Identifier for the default theme.
9pub const DEFAULT_THEME_ID: &str = "ciapre-dark";
10
11const MIN_CONTRAST: f64 = 4.5;
12
13/// Palette describing UI colors for the terminal experience.
14#[derive(Clone, Debug)]
15pub struct ThemePalette {
16    pub primary_accent: RgbColor,
17    pub background: RgbColor,
18    pub foreground: RgbColor,
19    pub secondary_accent: RgbColor,
20    pub alert: RgbColor,
21    pub logo_accent: RgbColor,
22}
23
24impl ThemePalette {
25    fn style_from(color: RgbColor, bold: bool) -> Style {
26        let mut style = Style::new().fg_color(Some(Color::Rgb(color)));
27        if bold {
28            style = style.bold();
29        }
30        style
31    }
32
33    fn build_styles(&self) -> ThemeStyles {
34        let primary = self.primary_accent;
35        let background = self.background;
36        let secondary = self.secondary_accent;
37
38        let fallback_light = RgbColor(0xFF, 0xFF, 0xFF);
39
40        let text_color = ensure_contrast(
41            self.foreground,
42            background,
43            MIN_CONTRAST,
44            &[
45                lighten(self.foreground, 0.25),
46                lighten(secondary, 0.2),
47                fallback_light,
48            ],
49        );
50        let info_color = ensure_contrast(
51            secondary,
52            background,
53            MIN_CONTRAST,
54            &[lighten(secondary, 0.2), text_color, fallback_light],
55        );
56        let tool_candidate = lighten(secondary, 0.3);
57        let tool_color = ensure_contrast(
58            tool_candidate,
59            background,
60            MIN_CONTRAST,
61            &[
62                lighten(secondary, 0.45),
63                lighten(primary, 0.35),
64                fallback_light,
65            ],
66        );
67        let response_color = ensure_contrast(
68            text_color,
69            background,
70            MIN_CONTRAST,
71            &[lighten(text_color, 0.15), fallback_light],
72        );
73        let reasoning_color = ensure_contrast(
74            lighten(secondary, 0.3),
75            background,
76            MIN_CONTRAST,
77            &[lighten(secondary, 0.15), text_color, fallback_light],
78        );
79        let reasoning_style = Self::style_from(reasoning_color, false).effects(Effects::ITALIC);
80        let user_color = ensure_contrast(
81            lighten(primary, 0.25),
82            background,
83            MIN_CONTRAST,
84            &[lighten(secondary, 0.15), info_color, text_color],
85        );
86        let alert_color = ensure_contrast(
87            self.alert,
88            background,
89            MIN_CONTRAST,
90            &[lighten(self.alert, 0.2), fallback_light, text_color],
91        );
92
93        ThemeStyles {
94            info: Self::style_from(info_color, true),
95            error: Self::style_from(alert_color, true),
96            output: Self::style_from(text_color, false),
97            response: Self::style_from(response_color, false),
98            reasoning: reasoning_style,
99            tool: Style::new().fg_color(Some(Color::Rgb(tool_color))).bold(),
100            user: Self::style_from(user_color, false),
101            primary: Self::style_from(primary, false),
102            secondary: Self::style_from(secondary, false),
103            background: Color::Rgb(background),
104            foreground: Color::Rgb(text_color),
105        }
106    }
107}
108
109/// Styles computed from palette colors.
110#[derive(Clone, Debug)]
111pub struct ThemeStyles {
112    pub info: Style,
113    pub error: Style,
114    pub output: Style,
115    pub response: Style,
116    pub reasoning: Style,
117    pub tool: Style,
118    pub user: Style,
119    pub primary: Style,
120    pub secondary: Style,
121    pub background: Color,
122    pub foreground: Color,
123}
124
125#[derive(Clone, Debug)]
126pub struct ThemeDefinition {
127    pub id: &'static str,
128    pub label: &'static str,
129    pub palette: ThemePalette,
130}
131
132#[derive(Clone, Debug)]
133struct ActiveTheme {
134    id: String,
135    label: String,
136    palette: ThemePalette,
137    styles: ThemeStyles,
138}
139
140#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
141enum CatppuccinFlavorKind {
142    Latte,
143    Frappe,
144    Macchiato,
145    Mocha,
146}
147
148impl CatppuccinFlavorKind {
149    const fn id(self) -> &'static str {
150        match self {
151            CatppuccinFlavorKind::Latte => "catppuccin-latte",
152            CatppuccinFlavorKind::Frappe => "catppuccin-frappe",
153            CatppuccinFlavorKind::Macchiato => "catppuccin-macchiato",
154            CatppuccinFlavorKind::Mocha => "catppuccin-mocha",
155        }
156    }
157
158    const fn label(self) -> &'static str {
159        match self {
160            CatppuccinFlavorKind::Latte => "Catppuccin Latte",
161            CatppuccinFlavorKind::Frappe => "Catppuccin Frappé",
162            CatppuccinFlavorKind::Macchiato => "Catppuccin Macchiato",
163            CatppuccinFlavorKind::Mocha => "Catppuccin Mocha",
164        }
165    }
166
167    fn flavor(self) -> catppuccin::Flavor {
168        match self {
169            CatppuccinFlavorKind::Latte => PALETTE.latte,
170            CatppuccinFlavorKind::Frappe => PALETTE.frappe,
171            CatppuccinFlavorKind::Macchiato => PALETTE.macchiato,
172            CatppuccinFlavorKind::Mocha => PALETTE.mocha,
173        }
174    }
175}
176
177static CATPPUCCIN_FLAVORS: &[CatppuccinFlavorKind] = &[
178    CatppuccinFlavorKind::Latte,
179    CatppuccinFlavorKind::Frappe,
180    CatppuccinFlavorKind::Macchiato,
181    CatppuccinFlavorKind::Mocha,
182];
183
184static REGISTRY: Lazy<HashMap<&'static str, ThemeDefinition>> = Lazy::new(|| {
185    let mut map = HashMap::new();
186    map.insert(
187        "ciapre-dark",
188        ThemeDefinition {
189            id: "ciapre-dark",
190            label: "Ciapre Dark",
191            palette: ThemePalette {
192                primary_accent: RgbColor(0xBF, 0xB3, 0x8F),
193                background: RgbColor(0x26, 0x26, 0x26),
194                foreground: RgbColor(0xBF, 0xB3, 0x8F),
195                secondary_accent: RgbColor(0xD9, 0x9A, 0x4E),
196                alert: RgbColor(0xFF, 0x8A, 0x8A),
197                logo_accent: RgbColor(0xD9, 0x9A, 0x4E),
198            },
199        },
200    );
201    map.insert(
202        "ciapre-blue",
203        ThemeDefinition {
204            id: "ciapre-blue",
205            label: "Ciapre Blue",
206            palette: ThemePalette {
207                primary_accent: RgbColor(0xBF, 0xB3, 0x8F),
208                background: RgbColor(0x17, 0x1C, 0x26),
209                foreground: RgbColor(0xBF, 0xB3, 0x8F),
210                secondary_accent: RgbColor(0xBF, 0xB3, 0x8F),
211                alert: RgbColor(0xFF, 0x8A, 0x8A),
212                logo_accent: RgbColor(0xD9, 0x9A, 0x4E),
213            },
214        },
215    );
216    register_catppuccin_themes(&mut map);
217    map
218});
219
220fn register_catppuccin_themes(map: &mut HashMap<&'static str, ThemeDefinition>) {
221    for &flavor_kind in CATPPUCCIN_FLAVORS {
222        let flavor = flavor_kind.flavor();
223        let theme_definition = ThemeDefinition {
224            id: flavor_kind.id(),
225            label: flavor_kind.label(),
226            palette: catppuccin_palette(flavor),
227        };
228        map.insert(flavor_kind.id(), theme_definition);
229    }
230}
231
232fn catppuccin_palette(flavor: catppuccin::Flavor) -> ThemePalette {
233    let colors = flavor.colors;
234    ThemePalette {
235        primary_accent: catppuccin_rgb(colors.lavender),
236        background: catppuccin_rgb(colors.base),
237        foreground: catppuccin_rgb(colors.text),
238        secondary_accent: catppuccin_rgb(colors.sapphire),
239        alert: catppuccin_rgb(colors.red),
240        logo_accent: catppuccin_rgb(colors.peach),
241    }
242}
243
244fn catppuccin_rgb(color: catppuccin::Color) -> RgbColor {
245    RgbColor(color.rgb.r, color.rgb.g, color.rgb.b)
246}
247
248static ACTIVE: Lazy<RwLock<ActiveTheme>> = Lazy::new(|| {
249    let default = REGISTRY
250        .get(DEFAULT_THEME_ID)
251        .expect("default theme must exist");
252    let styles = default.palette.build_styles();
253    RwLock::new(ActiveTheme {
254        id: default.id.to_string(),
255        label: default.label.to_string(),
256        palette: default.palette.clone(),
257        styles,
258    })
259});
260
261/// Set the active theme by identifier.
262pub fn set_active_theme(theme_id: &str) -> Result<()> {
263    let id_lc = theme_id.trim().to_lowercase();
264    let theme = REGISTRY
265        .get(id_lc.as_str())
266        .ok_or_else(|| anyhow!("Unknown theme '{theme_id}'"))?;
267
268    let styles = theme.palette.build_styles();
269    let mut guard = ACTIVE.write();
270    guard.id = theme.id.to_string();
271    guard.label = theme.label.to_string();
272    guard.palette = theme.palette.clone();
273    guard.styles = styles;
274    Ok(())
275}
276
277/// Get the identifier of the active theme.
278pub fn active_theme_id() -> String {
279    ACTIVE.read().id.clone()
280}
281
282/// Get the human-readable label of the active theme.
283pub fn active_theme_label() -> String {
284    ACTIVE.read().label.clone()
285}
286
287/// Get the current styles cloned from the active theme.
288pub fn active_styles() -> ThemeStyles {
289    ACTIVE.read().styles.clone()
290}
291
292/// Slightly adjusted accent color for banner-like copy.
293pub fn banner_color() -> RgbColor {
294    let guard = ACTIVE.read();
295    let accent = guard.palette.logo_accent;
296    let secondary = guard.palette.secondary_accent;
297    let background = guard.palette.background;
298    drop(guard);
299
300    let candidate = lighten(accent, 0.35);
301    ensure_contrast(
302        candidate,
303        background,
304        MIN_CONTRAST,
305        &[lighten(accent, 0.5), lighten(secondary, 0.25), accent],
306    )
307}
308
309/// Slightly darkened accent style for banner-like copy.
310pub fn banner_style() -> Style {
311    let accent = banner_color();
312    Style::new().fg_color(Some(Color::Rgb(accent))).bold()
313}
314
315/// Accent color for the startup banner logo.
316pub fn logo_accent_color() -> RgbColor {
317    ACTIVE.read().palette.logo_accent
318}
319
320/// Enumerate available theme identifiers.
321pub fn available_themes() -> Vec<&'static str> {
322    let mut keys: Vec<_> = REGISTRY.keys().copied().collect();
323    keys.sort();
324    keys
325}
326
327/// Look up a theme label for display.
328pub fn theme_label(theme_id: &str) -> Option<&'static str> {
329    REGISTRY.get(theme_id).map(|definition| definition.label)
330}
331
332fn relative_luminance(color: RgbColor) -> f64 {
333    fn channel(value: u8) -> f64 {
334        let c = (value as f64) / 255.0;
335        if c <= 0.03928 {
336            c / 12.92
337        } else {
338            ((c + 0.055) / 1.055).powf(2.4)
339        }
340    }
341    let r = channel(color.0);
342    let g = channel(color.1);
343    let b = channel(color.2);
344    0.2126 * r + 0.7152 * g + 0.0722 * b
345}
346
347fn contrast_ratio(foreground: RgbColor, background: RgbColor) -> f64 {
348    let fg = relative_luminance(foreground);
349    let bg = relative_luminance(background);
350    let (lighter, darker) = if fg > bg { (fg, bg) } else { (bg, fg) };
351    (lighter + 0.05) / (darker + 0.05)
352}
353
354fn ensure_contrast(
355    candidate: RgbColor,
356    background: RgbColor,
357    min_ratio: f64,
358    fallbacks: &[RgbColor],
359) -> RgbColor {
360    if contrast_ratio(candidate, background) >= min_ratio {
361        return candidate;
362    }
363    for &fallback in fallbacks {
364        if contrast_ratio(fallback, background) >= min_ratio {
365            return fallback;
366        }
367    }
368    candidate
369}
370
371fn mix(color: RgbColor, target: RgbColor, ratio: f64) -> RgbColor {
372    let ratio = ratio.clamp(0.0, 1.0);
373    let blend = |c: u8, t: u8| -> u8 {
374        let c = c as f64;
375        let t = t as f64;
376        ((c + (t - c) * ratio).round()).clamp(0.0, 255.0) as u8
377    };
378    RgbColor(
379        blend(color.0, target.0),
380        blend(color.1, target.1),
381        blend(color.2, target.2),
382    )
383}
384
385fn lighten(color: RgbColor, ratio: f64) -> RgbColor {
386    mix(color, RgbColor(0xFF, 0xFF, 0xFF), ratio)
387}
388
389/// Resolve a theme identifier from configuration or CLI input.
390pub fn resolve_theme(preferred: Option<String>) -> String {
391    preferred
392        .and_then(|candidate| {
393            let trimmed = candidate.trim().to_lowercase();
394            if trimmed.is_empty() {
395                None
396            } else if REGISTRY.contains_key(trimmed.as_str()) {
397                Some(trimmed)
398            } else {
399                None
400            }
401        })
402        .unwrap_or_else(|| DEFAULT_THEME_ID.to_string())
403}
404
405/// Validate a theme and return its label for messaging.
406pub fn ensure_theme(theme_id: &str) -> Result<&'static str> {
407    REGISTRY
408        .get(theme_id)
409        .map(|definition| definition.label)
410        .context("Theme not found")
411}