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#[derive(Clone, Debug, PartialEq)]
175pub struct Cell {
176    pub char: char,
177    pub fg: Color,
178    pub bg: Color,
179    pub style: Style,
180}
181
182impl Default for Cell {
183    fn default() -> Self {
184        Cell {
185            char: ' ',
186            fg: Color::Default,
187            bg: Color::Default,
188            style: Style::default(),
189        }
190    }
191}
192
193impl Cell {
194    /// Create a cell with a character and default styling.
195    pub fn char(ch: char) -> Self {
196        Cell {
197            char: ch,
198            ..Self::default()
199        }
200    }
201
202    /// Create a styled cell.
203    pub fn styled(ch: char, fg: Color, bg: Color, style: Style) -> Self {
204        Cell {
205            char: ch,
206            fg,
207            bg,
208            style,
209        }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn test_color_fg_escape_default() {
219        assert_eq!(Color::Default.fg_escape(), "\x1b[39m");
220    }
221
222    #[test]
223    fn test_color_fg_escape_standard() {
224        // Standard colors 0-7 use ESC[30–37m
225        assert_eq!(Color::Ansi(0).fg_escape(), "\x1b[30m"); // black
226        assert_eq!(Color::Ansi(1).fg_escape(), "\x1b[31m"); // red
227        assert_eq!(Color::Ansi(7).fg_escape(), "\x1b[37m"); // white
228    }
229
230    #[test]
231    fn test_color_fg_escape_bright() {
232        // Bright colors 8-15 use ESC[90–97m
233        assert_eq!(Color::Ansi(8).fg_escape(), "\x1b[90m"); // bright black
234        assert_eq!(Color::Ansi(14).fg_escape(), "\x1b[96m"); // bright cyan
235    }
236
237    #[test]
238    fn test_color_fg_escape_256() {
239        // 8-bit colors use ESC[38;5;Nm
240        assert_eq!(Color::Ansi(208).fg_escape(), "\x1b[38;5;208m"); // orange
241        assert_eq!(Color::Ansi(236).fg_escape(), "\x1b[38;5;236m"); // bg_dim
242    }
243
244    #[test]
245    fn test_color_fg_escape_rgb() {
246        assert_eq!(Color::Rgb(255, 0, 128).fg_escape(), "\x1b[38;2;255;0;128m");
247    }
248
249    #[test]
250    fn test_color_bg_escape_default() {
251        assert_eq!(Color::Default.bg_escape(), "\x1b[49m");
252    }
253
254    #[test]
255    fn test_color_bg_escape_standard() {
256        assert_eq!(Color::Ansi(1).bg_escape(), "\x1b[41m"); // red bg
257    }
258
259    #[test]
260    fn test_color_bg_escape_bright() {
261        assert_eq!(Color::Ansi(8).bg_escape(), "\x1b[100m"); // bright black bg
262    }
263
264    #[test]
265    fn test_color_bg_escape_256() {
266        assert_eq!(Color::Ansi(237).bg_escape(), "\x1b[48;5;237m");
267    }
268
269    #[test]
270    fn test_color_bg_escape_rgb() {
271        assert_eq!(Color::Rgb(10, 20, 30).bg_escape(), "\x1b[48;2;10;20;30m");
272    }
273
274    #[test]
275    fn test_style_escape() {
276        let s = Style {
277            bold: true,
278            dim: false,
279            italic: true,
280            underline: false,
281            blink: false,
282        };
283        assert_eq!(s.escape(), "\x1b[1m\x1b[3m");
284    }
285
286    #[test]
287    fn test_style_default_is_empty() {
288        let s = Style::default();
289        assert_eq!(s.escape(), "");
290    }
291
292    #[test]
293    fn test_cell_default() {
294        let c = Cell::default();
295        assert_eq!(c.char, ' ');
296        assert_eq!(c.fg, Color::Default);
297        assert_eq!(c.bg, Color::Default);
298    }
299
300    #[test]
301    fn test_cell_char() {
302        let c = Cell::char('X');
303        assert_eq!(c.char, 'X');
304        assert_eq!(c.fg, Color::Default);
305    }
306
307    #[test]
308    fn test_cell_styled() {
309        let c = Cell::styled('A', Color::RED, Color::BLUE, Style::bold());
310        assert_eq!(c.char, 'A');
311        assert_eq!(c.fg, Color::Ansi(1));
312        assert_eq!(c.bg, Color::Ansi(4));
313        assert!(c.style.bold);
314    }
315}