Skip to main content

adk_surface/tui/
theme.rs

1//! Light and dark from the visual tokens of spec 3.3 §9.
2
3use std::str::FromStr;
4use std::time::Duration;
5
6use ratatui::style::{Color, Modifier, Style};
7
8/// Which theme the terminal uses (spec 3.3 §9): detected from the terminal's background,
9/// or set.
10///
11/// # Example
12///
13/// ```rust
14/// use adk_surface::tui::ThemeChoice;
15///
16/// assert_eq!("dark".parse::<ThemeChoice>().unwrap(), ThemeChoice::Dark);
17/// assert_eq!(ThemeChoice::default(), ThemeChoice::Auto);
18/// ```
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20pub enum ThemeChoice {
21    /// Light on a light terminal background, dark on a dark one.
22    #[default]
23    Auto,
24    /// The light set.
25    Light,
26    /// The dark set.
27    Dark,
28}
29
30impl FromStr for ThemeChoice {
31    type Err = String;
32
33    fn from_str(value: &str) -> Result<Self, Self::Err> {
34        match value.trim().to_ascii_lowercase().as_str() {
35            "auto" => Ok(Self::Auto),
36            "light" => Ok(Self::Light),
37            "dark" => Ok(Self::Dark),
38            other => Err(format!("unknown theme '{other}': use auto, light or dark")),
39        }
40    }
41}
42
43/// Light or dark: which set of the spec 3.3 §9 tokens the terminal draws with.
44///
45/// # Example
46///
47/// ```rust
48/// use adk_surface::tui::{Appearance, ThemeChoice};
49///
50/// assert_eq!(ThemeChoice::Light.resolve(), Appearance::Light);
51/// ```
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Appearance {
54    /// The light set of §9.
55    Light,
56    /// The dark set of §9.
57    Dark,
58}
59
60impl ThemeChoice {
61    /// The appearance: `Auto` asks the terminal for its background (OSC 11, a short wait),
62    /// then reads `COLORFGBG`, and falls back to dark.
63    pub fn resolve(self) -> Appearance {
64        match self {
65            Self::Light => Appearance::Light,
66            Self::Dark => Appearance::Dark,
67            Self::Auto => detect(),
68        }
69    }
70}
71
72fn detect() -> Appearance {
73    let mut options = terminal_colorsaurus::QueryOptions::default();
74    options.timeout = Duration::from_millis(300);
75    match terminal_colorsaurus::theme_mode(options) {
76        Ok(terminal_colorsaurus::ThemeMode::Light) => return Appearance::Light,
77        Ok(terminal_colorsaurus::ThemeMode::Dark) => return Appearance::Dark,
78        Err(error) => tracing::debug!(error = %error, "the terminal did not report its background"),
79    }
80    // rxvt, Konsole and others: "fg;bg", where 7 and 15 are light backgrounds.
81    if let Ok(value) = std::env::var("COLORFGBG")
82        && let Some(background) = value.rsplit(';').next()
83    {
84        return match background.trim() {
85            "7" | "15" => Appearance::Light,
86            _ => Appearance::Dark,
87        };
88    }
89    Appearance::Dark
90}
91
92/// The §9 tokens and the status colours, as RGB.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub(crate) struct Palette {
95    pub background: (u8, u8, u8),
96    pub raised: (u8, u8, u8),
97    pub border: (u8, u8, u8),
98    pub text: (u8, u8, u8),
99    pub secondary: (u8, u8, u8),
100    pub label: (u8, u8, u8),
101    pub brand: (u8, u8, u8),
102    pub accent: (u8, u8, u8),
103    pub button: (u8, u8, u8),
104    pub button_text: (u8, u8, u8),
105    pub decision: (u8, u8, u8),
106    /// The decision's header row and the status line: the decision background, deeper.
107    pub decision_strong: (u8, u8, u8),
108    pub stop: (u8, u8, u8),
109    pub stop_text: (u8, u8, u8),
110    pub working: (u8, u8, u8),
111    pub done: (u8, u8, u8),
112    pub failed: (u8, u8, u8),
113}
114
115const fn rgb(hex: u32) -> (u8, u8, u8) {
116    (((hex >> 16) & 0xff) as u8, ((hex >> 8) & 0xff) as u8, (hex & 0xff) as u8)
117}
118
119/// Spec 3.3 §9, light.
120const LIGHT: Palette = Palette {
121    background: rgb(0xFFFFFF),
122    raised: rgb(0xF4F4F1),
123    border: rgb(0xE7E6E2),
124    text: rgb(0x18181B),
125    secondary: rgb(0x4B4B53),
126    label: rgb(0x6B6B74),
127    brand: rgb(0xF74C00),
128    accent: rgb(0xC2410C),
129    button: rgb(0xC2410C),
130    button_text: rgb(0xFFFFFF),
131    decision: rgb(0xFFF7F1),
132    decision_strong: rgb(0xFFEDE1),
133    stop: rgb(0x18181B),
134    stop_text: rgb(0xFFFFFF),
135    working: rgb(0x15803D),
136    done: rgb(0x1D4ED8),
137    failed: rgb(0xB91C1C),
138};
139
140/// Spec 3.3 §9, dark: the light screen with the dark set, layered from near black.
141const DARK: Palette = Palette {
142    background: rgb(0x0E0F11),
143    raised: rgb(0x1E1F23),
144    border: rgb(0x2C2D32),
145    text: rgb(0xEDEDEF),
146    secondary: rgb(0xB5B5BD),
147    label: rgb(0x8E8E97),
148    brand: rgb(0xFF6A1F),
149    accent: rgb(0xFF8A4C),
150    button: rgb(0xFF8A4C),
151    button_text: rgb(0x1A0D05),
152    decision: rgb(0x1F1610),
153    decision_strong: rgb(0x2A1D13),
154    stop: rgb(0xEDEDEF),
155    stop_text: rgb(0x0E0F11),
156    working: rgb(0x4ADE80),
157    done: rgb(0x93B4FF),
158    failed: rgb(0xFCA5A5),
159};
160
161/// The terminal's theme: the spec 3.3 §9 tokens of one appearance, as the terminal can show
162/// them.
163///
164/// # Example
165///
166/// ```rust
167/// use adk_surface::tui::{Appearance, Theme};
168///
169/// let theme = Theme::new(Appearance::Dark, true);
170/// assert_eq!(theme.appearance(), Appearance::Dark);
171/// ```
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct Theme {
174    appearance: Appearance,
175    truecolor: bool,
176    palette: Palette,
177}
178
179impl Theme {
180    /// The theme of `appearance`, in 24-bit colour when `truecolor`, else the nearest of the
181    /// 256 indexed colours.
182    pub fn new(appearance: Appearance, truecolor: bool) -> Self {
183        let palette = match appearance {
184            Appearance::Light => LIGHT,
185            Appearance::Dark => DARK,
186        };
187        Self { appearance, truecolor, palette }
188    }
189
190    /// The theme of `choice`, in the colours this terminal advertises (`COLORTERM`).
191    pub fn detect(choice: ThemeChoice) -> Self {
192        Self::new(choice.resolve(), truecolor())
193    }
194
195    /// Light or dark.
196    pub fn appearance(&self) -> Appearance {
197        self.appearance
198    }
199
200    pub(crate) fn palette(&self) -> &Palette {
201        &self.palette
202    }
203
204    pub(crate) fn color(&self, (r, g, b): (u8, u8, u8)) -> Color {
205        if self.truecolor { Color::Rgb(r, g, b) } else { Color::Indexed(xterm_index(r, g, b)) }
206    }
207
208    /// Text on the page.
209    pub(crate) fn base(&self) -> Style {
210        Style::new().fg(self.color(self.palette.text)).bg(self.color(self.palette.background))
211    }
212
213    pub(crate) fn fg(&self, token: (u8, u8, u8)) -> Style {
214        Style::new().fg(self.color(token))
215    }
216
217    pub(crate) fn text(&self) -> Style {
218        self.fg(self.palette.text)
219    }
220
221    pub(crate) fn secondary(&self) -> Style {
222        self.fg(self.palette.secondary)
223    }
224
225    pub(crate) fn label(&self) -> Style {
226        self.fg(self.palette.label)
227    }
228
229    pub(crate) fn heading(&self) -> Style {
230        self.label().add_modifier(Modifier::BOLD)
231    }
232
233    pub(crate) fn accent(&self) -> Style {
234        self.fg(self.palette.accent)
235    }
236
237    pub(crate) fn border(&self) -> Style {
238        self.fg(self.palette.border)
239    }
240
241    /// A key, drawn as a keycap.
242    pub(crate) fn keycap(&self) -> Style {
243        Style::new().fg(self.color(self.palette.background)).bg(self.color(self.palette.text))
244    }
245
246    /// The filled badge of a count (spec 3.3 §7.1).
247    pub(crate) fn badge(&self) -> Style {
248        Style::new()
249            .fg(self.color(self.palette.button_text))
250            .bg(self.color(self.palette.button))
251            .add_modifier(Modifier::BOLD)
252    }
253
254    /// The stop control (spec 3.3 §9).
255    pub(crate) fn stop(&self) -> Style {
256        Style::new().fg(self.color(self.palette.stop_text)).bg(self.color(self.palette.stop))
257    }
258}
259
260/// Whether the terminal advertises 24-bit colour.
261fn truecolor() -> bool {
262    let colorterm = std::env::var("COLORTERM").unwrap_or_default().to_ascii_lowercase();
263    colorterm == "truecolor"
264        || colorterm == "24bit"
265        || std::env::var_os("WT_SESSION").is_some()
266        || matches!(
267            std::env::var("TERM_PROGRAM").as_deref(),
268            Ok("iTerm.app" | "WezTerm" | "vscode" | "ghostty")
269        )
270}
271
272/// The nearest xterm 256-colour index to `(r, g, b)`: the 6×6×6 cube or the grey ramp.
273fn xterm_index(r: u8, g: u8, b: u8) -> u8 {
274    const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
275    let level = |v: u8| -> usize {
276        LEVELS
277            .iter()
278            .enumerate()
279            .min_by_key(|(_, l)| (i32::from(**l) - i32::from(v)).abs())
280            .map_or(0, |(i, _)| i)
281    };
282    let (ri, gi, bi) = (level(r), level(g), level(b));
283    let cube = (LEVELS[ri], LEVELS[gi], LEVELS[bi]);
284    let grey_step = ((u32::from(r) + u32::from(g) + u32::from(b)) / 3).saturating_sub(8) / 10;
285    let grey_step = grey_step.min(23) as u8;
286    let grey = 8 + 10 * grey_step;
287    let distance = |(a, b2, c): (u8, u8, u8)| -> i32 {
288        let d = |x: u8, y: u8| (i32::from(x) - i32::from(y)).pow(2);
289        d(a, r) + d(b2, g) + d(c, b)
290    };
291    if distance((grey, grey, grey)) < distance(cube) {
292        232 + grey_step
293    } else {
294        16 + 36 * ri as u8 + 6 * gi as u8 + bi as u8
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn the_tokens_of_section_9() {
304        assert_eq!(LIGHT.background, (0xFF, 0xFF, 0xFF));
305        assert_eq!(LIGHT.decision, (0xFF, 0xF7, 0xF1));
306        assert_eq!(LIGHT.accent, (0xC2, 0x41, 0x0C));
307        assert_eq!(DARK.background, (0x0E, 0x0F, 0x11));
308        assert_eq!(DARK.decision, (0x1F, 0x16, 0x10));
309        assert_eq!(DARK.accent, (0xFF, 0x8A, 0x4C));
310        // The brand is the one orange, brightened for the dark set.
311        assert_eq!(LIGHT.brand, (0xF7, 0x4C, 0x00));
312        assert_eq!(DARK.brand, (0xFF, 0x6A, 0x1F));
313    }
314
315    #[test]
316    fn indexed_colours_are_the_nearest() {
317        assert_eq!(xterm_index(255, 255, 255), 231);
318        assert_eq!(xterm_index(0, 0, 0), 16);
319        assert_eq!(xterm_index(0x80, 0x80, 0x80), 244);
320        let theme = Theme::new(Appearance::Light, false);
321        assert!(matches!(theme.color(LIGHT.accent), Color::Indexed(_)));
322        assert_eq!(
323            Theme::new(Appearance::Dark, true).color(DARK.text),
324            Color::Rgb(0xED, 0xED, 0xEF)
325        );
326    }
327}