Skip to main content

ados_term/
theme.rs

1//! Color + glyph theme for the terminal UI, with capability tiers.
2//!
3//! The palette is amber-on-charcoal: a charcoal background, near-white
4//! headings, muted gray body text, and a single amber accent for what is
5//! selected or acted on. Destructive is a salmon red, success a soft green.
6//!
7//! Color is emitted at the tier the terminal can show: truecolor (24-bit RGB),
8//! a 256-color fallback (nearest xterm index), a basic 16-color fallback, or
9//! plain text when there is no color at all. Every styled span resets only the
10//! foreground (`ESC[39m`) or the bold attribute (`ESC[22m`), never the whole
11//! SGR state, so the charcoal background painted once per frame is preserved
12//! across padding and borders. Only the selection bar changes the background,
13//! and it restores the charcoal base itself.
14//!
15//! Glyphs (marks, spinner, box drawing) are keyed on an ASCII tier for
16//! `--ascii`, non-UTF-8 locales, and basic terminals. Width math elsewhere
17//! counts `chars()`, so every glyph here is one display column.
18
19/// An RGB color for the truecolor tier.
20type Rgb = (u8, u8, u8);
21
22// --- palette (generated from the brand design tokens) ------------------------
23
24use crate::palette_generated::{
25    AMBER, AMBER_256, AMBER_DEEP, AMBER_LIGHT, CHARCOAL, CHARCOAL_256, DANGER, DANGER_256, HEADING,
26    HEADING_256, MUTED, MUTED_256, ON_AMBER, ON_AMBER_256, SUCCESS, SUCCESS_256, WARNING,
27    WARNING_256,
28};
29
30/// The braille spinner frames (the modern gold standard).
31const SPIN_UNICODE: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
32/// ASCII spinner fallback.
33const SPIN_ASCII: &[&str] = &["-", "\\", "|", "/"];
34
35/// How much color the terminal can render.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ColorTier {
38    /// 24-bit RGB (`COLORTERM=truecolor`).
39    Truecolor,
40    /// 256-color indexed (`TERM=*-256color`).
41    Ansi256,
42    /// Basic 16-color (bold + named foreground).
43    Basic,
44    /// No color: `NO_COLOR`, `--no-color`, `TERM=dumb`, or not a terminal.
45    None,
46}
47
48/// Box-drawing glyphs (rounded) and their ASCII fallbacks.
49pub struct BoxChars {
50    /// Top-left corner.
51    pub tl: &'static str,
52    /// Top-right corner.
53    pub tr: &'static str,
54    /// Bottom-left corner.
55    pub bl: &'static str,
56    /// Bottom-right corner.
57    pub br: &'static str,
58    /// Horizontal edge.
59    pub h: &'static str,
60    /// Vertical edge.
61    pub v: &'static str,
62}
63
64/// Resolved color + glyph capability for this run.
65#[derive(Debug, Clone, Copy)]
66pub struct Theme {
67    /// Use the ASCII glyph tier (no Unicode box/spinner/marks).
68    pub ascii: bool,
69    /// The color depth to emit at.
70    pub tier: ColorTier,
71}
72
73impl Theme {
74    /// Resolve from the flags + environment. `NO_COLOR` (any value) or
75    /// `--no-color` disables color; `--ascii` or a non-UTF-8 locale selects the
76    /// ASCII glyph tier. The color depth comes from `COLORTERM` + `TERM`.
77    pub fn detect(no_color_flag: bool, ascii_flag: bool) -> Theme {
78        let no_color = std::env::var_os("NO_COLOR").is_some() || no_color_flag;
79        Theme {
80            ascii: ascii_flag || !locale_is_utf8(),
81            tier: detect_tier(no_color),
82        }
83    }
84
85    /// Whether the tier paints a real background (truecolor / 256). Basic and
86    /// plain tiers use the terminal's own background.
87    pub fn paints_background(&self) -> bool {
88        matches!(self.tier, ColorTier::Truecolor | ColorTier::Ansi256)
89    }
90
91    /// The escape that sets the charcoal background for a frame, or empty when
92    /// the tier does not paint a background.
93    pub fn background_prefix(&self) -> String {
94        match self.tier {
95            ColorTier::Truecolor => bg_rgb(CHARCOAL),
96            ColorTier::Ansi256 => format!("\x1b[48;5;{CHARCOAL_256}m"),
97            _ => String::new(),
98        }
99    }
100
101    // --- foreground color helpers (foreground-only reset) ------------------
102
103    fn fg(&self, rgb: Rgb, idx: u8, basic: u8, s: &str) -> String {
104        match self.tier {
105            ColorTier::Truecolor => format!("\x1b[38;2;{};{};{}m{s}\x1b[39m", rgb.0, rgb.1, rgb.2),
106            ColorTier::Ansi256 => format!("\x1b[38;5;{idx}m{s}\x1b[39m"),
107            ColorTier::Basic => format!("\x1b[{basic}m{s}\x1b[39m"),
108            ColorTier::None => s.to_string(),
109        }
110    }
111
112    /// Success green.
113    pub fn ok(&self, s: &str) -> String {
114        self.fg(SUCCESS, SUCCESS_256, 32, s)
115    }
116    /// Destructive salmon red.
117    pub fn fail(&self, s: &str) -> String {
118        self.fg(DANGER, DANGER_256, 31, s)
119    }
120    /// The amber accent (selected / acted-on).
121    pub fn accent(&self, s: &str) -> String {
122        self.fg(AMBER, AMBER_256, 33, s)
123    }
124    /// Warning yellow.
125    pub fn warn(&self, s: &str) -> String {
126        self.fg(WARNING, WARNING_256, 33, s)
127    }
128    /// Muted gray body text.
129    pub fn dim(&self, s: &str) -> String {
130        self.fg(MUTED, MUTED_256, 90, s)
131    }
132    /// A bold near-white heading.
133    pub fn heading(&self, s: &str) -> String {
134        self.bold(&self.fg(HEADING, HEADING_256, 97, s))
135    }
136    /// Bold, resetting only the bold attribute.
137    pub fn bold(&self, s: &str) -> String {
138        if self.tier == ColorTier::None {
139            s.to_string()
140        } else {
141            format!("\x1b[1m{s}\x1b[22m")
142        }
143    }
144
145    /// Color one row of the block wordmark with an amber shade, lighter at the
146    /// top and deeper at the bottom (a subtle vertical gradient). The 256 and
147    /// basic tiers use the single amber accent; plain is untouched.
148    pub fn amber_gradient(&self, row: usize, s: &str) -> String {
149        match self.tier {
150            ColorTier::Truecolor => {
151                let rgb = match row {
152                    0 => AMBER_LIGHT,
153                    1 => AMBER,
154                    _ => AMBER_DEEP,
155                };
156                self.bold(&format!(
157                    "\x1b[38;2;{};{};{}m{s}\x1b[39m",
158                    rgb.0, rgb.1, rgb.2
159                ))
160            }
161            _ => self.bold(&self.accent(s)),
162        }
163    }
164
165    /// A full-width solid amber selection bar with dark text, `width` display
166    /// columns wide. In the basic and plain tiers there is no background to
167    /// draw, so the row degrades to an accented marker plus a bold label (the
168    /// caller pads it to width). `content` is plain text (no embedded escapes).
169    pub fn selection_bar(&self, content: &str, width: usize) -> String {
170        let body = pad_or_clip(content, width);
171        match self.tier {
172            ColorTier::Truecolor => format!(
173                "{}{}{body}{}",
174                bg_rgb(AMBER),
175                fg_rgb(ON_AMBER),
176                self.restore_base()
177            ),
178            ColorTier::Ansi256 => format!(
179                "\x1b[48;5;{AMBER_256}m\x1b[38;5;{ON_AMBER_256}m{body}{}",
180                self.restore_base()
181            ),
182            // No background tier: keep the label readable without a bar.
183            ColorTier::Basic => self.bold(&self.accent(content)),
184            ColorTier::None => content.to_string(),
185        }
186    }
187
188    /// The escape that restores the base background + default foreground after a
189    /// span that changed the background (the selection bar). Truecolor and 256
190    /// tiers restore charcoal; other tiers only reset the foreground.
191    fn restore_base(&self) -> String {
192        match self.tier {
193            ColorTier::Truecolor => format!("{}\x1b[39m", bg_rgb(CHARCOAL)),
194            ColorTier::Ansi256 => format!("\x1b[48;5;{CHARCOAL_256}m\x1b[39m"),
195            _ => "\x1b[39m".to_string(),
196        }
197    }
198
199    // --- glyphs ------------------------------------------------------------
200
201    /// The current spinner frame glyph.
202    pub fn spinner(&self, frame: usize) -> &'static str {
203        if self.ascii {
204            SPIN_ASCII[frame % SPIN_ASCII.len()]
205        } else {
206            SPIN_UNICODE[frame % SPIN_UNICODE.len()]
207        }
208    }
209    /// The success mark (`✓` / `+`).
210    pub fn glyph_ok(&self) -> &'static str {
211        if self.ascii {
212            "+"
213        } else {
214            "✓"
215        }
216    }
217    /// The failure mark (`✗` / `x`).
218    pub fn glyph_fail(&self) -> &'static str {
219        if self.ascii {
220            "x"
221        } else {
222            "✗"
223        }
224    }
225    /// The not-started mark (`•` / `.`).
226    pub fn glyph_pending(&self) -> &'static str {
227        if self.ascii {
228            "."
229        } else {
230            "•"
231        }
232    }
233    /// A filled radio / progress dot.
234    pub fn dot_filled(&self) -> &'static str {
235        if self.ascii {
236            "#"
237        } else {
238            "●"
239        }
240    }
241    /// An empty radio / progress dot.
242    pub fn dot_empty(&self) -> &'static str {
243        if self.ascii {
244            "."
245        } else {
246            "○"
247        }
248    }
249    /// A filled checkbox mark (checklist on).
250    pub fn box_checked(&self) -> &'static str {
251        if self.ascii {
252            "#"
253        } else {
254            "■"
255        }
256    }
257    /// An empty checkbox mark (checklist off).
258    pub fn box_unchecked(&self) -> &'static str {
259        if self.ascii {
260            "."
261        } else {
262            "□"
263        }
264    }
265
266    /// The box-drawing set (rounded Unicode, or ASCII).
267    pub fn box_chars(&self) -> BoxChars {
268        if self.ascii {
269            BoxChars {
270                tl: "+",
271                tr: "+",
272                bl: "+",
273                br: "+",
274                h: "-",
275                v: "|",
276            }
277        } else {
278            BoxChars {
279                tl: "╭",
280                tr: "╮",
281                bl: "╰",
282                br: "╯",
283                h: "─",
284                v: "│",
285            }
286        }
287    }
288}
289
290/// A truecolor foreground set.
291fn fg_rgb(rgb: Rgb) -> String {
292    format!("\x1b[38;2;{};{};{}m", rgb.0, rgb.1, rgb.2)
293}
294
295/// A truecolor background set.
296fn bg_rgb(rgb: Rgb) -> String {
297    format!("\x1b[48;2;{};{};{}m", rgb.0, rgb.1, rgb.2)
298}
299
300/// Pad `content` to `width` display columns with spaces, or clip it (with an
301/// ellipsis) when it overflows. `content` must be plain text.
302fn pad_or_clip(content: &str, width: usize) -> String {
303    let n = content.chars().count();
304    if n == width {
305        content.to_string()
306    } else if n < width {
307        format!("{content}{}", " ".repeat(width - n))
308    } else if width == 0 {
309        String::new()
310    } else {
311        let mut out: String = content.chars().take(width.saturating_sub(1)).collect();
312        out.push('…');
313        out
314    }
315}
316
317/// Resolve the color depth from the environment. `NO_COLOR` / `--no-color` and
318/// `TERM=dumb` force the plain tier; `COLORTERM=truecolor|24bit` selects
319/// truecolor; a `*-256color` `TERM` selects 256; anything else is basic.
320fn detect_tier(no_color: bool) -> ColorTier {
321    if no_color {
322        return ColorTier::None;
323    }
324    let term = std::env::var("TERM").unwrap_or_default();
325    if term == "dumb" {
326        return ColorTier::None;
327    }
328    let colorterm = std::env::var("COLORTERM")
329        .unwrap_or_default()
330        .to_lowercase();
331    if colorterm.contains("truecolor") || colorterm.contains("24bit") {
332        return ColorTier::Truecolor;
333    }
334    if term.contains("256color") {
335        return ColorTier::Ansi256;
336    }
337    ColorTier::Basic
338}
339
340/// True when the locale env vars indicate UTF-8 (or are unset — the modern
341/// default). A `C`/`POSIX` locale selects the ASCII tier.
342fn locale_is_utf8() -> bool {
343    // POSIX precedence: LC_ALL wins, then LC_CTYPE, then LANG. The first set,
344    // non-empty value decides; nothing set → assume a modern UTF-8 terminal.
345    for key in ["LC_ALL", "LC_CTYPE", "LANG"] {
346        if let Ok(v) = std::env::var(key) {
347            if v.is_empty() {
348                continue;
349            }
350            let v = v.to_ascii_lowercase();
351            return v.contains("utf-8") || v.contains("utf8");
352        }
353    }
354    true
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    fn plain() -> Theme {
362        Theme {
363            ascii: false,
364            tier: ColorTier::None,
365        }
366    }
367
368    #[test]
369    fn no_color_tier_emits_plain_text() {
370        let t = plain();
371        assert_eq!(t.ok("✓"), "✓");
372        assert_eq!(t.dim("x"), "x");
373        assert_eq!(t.accent("a"), "a");
374        assert_eq!(t.bold("b"), "b");
375        assert_eq!(t.heading("h"), "h");
376        assert_eq!(t.selection_bar("row", 3), "row");
377    }
378
379    #[test]
380    fn truecolor_amber_accent_uses_rgb_sgr() {
381        let t = Theme {
382            ascii: false,
383            tier: ColorTier::Truecolor,
384        };
385        let a = t.accent("x");
386        assert!(
387            a.contains("\x1b[38;2;235;193;87m"),
388            "amber rgb missing: {a:?}"
389        );
390        assert!(a.ends_with("\x1b[39m"), "fg not reset: {a:?}");
391        // Never a full reset that would clear the charcoal background.
392        assert!(!a.contains("\x1b[0m"), "must not full-reset: {a:?}");
393    }
394
395    #[test]
396    fn selection_bar_is_full_width_amber_with_dark_text() {
397        let t = Theme {
398            ascii: false,
399            tier: ColorTier::Truecolor,
400        };
401        let bar = t.selection_bar("● Drone", 20);
402        // Amber background + dark foreground, and the visible content padded.
403        assert!(
404            bar.contains("\x1b[48;2;235;193;87m"),
405            "amber bg missing: {bar:?}"
406        );
407        assert!(
408            bar.contains("\x1b[38;2;26;26;26m"),
409            "dark fg missing: {bar:?}"
410        );
411        // Restores the charcoal base so the row after it is not amber.
412        assert!(
413            bar.contains("\x1b[48;2;31;31;31m"),
414            "charcoal restore missing: {bar:?}"
415        );
416        assert_eq!(super::pad_or_clip("● Drone", 20).chars().count(), 20);
417    }
418
419    #[test]
420    fn background_prefix_only_on_painting_tiers() {
421        let tc = Theme {
422            ascii: false,
423            tier: ColorTier::Truecolor,
424        };
425        assert_eq!(tc.background_prefix(), "\x1b[48;2;31;31;31m");
426        assert!(tc.paints_background());
427        let basic = Theme {
428            ascii: false,
429            tier: ColorTier::Basic,
430        };
431        assert!(basic.background_prefix().is_empty());
432        assert!(!basic.paints_background());
433        assert!(plain().background_prefix().is_empty());
434    }
435
436    #[test]
437    fn ascii_tier_uses_ascii_glyphs() {
438        let t = Theme {
439            ascii: true,
440            tier: ColorTier::None,
441        };
442        assert_eq!(t.glyph_ok(), "+");
443        assert_eq!(t.glyph_fail(), "x");
444        assert_eq!(t.spinner(0), "-");
445        assert_eq!(t.box_chars().h, "-");
446        assert_eq!(t.dot_filled(), "#");
447        assert_eq!(t.box_checked(), "#");
448    }
449
450    #[test]
451    fn unicode_glyphs_are_single_column() {
452        let t = plain();
453        for g in [
454            t.glyph_ok(),
455            t.glyph_fail(),
456            t.glyph_pending(),
457            t.spinner(2),
458            t.dot_filled(),
459            t.dot_empty(),
460            t.box_checked(),
461            t.box_unchecked(),
462        ] {
463            assert_eq!(g.chars().count(), 1, "glyph {g:?} must be one column");
464        }
465    }
466}