Skip to main content

oomtop_cli/
ansi.rs

1//! Minimal SGR rendering of theme styles for `oomtop theme preview` (the TUI uses ratatui instead).
2//! Colors degrade truecolor → 256 → 16 → none exactly like the TUI (UX §12.1.5); `default` and missing
3//! colors emit nothing, so the terminal's own foreground/background show through.
4
5use oomtop_config::theme::{hex_rgb, Style};
6use oomtop_tui::style::ColorDepth;
7
8pub const RESET: &str = "\x1b[0m";
9
10const NAMES: &[&str] = &[
11    "black",
12    "red",
13    "green",
14    "yellow",
15    "blue",
16    "magenta",
17    "cyan",
18    "white",
19    "bright-black",
20    "bright-red",
21    "bright-green",
22    "bright-yellow",
23    "bright-blue",
24    "bright-magenta",
25    "bright-cyan",
26    "bright-white",
27];
28
29/// xterm's approximation of the 16 ANSI colors (used only to downsample hex colors).
30const ANSI16_RGB: [(u8, u8, u8); 16] = [
31    (0, 0, 0),
32    (205, 0, 0),
33    (0, 205, 0),
34    (205, 205, 0),
35    (0, 0, 238),
36    (205, 0, 205),
37    (0, 205, 205),
38    (229, 229, 229),
39    (127, 127, 127),
40    (255, 0, 0),
41    (0, 255, 0),
42    (255, 255, 0),
43    (92, 92, 255),
44    (255, 0, 255),
45    (0, 255, 255),
46    (255, 255, 255),
47];
48
49fn dist((r1, g1, b1): (u8, u8, u8), (r2, g2, b2): (u8, u8, u8)) -> u32 {
50    let d = |a: u8, b: u8| (a as i32 - b as i32).pow(2) as u32;
51    d(r1, r2) + d(g1, g2) + d(b1, b2)
52}
53
54/// Nearest xterm-256 index (6×6×6 cube or the 24-step gray ramp).
55pub fn rgb_to_256((r, g, b): (u8, u8, u8)) -> u8 {
56    const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
57    let idx = |v: u8| -> usize {
58        LEVELS
59            .iter()
60            .enumerate()
61            .min_by_key(|(_, l)| (**l as i32 - v as i32).abs())
62            .map(|(i, _)| i)
63            .unwrap_or(0)
64    };
65    let (ri, gi, bi) = (idx(r), idx(g), idx(b));
66    let cube = (LEVELS[ri], LEVELS[gi], LEVELS[bi]);
67    let cube_idx = 16 + 36 * ri + 6 * gi + bi;
68    let avg = ((r as u32 + g as u32 + b as u32) / 3) as u8;
69    let gi_ = ((avg.saturating_sub(8)) as u32 / 10).min(23) as u8;
70    let gray = 8 + 10 * gi_;
71    if dist((gray, gray, gray), (r, g, b)) < dist(cube, (r, g, b)) {
72        232 + gi_
73    } else {
74        cube_idx as u8
75    }
76}
77
78/// Nearest of the 16 ANSI colors.
79pub fn rgb_to_16(rgb: (u8, u8, u8)) -> u8 {
80    ANSI16_RGB
81        .iter()
82        .enumerate()
83        .min_by_key(|(_, c)| dist(**c, rgb))
84        .map(|(i, _)| i as u8)
85        .unwrap_or(7)
86}
87
88fn index_code(i: u8, bg: bool, depth: ColorDepth) -> Option<String> {
89    match (i, depth) {
90        (_, ColorDepth::None) => None,
91        (0..=7, _) => Some(format!("{}", if bg { 40 } else { 30 } + i as u32)),
92        (8..=15, _) => Some(format!("{}", if bg { 100 } else { 90 } + (i - 8) as u32)),
93        (_, ColorDepth::Ansi16) => None,
94        _ => Some(format!("{};5;{i}", if bg { 48 } else { 38 })),
95    }
96}
97
98/// SGR parameter(s) for one color, or `None` (terminal default / unsupported at this depth).
99pub fn color_code(c: &str, bg: bool, depth: ColorDepth) -> Option<String> {
100    if depth == ColorDepth::None || c == "default" || c.starts_with('@') {
101        return None;
102    }
103    if let Some(i) = NAMES.iter().position(|n| *n == c) {
104        return index_code(i as u8, bg, depth);
105    }
106    if let Ok(i) = c.parse::<u8>() {
107        return index_code(i, bg, depth);
108    }
109    let rgb = hex_rgb(c)?;
110    match depth {
111        ColorDepth::Truecolor => Some(format!(
112            "{};2;{};{};{}",
113            if bg { 48 } else { 38 },
114            rgb.0,
115            rgb.1,
116            rgb.2
117        )),
118        ColorDepth::Ansi256 => index_code(rgb_to_256(rgb), bg, depth),
119        ColorDepth::Ansi16 => index_code(rgb_to_16(rgb), bg, depth),
120        ColorDepth::None => None,
121    }
122}
123
124/// Full SGR start sequence for a style ("" when the style is plain). `paint_bg = false` drops backgrounds,
125/// as the default `terminal` theme and `appearance.background = "terminal"` require.
126pub fn sgr(style: &Style, depth: ColorDepth, paint_bg: bool) -> String {
127    let mut parts: Vec<String> = Vec::new();
128    for (on, code) in [
129        (style.bold, "1"),
130        (style.dim, "2"),
131        (style.italic, "3"),
132        (style.underline, "4"),
133        (style.reverse, "7"),
134    ] {
135        if on {
136            parts.push(code.into());
137        }
138    }
139    if let Some(c) = style.fg.as_deref().and_then(|c| color_code(c, false, depth)) {
140        parts.push(c);
141    }
142    if paint_bg {
143        if let Some(c) = style.bg.as_deref().and_then(|c| color_code(c, true, depth)) {
144            parts.push(c);
145        }
146    }
147    if parts.is_empty() {
148        String::new()
149    } else {
150        format!("\x1b[{}m", parts.join(";"))
151    }
152}
153
154/// `text` wrapped in the style (no escape codes at all for a plain style).
155pub fn paint(text: &str, style: &Style, depth: ColorDepth, paint_bg: bool) -> String {
156    let s = sgr(style, depth, paint_bg);
157    if s.is_empty() {
158        text.to_string()
159    } else {
160        format!("{s}{text}{RESET}")
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn names_indices_and_hex() {
170        assert_eq!(
171            color_code("yellow", false, ColorDepth::Ansi16).as_deref(),
172            Some("33")
173        );
174        assert_eq!(
175            color_code("bright-black", true, ColorDepth::Ansi16).as_deref(),
176            Some("100")
177        );
178        assert_eq!(
179            color_code("208", false, ColorDepth::Ansi256).as_deref(),
180            Some("38;5;208")
181        );
182        assert_eq!(color_code("208", false, ColorDepth::Ansi16), None);
183        assert_eq!(
184            color_code("#e07b39", false, ColorDepth::Truecolor).as_deref(),
185            Some("38;2;224;123;57")
186        );
187        assert_eq!(color_code("default", false, ColorDepth::Truecolor), None);
188        assert_eq!(color_code("yellow", false, ColorDepth::None), None);
189    }
190
191    #[test]
192    fn downsampling() {
193        assert_eq!(rgb_to_256((255, 0, 0)), 196);
194        assert_eq!(rgb_to_256((128, 128, 128)), 244);
195        assert_eq!(rgb_to_16((250, 250, 250)), 15);
196        assert_eq!(rgb_to_16((200, 10, 10)), 1);
197    }
198
199    #[test]
200    fn background_only_when_allowed() {
201        let st = Style {
202            fg: Some("green".into()),
203            bg: Some("black".into()),
204            bold: true,
205            ..Default::default()
206        };
207        assert_eq!(sgr(&st, ColorDepth::Ansi16, false), "\x1b[1;32m");
208        assert_eq!(sgr(&st, ColorDepth::Ansi16, true), "\x1b[1;32;40m");
209        assert_eq!(paint("x", &Style::default(), ColorDepth::Truecolor, true), "x");
210    }
211}