Skip to main content

tinyharness_ui/tui/
cell.rs

1// ── Color representation for the TUI screen buffer ──────────────────────────
2//
3// Supports 4-bit (16 colors), 8-bit (256 colors), and 24-bit (true color)
4// using raw ANSI escape sequences — no external TUI framework needed.
5
6/// Terminal color representation.
7///
8/// Supports the full range of terminal colors:
9/// - `Default`: use the terminal's default foreground/background
10/// - `Ansi(n)`: 4-bit (0–15) or 8-bit (16–255) indexed color
11/// - `Rgb(r, g, b)`: 24-bit true color
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum Color {
14    /// Terminal default color (inherits from terminal theme).
15    Default,
16    /// 4-bit (0–15) or 8-bit (16–255) indexed color.
17    Ansi(u8),
18    /// 24-bit true color.
19    Rgb(u8, u8, u8),
20}
21
22// ── Named color constants (matching style.rs ANSI codes) ───────────────────
23
24impl Color {
25    // Standard foreground colors (4-bit)
26    pub const BLACK: Color = Color::Ansi(0);
27    pub const RED: Color = Color::Ansi(1);
28    pub const GREEN: Color = Color::Ansi(2);
29    pub const YELLOW: Color = Color::Ansi(3);
30    pub const BLUE: Color = Color::Ansi(4);
31    pub const MAGENTA: Color = Color::Ansi(5);
32    pub const CYAN: Color = Color::Ansi(6);
33    pub const WHITE: Color = Color::Ansi(7);
34
35    // Bright / extended colors (matching style.rs)
36    pub const GRAY: Color = Color::Ansi(8); // bright black
37    pub const BRIGHT_RED: Color = Color::Ansi(9);
38    pub const BRIGHT_GREEN: Color = Color::Ansi(10);
39    pub const BRIGHT_YELLOW: Color = Color::Ansi(11);
40    pub const BRIGHT_BLUE: Color = Color::Ansi(12);
41    pub const BRIGHT_MAGENTA: Color = Color::Ansi(13);
42    pub const BRIGHT_CYAN: Color = Color::Ansi(14);
43    pub const BRIGHT_WHITE: Color = Color::Ansi(15);
44    pub const ORANGE: Color = Color::Ansi(208);
45
46    // Background colors (matching style.rs BG_* constants)
47    pub const BG_DIM: Color = Color::Ansi(236);
48    pub const BG_TOOL: Color = Color::Ansi(237);
49    pub const BG_WARN: Color = Color::Ansi(17);
50}
51
52impl Color {
53    /// Generate the ANSI escape sequence to set this color as the foreground.
54    pub fn fg_escape(&self) -> String {
55        match self {
56            Color::Default => "\x1b[39m".to_string(),
57            Color::Ansi(n) => {
58                if *n < 8 {
59                    // Standard colors: ESC[30–37m
60                    format!("\x1b[{}m", 30 + *n as u16)
61                } else if *n < 16 {
62                    // Bright colors: ESC[90–97m
63                    format!("\x1b[{}m", 90 + (*n - 8) as u16)
64                } else {
65                    // 8-bit colors: ESC[38;5;nm
66                    format!("\x1b[38;5;{}m", n)
67                }
68            }
69            Color::Rgb(r, g, b) => format!("\x1b[38;2;{r};{g};{b}m"),
70        }
71    }
72
73    /// Generate the ANSI escape sequence to set this color as the background.
74    pub fn bg_escape(&self) -> String {
75        match self {
76            Color::Default => "\x1b[49m".to_string(),
77            Color::Ansi(n) => {
78                if *n < 8 {
79                    // Standard background: ESC[40–47m
80                    format!("\x1b[{}m", 40 + *n as u16)
81                } else if *n < 16 {
82                    // Bright background: ESC[100–107m
83                    format!("\x1b[{}m", 100 + (*n - 8) as u16)
84                } else {
85                    // 8-bit background: ESC[48;5;nm
86                    format!("\x1b[48;5;{}m", n)
87                }
88            }
89            Color::Rgb(r, g, b) => format!("\x1b[48;2;{r};{g};{b}m"),
90        }
91    }
92}
93
94// ── Cell style flags ────────────────────────────────────────────────────────
95
96/// Text style attributes that can be combined.
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
98pub struct Style {
99    pub bold: bool,
100    pub dim: bool,
101    pub italic: bool,
102    pub underline: bool,
103    pub blink: bool,
104}
105
106impl Style {
107    pub fn new() -> Self {
108        Self::default()
109    }
110
111    pub fn bold() -> Self {
112        Self {
113            bold: true,
114            ..Self::default()
115        }
116    }
117
118    pub fn dim() -> Self {
119        Self {
120            dim: true,
121            ..Self::default()
122        }
123    }
124
125    pub fn bold_dim() -> Self {
126        Self {
127            bold: true,
128            dim: true,
129            ..Self::default()
130        }
131    }
132
133    pub fn blink() -> Self {
134        Self {
135            blink: true,
136            ..Self::default()
137        }
138    }
139
140    /// Generate the ANSI escape sequences for this style.
141    pub fn escape(&self) -> String {
142        let mut parts = Vec::new();
143        if self.bold {
144            parts.push("\x1b[1m");
145        }
146        if self.dim {
147            parts.push("\x1b[2m");
148        }
149        if self.italic {
150            parts.push("\x1b[3m");
151        }
152        if self.underline {
153            parts.push("\x1b[4m");
154        }
155        if self.blink {
156            parts.push("\x1b[5m");
157        }
158        parts.join("")
159    }
160
161    /// Generate the ANSI reset sequence to clear all styles.
162    pub fn reset() -> &'static str {
163        "\x1b[0m"
164    }
165}
166
167// ── Screen cell ─────────────────────────────────────────────────────────────
168
169/// A single cell in the screen buffer.
170///
171/// Each cell stores a character, foreground color, background color,
172/// and style flags. When the screen is rendered, only cells that changed
173/// from the previous frame are written to the terminal.
174///
175/// For wide (CJK/fullwidth) characters that occupy 2 columns, the first
176/// column holds the character and `wide` is false. The second column
177/// is a "continuation" cell with `wide = true`, which tells the renderer
178/// not to write it separately (the terminal already rendered it as part
179/// of the wide character).
180#[derive(Clone, Debug, PartialEq)]
181pub struct Cell {
182    pub char: char,
183    pub fg: Color,
184    pub bg: Color,
185    pub style: Style,
186    /// Whether this cell is the continuation (second column) of a wide
187    /// character. Continuation cells are skipped during rendering because
188    /// the terminal already drew them as part of the wide character.
189    pub wide: bool,
190}
191
192impl Default for Cell {
193    fn default() -> Self {
194        Cell {
195            char: ' ',
196            fg: Color::Default,
197            bg: Color::Default,
198            style: Style::default(),
199            wide: false,
200        }
201    }
202}
203
204impl Cell {
205    /// Create a cell with a character and default styling.
206    pub fn char(ch: char) -> Self {
207        Cell {
208            char: ch,
209            ..Self::default()
210        }
211    }
212
213    /// Create a styled cell.
214    pub fn styled(ch: char, fg: Color, bg: Color, style: Style) -> Self {
215        Cell {
216            char: ch,
217            fg,
218            bg,
219            style,
220            wide: false,
221        }
222    }
223
224    /// Create a continuation cell for a wide character's second column.
225    /// These cells are skipped during rendering since the terminal
226    /// already drew them as part of the wide character.
227    pub fn wide_continuation(fg: Color, bg: Color, style: Style) -> Self {
228        Cell {
229            char: ' ',
230            fg,
231            bg,
232            style,
233            wide: true,
234        }
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn test_color_fg_escape_default() {
244        assert_eq!(Color::Default.fg_escape(), "\x1b[39m");
245    }
246
247    #[test]
248    fn test_color_fg_escape_standard() {
249        // Standard colors 0-7 use ESC[30–37m
250        assert_eq!(Color::Ansi(0).fg_escape(), "\x1b[30m"); // black
251        assert_eq!(Color::Ansi(1).fg_escape(), "\x1b[31m"); // red
252        assert_eq!(Color::Ansi(7).fg_escape(), "\x1b[37m"); // white
253    }
254
255    #[test]
256    fn test_color_fg_escape_bright() {
257        // Bright colors 8-15 use ESC[90–97m
258        assert_eq!(Color::Ansi(8).fg_escape(), "\x1b[90m"); // bright black
259        assert_eq!(Color::Ansi(14).fg_escape(), "\x1b[96m"); // bright cyan
260    }
261
262    #[test]
263    fn test_color_fg_escape_256() {
264        // 8-bit colors use ESC[38;5;Nm
265        assert_eq!(Color::Ansi(208).fg_escape(), "\x1b[38;5;208m"); // orange
266        assert_eq!(Color::Ansi(236).fg_escape(), "\x1b[38;5;236m"); // bg_dim
267    }
268
269    #[test]
270    fn test_color_fg_escape_rgb() {
271        assert_eq!(Color::Rgb(255, 0, 128).fg_escape(), "\x1b[38;2;255;0;128m");
272    }
273
274    #[test]
275    fn test_color_bg_escape_default() {
276        assert_eq!(Color::Default.bg_escape(), "\x1b[49m");
277    }
278
279    #[test]
280    fn test_color_bg_escape_standard() {
281        assert_eq!(Color::Ansi(1).bg_escape(), "\x1b[41m"); // red bg
282    }
283
284    #[test]
285    fn test_color_bg_escape_bright() {
286        assert_eq!(Color::Ansi(8).bg_escape(), "\x1b[100m"); // bright black bg
287    }
288
289    #[test]
290    fn test_color_bg_escape_256() {
291        assert_eq!(Color::Ansi(237).bg_escape(), "\x1b[48;5;237m");
292    }
293
294    #[test]
295    fn test_color_bg_escape_rgb() {
296        assert_eq!(Color::Rgb(10, 20, 30).bg_escape(), "\x1b[48;2;10;20;30m");
297    }
298
299    #[test]
300    fn test_style_escape() {
301        let s = Style {
302            bold: true,
303            dim: false,
304            italic: true,
305            underline: false,
306            blink: false,
307        };
308        assert_eq!(s.escape(), "\x1b[1m\x1b[3m");
309    }
310
311    #[test]
312    fn test_style_default_is_empty() {
313        let s = Style::default();
314        assert_eq!(s.escape(), "");
315    }
316
317    #[test]
318    fn test_cell_default() {
319        let c = Cell::default();
320        assert_eq!(c.char, ' ');
321        assert_eq!(c.fg, Color::Default);
322        assert_eq!(c.bg, Color::Default);
323    }
324
325    #[test]
326    fn test_cell_char() {
327        let c = Cell::char('X');
328        assert_eq!(c.char, 'X');
329        assert_eq!(c.fg, Color::Default);
330    }
331
332    #[test]
333    fn test_cell_styled() {
334        let c = Cell::styled('A', Color::RED, Color::BLUE, Style::bold());
335        assert_eq!(c.char, 'A');
336        assert_eq!(c.fg, Color::Ansi(1));
337        assert_eq!(c.bg, Color::Ansi(4));
338        assert!(c.style.bold);
339    }
340}