Skip to main content

tinyharness_ui/tui/
screen.rs

1// ── Double-buffered screen ───────────────────────────────────────────────────
2//
3// The screen is a 2D grid of cells. Each frame, we compute a new grid and
4// diff it against the previous frame. Only changed cells are written to
5// the terminal, achieving flicker-free rendering.
6
7use std::fmt;
8
9use super::cell::{Cell, Color, Style};
10use super::layout::Rect;
11
12// ── Screen ──────────────────────────────────────────────────────────────────
13
14/// A double-buffered screen of cells.
15///
16/// The screen tracks the current state of every cell. When rendering,
17/// the diff from the previous frame determines which cells need updating.
18/// This avoids redrawing the entire screen on every frame.
19pub struct Screen {
20    width: u16,
21    height: u16,
22    cells: Vec<Cell>,
23}
24
25impl Screen {
26    /// Create a new screen with the given dimensions, filled with default cells.
27    pub fn new(width: u16, height: u16) -> Self {
28        let cells = vec![Cell::default(); (width as usize) * (height as usize)];
29        Screen {
30            width,
31            height,
32            cells,
33        }
34    }
35
36    /// Resize the screen, clearing all content.
37    pub fn resize(&mut self, width: u16, height: u16) {
38        self.width = width;
39        self.height = height;
40        self.cells = vec![Cell::default(); (width as usize) * (height as usize)];
41    }
42
43    /// Clear the entire screen to default cells.
44    pub fn clear(&mut self) {
45        self.cells.fill(Cell::default());
46    }
47
48    /// Get the screen width in columns.
49    pub fn width(&self) -> u16 {
50        self.width
51    }
52
53    /// Get the screen height in rows.
54    pub fn height(&self) -> u16 {
55        self.height
56    }
57
58    /// Get a cell at the given position. Returns `None` if out of bounds.
59    pub fn get(&self, row: u16, col: u16) -> Option<&Cell> {
60        if row >= self.height || col >= self.width {
61            return None;
62        }
63        self.cells
64            .get((row as usize) * (self.width as usize) + (col as usize))
65    }
66
67    /// Get a mutable cell at the given position. Returns `None` if out of bounds.
68    pub fn get_mut(&mut self, row: u16, col: u16) -> Option<&mut Cell> {
69        if row >= self.height || col >= self.width {
70            return None;
71        }
72        let idx = (row as usize) * (self.width as usize) + (col as usize);
73        self.cells.get_mut(idx)
74    }
75
76    /// Set a cell at the given position. Does nothing if out of bounds.
77    pub fn set_cell(&mut self, row: u16, col: u16, cell: Cell) {
78        if let Some(c) = self.get_mut(row, col) {
79            *c = cell;
80        }
81    }
82
83    /// Write a string starting at the given position, with the given style.
84    ///
85    /// Characters that exceed the screen width are truncated.
86    pub fn write_str(
87        &mut self,
88        row: u16,
89        col: u16,
90        text: &str,
91        fg: Color,
92        bg: Color,
93        style: Style,
94    ) {
95        let mut c = col;
96        for ch in text.chars() {
97            if c >= self.width {
98                break;
99            }
100            self.set_cell(
101                row,
102                c,
103                Cell {
104                    char: ch,
105                    fg,
106                    bg,
107                    style,
108                },
109            );
110            c += 1;
111        }
112    }
113
114    /// Write a string starting at the given position, truncating or wrapping.
115    ///
116    /// If `wrap` is true, text wraps to the next line. If false, text is
117    /// truncated at the right edge.
118    pub fn write_str_wrapped(
119        &mut self,
120        start_row: u16,
121        start_col: u16,
122        text: &str,
123        fg: Color,
124        bg: Color,
125        style: Style,
126        wrap: bool,
127    ) -> u16 {
128        let mut row = start_row;
129        let mut col = start_col;
130
131        for ch in text.chars() {
132            if col >= self.width {
133                if wrap && row + 1 < self.height {
134                    row += 1;
135                    col = 0;
136                } else {
137                    break;
138                }
139            }
140            if ch == '\n' {
141                row += 1;
142                col = 0;
143                continue;
144            }
145            self.set_cell(
146                row,
147                col,
148                Cell {
149                    char: ch,
150                    fg,
151                    bg,
152                    style,
153                },
154            );
155            col += 1;
156        }
157
158        row
159    }
160
161    /// Write a string with wrapping, but clip rendering at the given maximum row
162    /// and wrap at the given column.
163    ///
164    /// `wrap_col` is the maximum column number; text wraps when `col >= wrap_col`.
165    /// `max_row` is the maximum row; text stops when `row > max_row`.
166    /// `left_margin` is the column where wrapped lines start.
167    pub fn write_str_wrapped_clipped(
168        &mut self,
169        start_row: u16,
170        start_col: u16,
171        text: &str,
172        fg: Color,
173        bg: Color,
174        style: Style,
175        left_margin: u16,
176        max_row: u16,
177        wrap_col: u16,
178    ) -> u16 {
179        let mut row = start_row;
180        let mut col = start_col;
181
182        for ch in text.chars() {
183            if col >= wrap_col {
184                // Wrap to next line
185                row += 1;
186                col = left_margin;
187            }
188            // Stop if we've exceeded the max row
189            if row > max_row {
190                break;
191            }
192            if ch == '\n' {
193                row += 1;
194                col = left_margin;
195                if row > max_row {
196                    break;
197                }
198                continue;
199            }
200            self.set_cell(
201                row,
202                col,
203                Cell {
204                    char: ch,
205                    fg,
206                    bg,
207                    style,
208                },
209            );
210            col += 1;
211        }
212
213        row
214    }
215
216    /// Write a string with wrapping, skip the first `skip_rows` visual rows,
217    /// and clip rendering at the given maximum row and wrap column.
218    ///
219    /// `wrap_col` is the maximum column number; text wraps when `col >= wrap_col`.
220    /// `skip_rows` is the number of visual rows to skip before rendering.
221    /// `max_row` is the maximum row; text stops when `row > max_row`.
222    /// `left_margin` is the column where wrapped lines start.
223    pub fn write_str_wrapped_skip_clipped(
224        &mut self,
225        start_row: u16,
226        start_col: u16,
227        text: &str,
228        fg: Color,
229        bg: Color,
230        style: Style,
231        left_margin: u16,
232        max_row: u16,
233        wrap_col: u16,
234        skip_rows: usize,
235    ) {
236        let mut visual_row: usize = 0;
237        let mut col = start_col;
238        let mut screen_row = start_row;
239
240        for ch in text.chars() {
241            // Check if we need to wrap before placing this character
242            if ch != '\n' && col >= wrap_col {
243                // Wrap to next visual line
244                visual_row += 1;
245                col = left_margin;
246                // Only advance screen_row if we're past the renderable zone
247                if visual_row > skip_rows {
248                    screen_row += 1;
249                }
250                if screen_row > max_row {
251                    break;
252                }
253            }
254
255            if ch == '\n' {
256                // Newline — advance to next visual row
257                visual_row += 1;
258                col = left_margin;
259                if visual_row > skip_rows {
260                    screen_row += 1;
261                }
262                if screen_row > max_row {
263                    break;
264                }
265                continue;
266            }
267
268            // Only write the cell if we're past the skip zone
269            if visual_row >= skip_rows && screen_row <= max_row {
270                self.set_cell(
271                    screen_row,
272                    col,
273                    Cell {
274                        char: ch,
275                        fg,
276                        bg,
277                        style,
278                    },
279                );
280            }
281
282            col += 1;
283        }
284    }
285
286    /// Fill a rectangular area with the given cell.
287    pub fn fill_rect(&mut self, rect: Rect, cell: Cell) {
288        for row in rect.y..rect.y + rect.height {
289            for col in rect.x..rect.x + rect.width {
290                if row < self.height && col < self.width {
291                    self.set_cell(row, col, cell.clone());
292                }
293            }
294        }
295    }
296
297    /// Draw a horizontal line using the given character.
298    pub fn hline(
299        &mut self,
300        row: u16,
301        col_start: u16,
302        col_end: u16,
303        ch: char,
304        fg: Color,
305        bg: Color,
306    ) {
307        for col in col_start..=col_end.min(self.width.saturating_sub(1)) {
308            self.set_cell(
309                row,
310                col,
311                Cell {
312                    char: ch,
313                    fg,
314                    bg,
315                    style: Style::default(),
316                },
317            );
318        }
319    }
320
321    /// Draw a vertical line using the given character.
322    pub fn vline(
323        &mut self,
324        col: u16,
325        row_start: u16,
326        row_end: u16,
327        ch: char,
328        fg: Color,
329        bg: Color,
330    ) {
331        for row in row_start..=row_end.min(self.height.saturating_sub(1)) {
332            self.set_cell(
333                row,
334                col,
335                Cell {
336                    char: ch,
337                    fg,
338                    bg,
339                    style: Style::default(),
340                },
341            );
342        }
343    }
344
345    /// Draw a box (border) around a rectangular area.
346    pub fn draw_box(&mut self, rect: Rect, fg: Color, bg: Color, style: Style) {
347        let x = rect.x;
348        let y = rect.y;
349        let w = rect.width;
350        let h = rect.height;
351
352        if w < 2 || h < 2 {
353            return;
354        }
355
356        // Corners
357        self.set_cell(
358            y,
359            x,
360            Cell {
361                char: '┌',
362                fg,
363                bg,
364                style,
365            },
366        );
367        self.set_cell(
368            y,
369            x + w - 1,
370            Cell {
371                char: '┐',
372                fg,
373                bg,
374                style,
375            },
376        );
377        self.set_cell(
378            y + h - 1,
379            x,
380            Cell {
381                char: '└',
382                fg,
383                bg,
384                style,
385            },
386        );
387        self.set_cell(
388            y + h - 1,
389            x + w - 1,
390            Cell {
391                char: '┘',
392                fg,
393                bg,
394                style,
395            },
396        );
397
398        // Top and bottom borders
399        for col in (x + 1)..(x + w - 1) {
400            self.set_cell(
401                y,
402                col,
403                Cell {
404                    char: '─',
405                    fg,
406                    bg,
407                    style,
408                },
409            );
410            self.set_cell(
411                y + h - 1,
412                col,
413                Cell {
414                    char: '─',
415                    fg,
416                    bg,
417                    style,
418                },
419            );
420        }
421
422        // Left and right borders
423        for row in (y + 1)..(y + h - 1) {
424            self.set_cell(
425                row,
426                x,
427                Cell {
428                    char: '│',
429                    fg,
430                    bg,
431                    style,
432                },
433            );
434            self.set_cell(
435                row,
436                x + w - 1,
437                Cell {
438                    char: '│',
439                    fg,
440                    bg,
441                    style,
442                },
443            );
444        }
445    }
446
447    // ── Diff-based rendering ────────────────────────────────────────────
448
449    /// Compute the diff between this screen and a previous frame.
450    ///
451    /// Returns a list of `DiffOp` entries that, when applied in order,
452    /// will bring the terminal from the previous state to the current state.
453    pub fn diff_from(&self, previous: &Screen) -> Vec<DiffOp> {
454        let mut ops = Vec::new();
455        let max_row = self.height.min(previous.height);
456        let max_col = self.width.min(previous.width);
457
458        for row in 0..max_row {
459            for col in 0..max_col {
460                let prev_cell = previous.get(row, col);
461                let curr_cell = self.get(row, col);
462
463                match (prev_cell, curr_cell) {
464                    (Some(prev), Some(curr)) if prev != curr => {
465                        ops.push(DiffOp::SetCell {
466                            row,
467                            col,
468                            cell: curr.clone(),
469                        });
470                    }
471                    (None, Some(curr)) => {
472                        ops.push(DiffOp::SetCell {
473                            row,
474                            col,
475                            cell: curr.clone(),
476                        });
477                    }
478                    _ => {}
479                }
480            }
481        }
482
483        // Handle rows that exist in the new screen but not the old one
484        for row in previous.height..self.height {
485            for col in 0..self.width {
486                if let Some(cell) = self.get(row, col) {
487                    ops.push(DiffOp::SetCell {
488                        row,
489                        col,
490                        cell: cell.clone(),
491                    });
492                }
493            }
494        }
495
496        ops
497    }
498
499    /// Render a list of diff operations to an ANSI escape sequence string.
500    ///
501    /// This is the core of the efficient rendering: we only write cells
502    /// that actually changed, and we batch cursor movements.
503    pub fn render_diff(ops: &[DiffOp], width: u16) -> String {
504        if ops.is_empty() {
505            return String::new();
506        }
507
508        let mut output = String::with_capacity(ops.len() * 20);
509        let mut last_row: Option<u16> = None;
510        let mut last_col: Option<u16> = None;
511
512        for op in ops {
513            match op {
514                DiffOp::SetCell { row, col, cell } => {
515                    // Move cursor if needed
516                    let need_move = last_row != Some(*row) || last_col.unwrap_or(0) + 1 != *col;
517
518                    if need_move {
519                        output.push_str(&format!("\x1b[{};{}H", row + 1, col + 1));
520                    }
521
522                    // Apply style
523                    output.push_str(&cell.style.escape());
524                    // Apply foreground color
525                    output.push_str(&cell.fg.fg_escape());
526                    // Apply background color
527                    output.push_str(&cell.bg.bg_escape());
528                    // Write character
529                    output.push(cell.char);
530
531                    last_row = Some(*row);
532                    last_col = Some(*col + 1);
533
534                    // If we're at the right edge, the cursor won't advance
535                    // further, so we need to move it explicitly next time
536                    if *col + 1 >= width {
537                        last_col = None;
538                    }
539                }
540            }
541        }
542
543        // Reset all styles at the end
544        output.push_str(Style::reset());
545
546        output
547    }
548}
549
550impl Clone for Screen {
551    fn clone(&self) -> Self {
552        Screen {
553            width: self.width,
554            height: self.height,
555            cells: self.cells.clone(),
556        }
557    }
558}
559
560impl fmt::Debug for Screen {
561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562        f.debug_struct("Screen")
563            .field("width", &self.width)
564            .field("height", &self.height)
565            .finish()
566    }
567}
568
569// ── Diff operation ───────────────────────────────────────────────────────────
570
571/// A single rendering operation produced by diffing two screens.
572#[derive(Clone, Debug, PartialEq)]
573pub enum DiffOp {
574    /// Set the cell at (row, col) to the given value.
575    SetCell { row: u16, col: u16, cell: Cell },
576}
577
578#[cfg(test)]
579mod tests {
580    use super::*;
581
582    #[test]
583    fn test_screen_new() {
584        let s = Screen::new(10, 5);
585        assert_eq!(s.width(), 10);
586        assert_eq!(s.height(), 5);
587        // All cells should be default (space)
588        assert_eq!(s.get(0, 0).unwrap().char, ' ');
589    }
590
591    #[test]
592    fn test_screen_set_get_cell() {
593        let mut s = Screen::new(10, 5);
594        let cell = Cell::styled('X', Color::RED, Color::Default, Style::bold());
595        s.set_cell(2, 3, cell.clone());
596        assert_eq!(s.get(2, 3).unwrap(), &cell);
597    }
598
599    #[test]
600    fn test_screen_out_of_bounds() {
601        let s = Screen::new(10, 5);
602        assert!(s.get(5, 0).is_none());
603        assert!(s.get(0, 10).is_none());
604    }
605
606    #[test]
607    fn test_screen_write_str() {
608        let mut s = Screen::new(20, 5);
609        s.write_str(1, 2, "Hello", Color::GREEN, Color::Default, Style::new());
610        assert_eq!(s.get(1, 2).unwrap().char, 'H');
611        assert_eq!(s.get(1, 3).unwrap().char, 'e');
612        assert_eq!(s.get(1, 6).unwrap().char, 'o');
613        assert_eq!(s.get(1, 7).unwrap().char, ' '); // default
614    }
615
616    #[test]
617    fn test_screen_write_str_truncates() {
618        let mut s = Screen::new(5, 1);
619        s.write_str(
620            0,
621            0,
622            "Hello World",
623            Color::Default,
624            Color::Default,
625            Style::new(),
626        );
627        assert_eq!(s.get(0, 4).unwrap().char, 'o'); // 5th char (index 4)
628        // "World" should be truncated
629    }
630
631    #[test]
632    fn test_screen_clear() {
633        let mut s = Screen::new(10, 5);
634        s.set_cell(0, 0, Cell::char('X'));
635        s.clear();
636        assert_eq!(s.get(0, 0).unwrap().char, ' ');
637    }
638
639    #[test]
640    fn test_screen_resize() {
641        let mut s = Screen::new(10, 5);
642        s.set_cell(0, 0, Cell::char('X'));
643        s.resize(20, 10);
644        assert_eq!(s.width(), 20);
645        assert_eq!(s.height(), 10);
646        // Old content should be gone
647        assert_eq!(s.get(0, 0).unwrap().char, ' ');
648    }
649
650    #[test]
651    fn test_screen_draw_box() {
652        let mut s = Screen::new(10, 5);
653        s.draw_box(
654            Rect {
655                x: 0,
656                y: 0,
657                width: 10,
658                height: 5,
659            },
660            Color::BLUE,
661            Color::Default,
662            Style::default(),
663        );
664        assert_eq!(s.get(0, 0).unwrap().char, '┌');
665        assert_eq!(s.get(0, 9).unwrap().char, '┐');
666        assert_eq!(s.get(4, 0).unwrap().char, '└');
667        assert_eq!(s.get(4, 9).unwrap().char, '┘');
668        assert_eq!(s.get(0, 5).unwrap().char, '─');
669        assert_eq!(s.get(2, 0).unwrap().char, '│');
670    }
671
672    #[test]
673    fn test_screen_diff_no_changes() {
674        let s1 = Screen::new(10, 5);
675        let s2 = Screen::new(10, 5);
676        let diff = s2.diff_from(&s1);
677        assert!(diff.is_empty());
678    }
679
680    #[test]
681    fn test_screen_diff_with_changes() {
682        let s1 = Screen::new(10, 5);
683        let mut s2 = Screen::new(10, 5);
684        s2.set_cell(1, 2, Cell::char('X'));
685        s2.set_cell(3, 4, Cell::char('Y'));
686
687        let diff = s2.diff_from(&s1);
688        assert_eq!(diff.len(), 2);
689    }
690
691    #[test]
692    fn test_screen_render_diff() {
693        let s1 = Screen::new(10, 5);
694        let mut s2 = Screen::new(10, 5);
695        s2.set_cell(
696            0,
697            0,
698            Cell::styled('A', Color::RED, Color::Default, Style::bold()),
699        );
700
701        let diff = s2.diff_from(&s1);
702        let rendered = Screen::render_diff(&diff, 10);
703
704        // Should contain cursor movement and the character
705        assert!(rendered.contains("\x1b[1;1H")); // move to (1,1)
706        assert!(rendered.contains('A'));
707        assert!(rendered.contains("\x1b[0m")); // reset at end
708    }
709
710    #[test]
711    fn test_screen_hline() {
712        let mut s = Screen::new(10, 5);
713        s.hline(2, 1, 8, '─', Color::Default, Color::Default);
714        assert_eq!(s.get(2, 1).unwrap().char, '─');
715        assert_eq!(s.get(2, 8).unwrap().char, '─');
716        assert_eq!(s.get(2, 0).unwrap().char, ' '); // before line
717    }
718
719    #[test]
720    fn test_screen_vline() {
721        let mut s = Screen::new(10, 5);
722        s.vline(5, 1, 3, '│', Color::Default, Color::Default);
723        assert_eq!(s.get(1, 5).unwrap().char, '│');
724        assert_eq!(s.get(2, 5).unwrap().char, '│');
725        assert_eq!(s.get(3, 5).unwrap().char, '│');
726        assert_eq!(s.get(0, 5).unwrap().char, ' '); // before line
727    }
728
729    #[test]
730    fn test_screen_fill_rect() {
731        let mut s = Screen::new(10, 5);
732        let rect = Rect {
733            x: 2,
734            y: 1,
735            width: 3,
736            height: 2,
737        };
738        s.fill_rect(rect, Cell::char('█'));
739
740        assert_eq!(s.get(1, 2).unwrap().char, '█');
741        assert_eq!(s.get(1, 4).unwrap().char, '█');
742        assert_eq!(s.get(2, 2).unwrap().char, '█');
743        assert_eq!(s.get(0, 2).unwrap().char, ' '); // outside rect
744    }
745
746    #[test]
747    fn test_screen_write_str_wrapped() {
748        let mut s = Screen::new(5, 5);
749        let end_row = s.write_str_wrapped(
750            0,
751            0,
752            "ABCDEFGH",
753            Color::Default,
754            Color::Default,
755            Style::new(),
756            true,
757        );
758        // "ABCDE" on row 0, "FGH" on row 1
759        assert_eq!(s.get(0, 0).unwrap().char, 'A');
760        assert_eq!(s.get(0, 4).unwrap().char, 'E');
761        assert_eq!(s.get(1, 0).unwrap().char, 'F');
762        assert_eq!(s.get(1, 2).unwrap().char, 'H');
763        assert_eq!(end_row, 1);
764    }
765
766    #[test]
767    fn test_screen_write_str_wrapped_skip_clipped() {
768        let mut s = Screen::new(5, 5);
769        // "ABCDE" on row 0, "FGH" on row 1
770        // Skip the first row, render only "FGH" starting at screen row 0
771        s.write_str_wrapped_skip_clipped(
772            0,
773            0,
774            "ABCDEFGH",
775            Color::Default,
776            Color::Default,
777            Style::new(),
778            0,
779            4,
780            5, // wrap_col
781            1, // skip 1 row
782        );
783        // Row 0 should have "FGH" (the 2nd visual row of the text)
784        assert_eq!(s.get(0, 0).unwrap().char, 'F');
785        assert_eq!(s.get(0, 2).unwrap().char, 'H');
786        // Row 1 should be empty (default)
787        assert_eq!(s.get(1, 0).unwrap().char, ' ');
788    }
789
790    #[test]
791    fn test_screen_write_str_wrapped_skip_clipped_newlines() {
792        let mut s = Screen::new(5, 5);
793        // "AB\nCD" → row 0: "AB", row 1: "CD"
794        // Skip 1 row, render "CD" starting at screen row 0
795        s.write_str_wrapped_skip_clipped(
796            0,
797            0,
798            "AB\nCD",
799            Color::Default,
800            Color::Default,
801            Style::new(),
802            0,
803            4,
804            5,
805            1,
806        );
807        assert_eq!(s.get(0, 0).unwrap().char, 'C');
808        assert_eq!(s.get(0, 1).unwrap().char, 'D');
809    }
810}