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 unicode_width::UnicodeWidthChar;
10
11use super::cell::{Cell, Color, Style};
12use super::layout::Rect;
13
14// ── Wrap configuration ────────────────────────────────────────────────────────
15
16/// Configuration for wrapped text rendering.
17///
18/// Controls wrapping, clipping, and skipping behavior for the
19/// [`Screen::write_wrapped`] method.
20struct WrapConfig {
21    /// Maximum column number; text wraps when `col + char_width > wrap_col`.
22    wrap_col: u16,
23    /// Column where wrapped lines start (left margin for continuation lines).
24    left_margin: u16,
25    /// Maximum screen row; text stops when `screen_row > max_row`.
26    max_row: u16,
27    /// Number of visual rows to skip before rendering (for scroll offset).
28    skip_rows: usize,
29    /// If true, don't wrap — truncate at `wrap_col` instead.
30    no_wrap: bool,
31    /// If true, use screen-bounded wrapping (old `write_str_wrapped` semantics):
32    /// wraps at screen width and clips at screen height.
33    screen_bounded: bool,
34}
35
36// ── Screen ──────────────────────────────────────────────────────────────────
37
38/// A double-buffered screen of cells.
39///
40/// The screen tracks the current state of every cell. When rendering,
41/// the diff from the previous frame determines which cells need updating.
42/// This avoids redrawing the entire screen on every frame.
43pub struct Screen {
44    width: u16,
45    height: u16,
46    cells: Vec<Cell>,
47}
48
49impl Screen {
50    /// Create a new screen with the given dimensions, filled with default cells.
51    pub fn new(width: u16, height: u16) -> Self {
52        let cells = vec![Cell::default(); (width as usize) * (height as usize)];
53        Screen {
54            width,
55            height,
56            cells,
57        }
58    }
59
60    /// Resize the screen, clearing all content.
61    pub fn resize(&mut self, width: u16, height: u16) {
62        self.width = width;
63        self.height = height;
64        self.cells = vec![Cell::default(); (width as usize) * (height as usize)];
65    }
66
67    /// Clear the entire screen to default cells.
68    pub fn clear(&mut self) {
69        self.cells.fill(Cell::default());
70    }
71
72    /// Get the screen width in columns.
73    pub fn width(&self) -> u16 {
74        self.width
75    }
76
77    /// Get the screen height in rows.
78    pub fn height(&self) -> u16 {
79        self.height
80    }
81
82    /// Get a cell at the given position. Returns `None` if out of bounds.
83    pub fn get(&self, row: u16, col: u16) -> Option<&Cell> {
84        if row >= self.height || col >= self.width {
85            return None;
86        }
87        self.cells
88            .get((row as usize) * (self.width as usize) + (col as usize))
89    }
90
91    /// Get a mutable cell at the given position. Returns `None` if out of bounds.
92    pub fn get_mut(&mut self, row: u16, col: u16) -> Option<&mut Cell> {
93        if row >= self.height || col >= self.width {
94            return None;
95        }
96        let idx = (row as usize) * (self.width as usize) + (col as usize);
97        self.cells.get_mut(idx)
98    }
99
100    /// Set a cell at the given position. Does nothing if out of bounds.
101    pub fn set_cell(&mut self, row: u16, col: u16, cell: Cell) {
102        if let Some(c) = self.get_mut(row, col) {
103            *c = cell;
104        }
105    }
106
107    /// Merge a zero-width combining mark into the previous cell.
108    ///
109    /// Does nothing if `col` is at the start of the current rendering run
110    /// or if `in_view` is false. If the preceding cell is a wide-character
111    /// continuation cell, the mark is merged into the wide character's
112    /// primary cell (two columns back) instead, since continuation cells
113    /// are skipped during rendering.
114    fn merge_combining_mark(
115        &mut self,
116        row: u16,
117        col: u16,
118        start_col: u16,
119        ch: char,
120        fg: Color,
121        bg: Color,
122        style: Style,
123        in_view: bool,
124    ) {
125        if !in_view || col <= start_col {
126            return;
127        }
128        // If the immediately preceding cell is a wide continuation cell,
129        // the actual character is one column further back.
130        let target_col = if let Some(prev) = self.get(row, col - 1) {
131            if prev.wide && col >= 2 {
132                col - 2
133            } else {
134                col - 1
135            }
136        } else {
137            col - 1
138        };
139        if target_col < start_col {
140            return;
141        }
142        if let Some(prev) = self.get_mut(row, target_col) {
143            prev.char = ch;
144            prev.fg = fg;
145            prev.bg = bg;
146            prev.style = style;
147        }
148    }
149
150    /// Write a string starting at the given position, with the given style.
151    ///
152    /// Characters that exceed the screen width are truncated. Each character
153    /// is placed according to its Unicode display width; zero-width chars
154    /// (e.g. combining marks) overwrite the previous cell. Wide (CJK/
155    /// fullwidth) characters that occupy 2 columns get a continuation
156    /// cell marked at `col+1` so the renderer can skip it.
157    pub fn write_str(
158        &mut self,
159        row: u16,
160        col: u16,
161        text: &str,
162        fg: Color,
163        bg: Color,
164        style: Style,
165    ) {
166        let mut c = col;
167        for ch in text.chars() {
168            if c >= self.width {
169                break;
170            }
171            let width = ch.width().unwrap_or(1);
172            if width == 0 {
173                self.merge_combining_mark(row, c, col, ch, fg, bg, style, c < self.width);
174                continue;
175            }
176            // Don't write a wide character if it doesn't fully fit — the
177            // terminal would render it as 2 columns but only 1 cell would
178            // be tracked, causing cursor misalignment in render_diff.
179            if width > 1 && c + 1 >= self.width {
180                break;
181            }
182            self.set_cell(
183                row,
184                c,
185                Cell {
186                    char: ch,
187                    fg,
188                    bg,
189                    style,
190                    wide: false,
191                },
192            );
193            if width > 1 && c + 1 < self.width {
194                self.set_cell(row, c + 1, Cell::wide_continuation(fg, bg, style));
195            }
196            c += width as u16;
197        }
198    }
199
200    /// Write a string starting at the given position, truncating or wrapping.
201    ///
202    /// If `wrap` is true, text wraps to the next line. If false, text is
203    /// truncated at the right edge. Uses Unicode display widths.
204    ///
205    /// This is a convenience wrapper around `Self::write_wrapped` with
206    /// simple wrapping bounded by the screen dimensions.
207    pub fn write_str_wrapped(
208        &mut self,
209        start_row: u16,
210        start_col: u16,
211        text: &str,
212        fg: Color,
213        bg: Color,
214        style: Style,
215        wrap: bool,
216    ) -> u16 {
217        self.write_wrapped(
218            start_row,
219            start_col,
220            text,
221            fg,
222            bg,
223            style,
224            WrapConfig {
225                wrap_col: self.width,
226                left_margin: 0,
227                max_row: self.height.saturating_sub(1),
228                skip_rows: 0,
229                no_wrap: !wrap,
230                screen_bounded: true,
231            },
232        )
233    }
234
235    /// Write a string with wrapping, but clip rendering at the given maximum row
236    /// and wrap at the given column.
237    ///
238    /// `wrap_col` is the maximum column number; text wraps when `col >= wrap_col`.
239    /// `max_row` is the maximum row; text stops when `row > max_row`.
240    /// `left_margin` is the column where wrapped lines start. Uses Unicode display widths.
241    ///
242    /// This is a convenience wrapper around `Self::write_wrapped` with
243    /// `skip_rows = 0` and wrapping enabled.
244    pub fn write_str_wrapped_clipped(
245        &mut self,
246        start_row: u16,
247        start_col: u16,
248        text: &str,
249        fg: Color,
250        bg: Color,
251        style: Style,
252        left_margin: u16,
253        max_row: u16,
254        wrap_col: u16,
255    ) -> u16 {
256        self.write_wrapped(
257            start_row,
258            start_col,
259            text,
260            fg,
261            bg,
262            style,
263            WrapConfig {
264                wrap_col,
265                left_margin,
266                max_row,
267                skip_rows: 0,
268                no_wrap: false,
269                screen_bounded: false,
270            },
271        )
272    }
273
274    /// Write a string with wrapping, skip the first `skip_rows` visual rows,
275    /// and clip rendering at the given maximum row and wrap column.
276    ///
277    /// `wrap_col` is the maximum column number; text wraps when `col >= wrap_col`.
278    /// `skip_rows` is the number of visual rows to skip before rendering.
279    /// `max_row` is the maximum row; text stops when `row > max_row`.
280    /// `left_margin` is the column where wrapped lines start. Uses Unicode display widths.
281    ///
282    /// This is a convenience wrapper around `Self::write_wrapped` with
283    /// `skip_rows > 0`.
284    pub fn write_str_wrapped_skip_clipped(
285        &mut self,
286        start_row: u16,
287        start_col: u16,
288        text: &str,
289        fg: Color,
290        bg: Color,
291        style: Style,
292        left_margin: u16,
293        max_row: u16,
294        wrap_col: u16,
295        skip_rows: usize,
296    ) {
297        self.write_wrapped(
298            start_row,
299            start_col,
300            text,
301            fg,
302            bg,
303            style,
304            WrapConfig {
305                wrap_col,
306                left_margin,
307                max_row,
308                skip_rows,
309                no_wrap: false,
310                screen_bounded: false,
311            },
312        );
313    }
314
315    /// Unified wrapped text writing method.
316    ///
317    /// Handles all wrapping scenarios through a single [`WrapConfig`] struct.
318    /// The method tracks both a visual row counter (for skip/clipping) and a
319    /// screen row counter (for actual cell placement).
320    ///
321    /// Returns the final screen row where text ended.
322    fn write_wrapped(
323        &mut self,
324        start_row: u16,
325        start_col: u16,
326        text: &str,
327        fg: Color,
328        bg: Color,
329        style: Style,
330        cfg: WrapConfig,
331    ) -> u16 {
332        let mut visual_row: usize = 0;
333        let mut col = start_col;
334        let mut screen_row = start_row;
335
336        for ch in text.chars() {
337            let width = ch.width().unwrap_or(1);
338            if width == 0 {
339                let in_view = if cfg.skip_rows > 0 {
340                    visual_row >= cfg.skip_rows && screen_row <= cfg.max_row
341                } else if cfg.screen_bounded {
342                    col < self.width && screen_row < self.height
343                } else {
344                    screen_row <= cfg.max_row
345                };
346                self.merge_combining_mark(screen_row, col, start_col, ch, fg, bg, style, in_view);
347                continue;
348            }
349            let width_u16 = width as u16;
350
351            // Handle newline
352            if ch == '\n' {
353                visual_row += 1;
354                col = cfg.left_margin;
355                if cfg.skip_rows == 0 || visual_row > cfg.skip_rows {
356                    screen_row += 1;
357                }
358                if screen_row > cfg.max_row {
359                    break;
360                }
361                continue;
362            }
363
364            // Handle wrap
365            if col + width_u16 > cfg.wrap_col {
366                if cfg.no_wrap {
367                    break;
368                }
369                visual_row += 1;
370                col = cfg.left_margin;
371                if cfg.skip_rows == 0 || visual_row > cfg.skip_rows {
372                    screen_row += 1;
373                }
374                if screen_row > cfg.max_row {
375                    break;
376                }
377                // For screen_bounded mode (old write_str_wrapped), check screen height
378                if cfg.screen_bounded && screen_row >= self.height {
379                    break;
380                }
381            }
382
383            // Only write the cell if we're past the skip zone and within bounds
384            let past_skip = cfg.skip_rows == 0 || visual_row >= cfg.skip_rows;
385            if past_skip && screen_row <= cfg.max_row {
386                // Don't write a wide character if it doesn't fully fit on the
387                // screen — the terminal renders it as 2 columns but only 1
388                // cell would be tracked, causing cursor misalignment.
389                if width > 1 && col + 1 >= self.width {
390                    break;
391                }
392                self.set_cell(
393                    screen_row,
394                    col,
395                    Cell {
396                        char: ch,
397                        fg,
398                        bg,
399                        style,
400                        wide: false,
401                    },
402                );
403                if width > 1 && col + 1 < self.width {
404                    self.set_cell(screen_row, col + 1, Cell::wide_continuation(fg, bg, style));
405                }
406            }
407
408            col += width_u16;
409        }
410
411        screen_row
412    }
413
414    /// Fill a rectangular area with the given cell.
415    pub fn fill_rect(&mut self, rect: Rect, cell: Cell) {
416        for row in rect.y..rect.y + rect.height {
417            for col in rect.x..rect.x + rect.width {
418                if row < self.height && col < self.width {
419                    self.set_cell(row, col, cell.clone());
420                }
421            }
422        }
423    }
424
425    /// Draw a horizontal line using the given character.
426    pub fn hline(
427        &mut self,
428        row: u16,
429        col_start: u16,
430        col_end: u16,
431        ch: char,
432        fg: Color,
433        bg: Color,
434    ) {
435        for col in col_start..=col_end.min(self.width.saturating_sub(1)) {
436            self.set_cell(
437                row,
438                col,
439                Cell {
440                    char: ch,
441                    fg,
442                    bg,
443                    style: Style::default(),
444                    wide: false,
445                },
446            );
447        }
448    }
449
450    /// Draw a vertical line using the given character.
451    pub fn vline(
452        &mut self,
453        col: u16,
454        row_start: u16,
455        row_end: u16,
456        ch: char,
457        fg: Color,
458        bg: Color,
459    ) {
460        for row in row_start..=row_end.min(self.height.saturating_sub(1)) {
461            self.set_cell(
462                row,
463                col,
464                Cell {
465                    char: ch,
466                    fg,
467                    bg,
468                    style: Style::default(),
469                    wide: false,
470                },
471            );
472        }
473    }
474
475    /// Draw a box (border) around a rectangular area.
476    pub fn draw_box(&mut self, rect: Rect, fg: Color, bg: Color, style: Style) {
477        let x = rect.x;
478        let y = rect.y;
479        let w = rect.width;
480        let h = rect.height;
481
482        if w < 2 || h < 2 {
483            return;
484        }
485
486        // Corners
487        self.set_cell(
488            y,
489            x,
490            Cell {
491                char: '┌',
492                fg,
493                bg,
494                style,
495                wide: false,
496            },
497        );
498        self.set_cell(
499            y,
500            x + w - 1,
501            Cell {
502                char: '┐',
503                fg,
504                bg,
505                style,
506                wide: false,
507            },
508        );
509        self.set_cell(
510            y + h - 1,
511            x,
512            Cell {
513                char: '└',
514                fg,
515                bg,
516                style,
517                wide: false,
518            },
519        );
520        self.set_cell(
521            y + h - 1,
522            x + w - 1,
523            Cell {
524                char: '┘',
525                fg,
526                bg,
527                style,
528                wide: false,
529            },
530        );
531
532        // Top and bottom borders
533        for col in (x + 1)..(x + w - 1) {
534            self.set_cell(
535                y,
536                col,
537                Cell {
538                    char: '─',
539                    fg,
540                    bg,
541                    style,
542                    wide: false,
543                },
544            );
545            self.set_cell(
546                y + h - 1,
547                col,
548                Cell {
549                    char: '─',
550                    fg,
551                    bg,
552                    style,
553                    wide: false,
554                },
555            );
556        }
557
558        // Left and right borders
559        for row in (y + 1)..(y + h - 1) {
560            self.set_cell(
561                row,
562                x,
563                Cell {
564                    char: '│',
565                    fg,
566                    bg,
567                    style,
568                    wide: false,
569                },
570            );
571            self.set_cell(
572                row,
573                x + w - 1,
574                Cell {
575                    char: '│',
576                    fg,
577                    bg,
578                    style,
579                    wide: false,
580                },
581            );
582        }
583    }
584
585    // ── Diff-based rendering ────────────────────────────────────────────
586
587    /// Compute the diff between this screen and a previous frame.
588    ///
589    /// Returns a list of `DiffOp` entries that, when applied in order,
590    /// will bring the terminal from the previous state to the current state.
591    pub fn diff_from(&self, previous: &Screen) -> Vec<DiffOp> {
592        let mut ops = Vec::new();
593        let max_row = self.height.min(previous.height);
594        let max_col = self.width.min(previous.width);
595
596        for row in 0..max_row {
597            for col in 0..max_col {
598                let prev_cell = previous.get(row, col);
599                let curr_cell = self.get(row, col);
600
601                match (prev_cell, curr_cell) {
602                    (Some(prev), Some(curr)) if prev != curr => {
603                        ops.push(DiffOp::SetCell {
604                            row,
605                            col,
606                            cell: curr.clone(),
607                        });
608                    }
609                    (None, Some(curr)) => {
610                        ops.push(DiffOp::SetCell {
611                            row,
612                            col,
613                            cell: curr.clone(),
614                        });
615                    }
616                    _ => {}
617                }
618            }
619        }
620
621        // Handle rows that exist in the new screen but not the old one
622        for row in previous.height..self.height {
623            for col in 0..self.width {
624                if let Some(cell) = self.get(row, col) {
625                    ops.push(DiffOp::SetCell {
626                        row,
627                        col,
628                        cell: cell.clone(),
629                    });
630                }
631            }
632        }
633
634        ops
635    }
636
637    /// Render a list of diff operations to an ANSI escape sequence string.
638    ///
639    /// This is the core of the efficient rendering: we only write cells
640    /// that actually changed, and we batch cursor movements.
641    ///
642    /// Handles wide (CJK/fullwidth) characters correctly by skipping
643    /// continuation cells and tracking display width for cursor position.
644    ///
645    /// Optimizations for terminal throughput:
646    /// - Consecutive cells on the same row skip the cursor move (cursor
647    ///   naturally advances after writing a character).
648    /// - Style reset (`\x1b[0m`) + re-application is only emitted when the
649    ///   style actually changes from the previous cell, not per-cell.
650    /// - Cells with default style and colors (typically spaces) skip the
651    ///   style/fg/bg escape sequences entirely.
652    pub fn render_diff(ops: &[DiffOp], width: u16) -> String {
653        use unicode_width::UnicodeWidthChar;
654
655        if ops.is_empty() {
656            return String::new();
657        }
658
659        let mut output = String::with_capacity(ops.len() * 24);
660        let mut last_row: Option<u16> = None;
661        let mut last_col: Option<u16> = None;
662        // Track the currently active style on the terminal so we only emit
663        // changes, not a full reset+reapply for every cell.
664        let mut active_fg: Option<Color> = None;
665        let mut active_bg: Option<Color> = None;
666        let mut active_style: Option<Style> = None;
667
668        for op in ops {
669            match op {
670                DiffOp::SetCell { row, col, cell } => {
671                    // Skip continuation cells — they're rendered as part of
672                    // the wide character in the preceding column
673                    if cell.wide {
674                        continue;
675                    }
676
677                    // Move cursor if needed
678                    // last_col stores the position the cursor should be at after
679                    // writing the previous character (col + char_width), so the
680                    // next character is expected at exactly last_col — no +1 needed.
681                    let need_move = last_row != Some(*row) || last_col != Some(*col);
682
683                    if need_move {
684                        output.push_str(&format!("\x1b[{};{}H", row + 1, col + 1));
685                    }
686
687                    // Apply style/fg/bg only when they differ from what's
688                    // currently active on the terminal. This avoids flooding
689                    // the terminal with redundant escape sequences.
690                    let fg_changed = active_fg != Some(cell.fg);
691                    let bg_changed = active_bg != Some(cell.bg);
692                    let style_changed = active_style != Some(cell.style);
693                    let needs_reset = style_changed
694                        || (fg_changed && cell.fg != Color::Default)
695                        || (bg_changed && cell.bg != Color::Default);
696
697                    if needs_reset {
698                        // Full reset + reapply is safest when style attributes
699                        // (bold/dim/etc.) change, because you can't selectively
700                        // unset bold without resetting everything.
701                        output.push_str("\x1b[0m");
702                        active_fg = None;
703                        active_bg = None;
704                        active_style = None;
705                    }
706
707                    // Apply style if changed (or was just reset)
708                    if active_style != Some(cell.style) {
709                        output.push_str(&cell.style.escape());
710                        active_style = Some(cell.style);
711                    }
712
713                    // Apply fg if changed (or was just reset)
714                    if active_fg != Some(cell.fg) {
715                        output.push_str(&cell.fg.fg_escape());
716                        active_fg = Some(cell.fg);
717                    }
718
719                    // Apply bg if changed (or was just reset)
720                    if active_bg != Some(cell.bg) {
721                        output.push_str(&cell.bg.bg_escape());
722                        active_bg = Some(cell.bg);
723                    }
724
725                    // Write character
726                    output.push(cell.char);
727
728                    // Track cursor position accounting for display width
729                    let char_width = cell.char.width().unwrap_or(1).max(1) as u16;
730                    last_row = Some(*row);
731                    last_col = Some(*col + char_width);
732
733                    // If we're at the right edge, the cursor won't advance
734                    // further, so we need to move it explicitly next time
735                    if *col + char_width >= width {
736                        last_col = None;
737                    }
738                }
739            }
740        }
741
742        // Reset all styles at the end
743        output.push_str(Style::reset());
744
745        output
746    }
747}
748
749impl Clone for Screen {
750    fn clone(&self) -> Self {
751        Screen {
752            width: self.width,
753            height: self.height,
754            cells: self.cells.clone(),
755        }
756    }
757}
758
759impl fmt::Debug for Screen {
760    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
761        f.debug_struct("Screen")
762            .field("width", &self.width)
763            .field("height", &self.height)
764            .finish()
765    }
766}
767
768// ── Diff operation ───────────────────────────────────────────────────────────
769
770/// A single rendering operation produced by diffing two screens.
771#[derive(Clone, Debug, PartialEq)]
772pub enum DiffOp {
773    /// Set the cell at (row, col) to the given value.
774    SetCell { row: u16, col: u16, cell: Cell },
775}
776
777#[cfg(test)]
778mod tests {
779    use super::*;
780
781    #[test]
782    fn test_screen_new() {
783        let s = Screen::new(10, 5);
784        assert_eq!(s.width(), 10);
785        assert_eq!(s.height(), 5);
786        // All cells should be default (space)
787        assert_eq!(s.get(0, 0).unwrap().char, ' ');
788    }
789
790    #[test]
791    fn test_screen_set_get_cell() {
792        let mut s = Screen::new(10, 5);
793        let cell = Cell::styled('X', Color::RED, Color::Default, Style::bold());
794        s.set_cell(2, 3, cell.clone());
795        assert_eq!(s.get(2, 3).unwrap(), &cell);
796    }
797
798    #[test]
799    fn test_screen_out_of_bounds() {
800        let s = Screen::new(10, 5);
801        assert!(s.get(5, 0).is_none());
802        assert!(s.get(0, 10).is_none());
803    }
804
805    #[test]
806    fn test_screen_write_str() {
807        let mut s = Screen::new(20, 5);
808        s.write_str(1, 2, "Hello", Color::GREEN, Color::Default, Style::new());
809        assert_eq!(s.get(1, 2).unwrap().char, 'H');
810        assert_eq!(s.get(1, 3).unwrap().char, 'e');
811        assert_eq!(s.get(1, 6).unwrap().char, 'o');
812        assert_eq!(s.get(1, 7).unwrap().char, ' '); // default
813    }
814
815    #[test]
816    fn test_screen_write_str_truncates() {
817        let mut s = Screen::new(5, 1);
818        s.write_str(
819            0,
820            0,
821            "Hello World",
822            Color::Default,
823            Color::Default,
824            Style::new(),
825        );
826        assert_eq!(s.get(0, 4).unwrap().char, 'o'); // 5th char (index 4)
827        // "World" should be truncated
828    }
829
830    #[test]
831    fn test_screen_clear() {
832        let mut s = Screen::new(10, 5);
833        s.set_cell(0, 0, Cell::char('X'));
834        s.clear();
835        assert_eq!(s.get(0, 0).unwrap().char, ' ');
836    }
837
838    #[test]
839    fn test_screen_resize() {
840        let mut s = Screen::new(10, 5);
841        s.set_cell(0, 0, Cell::char('X'));
842        s.resize(20, 10);
843        assert_eq!(s.width(), 20);
844        assert_eq!(s.height(), 10);
845        // Old content should be gone
846        assert_eq!(s.get(0, 0).unwrap().char, ' ');
847    }
848
849    #[test]
850    fn test_screen_draw_box() {
851        let mut s = Screen::new(10, 5);
852        s.draw_box(
853            Rect {
854                x: 0,
855                y: 0,
856                width: 10,
857                height: 5,
858            },
859            Color::BLUE,
860            Color::Default,
861            Style::default(),
862        );
863        assert_eq!(s.get(0, 0).unwrap().char, '┌');
864        assert_eq!(s.get(0, 9).unwrap().char, '┐');
865        assert_eq!(s.get(4, 0).unwrap().char, '└');
866        assert_eq!(s.get(4, 9).unwrap().char, '┘');
867        assert_eq!(s.get(0, 5).unwrap().char, '─');
868        assert_eq!(s.get(2, 0).unwrap().char, '│');
869    }
870
871    #[test]
872    fn test_screen_diff_no_changes() {
873        let s1 = Screen::new(10, 5);
874        let s2 = Screen::new(10, 5);
875        let diff = s2.diff_from(&s1);
876        assert!(diff.is_empty());
877    }
878
879    #[test]
880    fn test_screen_diff_with_changes() {
881        let s1 = Screen::new(10, 5);
882        let mut s2 = Screen::new(10, 5);
883        s2.set_cell(1, 2, Cell::char('X'));
884        s2.set_cell(3, 4, Cell::char('Y'));
885
886        let diff = s2.diff_from(&s1);
887        assert_eq!(diff.len(), 2);
888    }
889
890    #[test]
891    fn test_screen_render_diff() {
892        let s1 = Screen::new(10, 5);
893        let mut s2 = Screen::new(10, 5);
894        s2.set_cell(
895            0,
896            0,
897            Cell::styled('A', Color::RED, Color::Default, Style::bold()),
898        );
899
900        let diff = s2.diff_from(&s1);
901        let rendered = Screen::render_diff(&diff, 10);
902
903        // Should contain cursor movement and the character
904        assert!(rendered.contains("\x1b[1;1H")); // move to (1,1)
905        assert!(rendered.contains('A'));
906        assert!(rendered.contains("\x1b[0m")); // reset at end
907    }
908
909    #[test]
910    fn test_screen_hline() {
911        let mut s = Screen::new(10, 5);
912        s.hline(2, 1, 8, '─', Color::Default, Color::Default);
913        assert_eq!(s.get(2, 1).unwrap().char, '─');
914        assert_eq!(s.get(2, 8).unwrap().char, '─');
915        assert_eq!(s.get(2, 0).unwrap().char, ' '); // before line
916    }
917
918    #[test]
919    fn test_screen_vline() {
920        let mut s = Screen::new(10, 5);
921        s.vline(5, 1, 3, '│', Color::Default, Color::Default);
922        assert_eq!(s.get(1, 5).unwrap().char, '│');
923        assert_eq!(s.get(2, 5).unwrap().char, '│');
924        assert_eq!(s.get(3, 5).unwrap().char, '│');
925        assert_eq!(s.get(0, 5).unwrap().char, ' '); // before line
926    }
927
928    #[test]
929    fn test_screen_fill_rect() {
930        let mut s = Screen::new(10, 5);
931        let rect = Rect {
932            x: 2,
933            y: 1,
934            width: 3,
935            height: 2,
936        };
937        s.fill_rect(rect, Cell::char('█'));
938
939        assert_eq!(s.get(1, 2).unwrap().char, '█');
940        assert_eq!(s.get(1, 4).unwrap().char, '█');
941        assert_eq!(s.get(2, 2).unwrap().char, '█');
942        assert_eq!(s.get(0, 2).unwrap().char, ' '); // outside rect
943    }
944
945    #[test]
946    fn test_screen_write_str_wrapped() {
947        let mut s = Screen::new(5, 5);
948        let end_row = s.write_str_wrapped(
949            0,
950            0,
951            "ABCDEFGH",
952            Color::Default,
953            Color::Default,
954            Style::new(),
955            true,
956        );
957        // "ABCDE" on row 0, "FGH" on row 1
958        assert_eq!(s.get(0, 0).unwrap().char, 'A');
959        assert_eq!(s.get(0, 4).unwrap().char, 'E');
960        assert_eq!(s.get(1, 0).unwrap().char, 'F');
961        assert_eq!(s.get(1, 2).unwrap().char, 'H');
962        assert_eq!(end_row, 1);
963    }
964
965    #[test]
966    fn test_screen_write_str_wrapped_skip_clipped() {
967        let mut s = Screen::new(5, 5);
968        // "ABCDE" on row 0, "FGH" on row 1
969        // Skip the first row, render only "FGH" starting at screen row 0
970        s.write_str_wrapped_skip_clipped(
971            0,
972            0,
973            "ABCDEFGH",
974            Color::Default,
975            Color::Default,
976            Style::new(),
977            0,
978            4,
979            5, // wrap_col
980            1, // skip 1 row
981        );
982        // Row 0 should have "FGH" (the 2nd visual row of the text)
983        assert_eq!(s.get(0, 0).unwrap().char, 'F');
984        assert_eq!(s.get(0, 2).unwrap().char, 'H');
985        // Row 1 should be empty (default)
986        assert_eq!(s.get(1, 0).unwrap().char, ' ');
987    }
988
989    #[test]
990    fn test_screen_write_str_wrapped_skip_clipped_newlines() {
991        let mut s = Screen::new(5, 5);
992        // "AB\nCD" → row 0: "AB", row 1: "CD"
993        // Skip 1 row, render "CD" starting at screen row 0
994        s.write_str_wrapped_skip_clipped(
995            0,
996            0,
997            "AB\nCD",
998            Color::Default,
999            Color::Default,
1000            Style::new(),
1001            0,
1002            4,
1003            5,
1004            1,
1005        );
1006        assert_eq!(s.get(0, 0).unwrap().char, 'C');
1007        assert_eq!(s.get(0, 1).unwrap().char, 'D');
1008    }
1009
1010    #[test]
1011    fn test_screen_write_str_wide_char() {
1012        // Wide (CJK) characters should occupy 2 columns and mark continuation cell
1013        let mut s = Screen::new(10, 3);
1014        // '一' is a CJK character with display width 2
1015        s.write_str(0, 0, "一x", Color::Default, Color::Default, Style::new());
1016
1017        // The wide char should be at col 0
1018        let cell_0 = s.get(0, 0).unwrap();
1019        assert_eq!(cell_0.char, '一');
1020        assert!(!cell_0.wide);
1021
1022        // The continuation cell should be at col 1
1023        let cell_1 = s.get(0, 1).unwrap();
1024        assert!(cell_1.wide);
1025
1026        // 'x' should be at col 2 (not col 1)
1027        let cell_2 = s.get(0, 2).unwrap();
1028        assert_eq!(cell_2.char, 'x');
1029        assert!(!cell_2.wide);
1030    }
1031
1032    #[test]
1033    fn test_screen_write_str_wide_char_at_edge() {
1034        // Wide char at the right edge should not overflow
1035        let mut s = Screen::new(3, 1);
1036        s.write_str(0, 0, "一", Color::Default, Color::Default, Style::new());
1037
1038        // '一' takes cols 0-1, which fits in width 3
1039        assert_eq!(s.get(0, 0).unwrap().char, '一');
1040        assert!(s.get(0, 1).unwrap().wide);
1041        assert_eq!(s.get(0, 2).unwrap().char, ' '); // empty
1042    }
1043
1044    #[test]
1045    fn test_cell_default_not_wide() {
1046        let cell = Cell::default();
1047        assert!(!cell.wide);
1048        assert_eq!(cell.char, ' ');
1049    }
1050
1051    #[test]
1052    fn test_cell_wide_continuation() {
1053        let cell = Cell::wide_continuation(Color::RED, Color::BLUE, Style::bold());
1054        assert!(cell.wide);
1055        assert_eq!(cell.char, ' ');
1056        assert_eq!(cell.fg, Color::RED);
1057        assert_eq!(cell.bg, Color::BLUE);
1058        assert!(cell.style.bold);
1059    }
1060
1061    #[test]
1062    fn test_screen_diff_wide_char_tracking() {
1063        // When a wide char changes, the continuation cell should also be
1064        // included in the diff so it gets properly updated.
1065        let mut s1 = Screen::new(10, 1);
1066        let mut s2 = Screen::new(10, 1);
1067        s1.write_str(0, 0, "AB", Color::Default, Color::Default, Style::new());
1068        s2.write_str(0, 0, "一x", Color::Default, Color::Default, Style::new());
1069
1070        let diff = s2.diff_from(&s1);
1071
1072        // Should have diffs for: col 0 (一 replaces A), col 1 (continuation replaces B), col 2 (x replaces nothing)
1073        // At minimum, cols 0 and 1 must differ
1074        assert!(diff.len() >= 2);
1075
1076        // Check that col 0 has the wide char
1077        let col0_op = diff
1078            .iter()
1079            .find(|op| matches!(op, DiffOp::SetCell { col: 0, .. }));
1080        assert!(col0_op.is_some());
1081        let DiffOp::SetCell { cell: cell0, .. } = col0_op.unwrap();
1082        assert_eq!(cell0.char, '一');
1083        assert!(!cell0.wide);
1084
1085        // Check that col 1 has the continuation marker
1086        let col1_op = diff
1087            .iter()
1088            .find(|op| matches!(op, DiffOp::SetCell { col: 1, .. }));
1089        assert!(col1_op.is_some());
1090        let DiffOp::SetCell { cell: cell1, .. } = col1_op.unwrap();
1091        assert!(cell1.wide);
1092    }
1093
1094    #[test]
1095    fn test_screen_write_str_wrapped_long_message_with_spaces() {
1096        // Simulate a long message with spaces, like what the conversation widget renders
1097        let mut s = Screen::new(10, 5);
1098        let _end_row = s.write_str_wrapped(
1099            0,
1100            0,
1101            "Hello World This Is A Test",
1102            Color::WHITE,
1103            Color::Default,
1104            Style::default(),
1105            true,
1106        );
1107        // With width 10:
1108        // Row 0: "Hello Worl" (10 chars, 'd' wraps)
1109        // Row 1: "d This Is " (10 chars, 'A' wraps)
1110        // Row 2: "A Test" (6 chars)
1111        // Verify wrapping preserves spaces correctly
1112        assert_eq!(s.get(0, 0).unwrap().char, 'H');
1113        assert_eq!(s.get(0, 5).unwrap().char, ' '); // space between "Hello" and "World"
1114        assert_eq!(s.get(1, 0).unwrap().char, 'd');
1115        assert_eq!(s.get(1, 1).unwrap().char, ' '); // space between "World" and "This"
1116        assert_eq!(s.get(2, 0).unwrap().char, 'A');
1117        assert_eq!(s.get(2, 1).unwrap().char, ' '); // space between "A" and "Test"
1118        assert_eq!(s.get(2, 2).unwrap().char, 'T');
1119    }
1120
1121    #[test]
1122    fn test_screen_write_str_wrapped_clipped_multiline() {
1123        // Test clipped wrapping with a multi-line message
1124        let mut s = Screen::new(10, 5);
1125        let _end_row = s.write_str_wrapped_clipped(
1126            0,
1127            2,
1128            "AB CD",
1129            Color::WHITE,
1130            Color::Default,
1131            Style::default(),
1132            2,  // left_margin
1133            4,  // max_row
1134            10, // wrap_col
1135        );
1136        // "AB CD" starting at col 2, width 10
1137        // Row 0: "  AB CD" (fits within 8 cols from col 2)
1138        assert_eq!(s.get(0, 2).unwrap().char, 'A');
1139        assert_eq!(s.get(0, 3).unwrap().char, 'B');
1140        assert_eq!(s.get(0, 4).unwrap().char, ' ');
1141        assert_eq!(s.get(0, 5).unwrap().char, 'C');
1142        assert_eq!(s.get(0, 6).unwrap().char, 'D');
1143    }
1144
1145    #[test]
1146    fn test_screen_write_str_wrapped_newlines() {
1147        // Test that newlines work correctly in wrapped mode
1148        let mut s = Screen::new(10, 5);
1149        s.write_str_wrapped(
1150            0,
1151            0,
1152            "AB\nCD",
1153            Color::WHITE,
1154            Color::Default,
1155            Style::default(),
1156            true,
1157        );
1158        // Row 0: "AB        "
1159        // Row 1: "CD        "
1160        assert_eq!(s.get(0, 0).unwrap().char, 'A');
1161        assert_eq!(s.get(0, 1).unwrap().char, 'B');
1162        assert_eq!(s.get(1, 0).unwrap().char, 'C');
1163        assert_eq!(s.get(1, 1).unwrap().char, 'D');
1164    }
1165
1166    #[test]
1167    fn test_screen_write_str_wrapped_clipped_with_left_margin() {
1168        // Test wrapped clipping with left margin (like conversation messages)
1169        let mut s = Screen::new(20, 5);
1170        let _end_row = s.write_str_wrapped_clipped(
1171            0,
1172            7,
1173            "Hello World This Is A Long Message That Wraps",
1174            Color::WHITE,
1175            Color::Default,
1176            Style::default(),
1177            7,  // left_margin
1178            4,  // max_row
1179            20, // wrap_col
1180        );
1181        // First line starts at col 7, wraps at col 20
1182        // Subsequent lines start at col 7
1183        assert_eq!(s.get(0, 7).unwrap().char, 'H');
1184    }
1185
1186    #[test]
1187    fn test_screen_clear_replaces_with_spaces() {
1188        // Verify that clear() properly resets cells to spaces
1189        let mut s = Screen::new(10, 3);
1190        s.write_str(
1191            0,
1192            0,
1193            "ABCDEFGHIJ",
1194            Color::WHITE,
1195            Color::Default,
1196            Style::default(),
1197        );
1198        assert_eq!(s.get(0, 0).unwrap().char, 'A');
1199        assert_eq!(s.get(0, 5).unwrap().char, 'F');
1200        s.clear();
1201        assert_eq!(s.get(0, 0).unwrap().char, ' ');
1202        assert_eq!(s.get(0, 5).unwrap().char, ' ');
1203    }
1204
1205    #[test]
1206    fn test_screen_write_str_wrapped_skip_clipped_preserves_spaces() {
1207        // Test that spaces are preserved when using skip_clipped wrapping
1208        let mut s = Screen::new(20, 5);
1209        // "Hello World" with left_margin=2, starting at col 2
1210        // First row: "  Hello World" (fits in 18 cols)
1211        // Now skip 0 rows (render from start)
1212        s.write_str_wrapped_skip_clipped(
1213            0,
1214            2,
1215            "Hello World",
1216            Color::WHITE,
1217            Color::Default,
1218            Style::default(),
1219            2,  // left_margin
1220            4,  // max_row
1221            20, // wrap_col
1222            0,  // skip_rows
1223        );
1224        // The space between "Hello" and "World" should be preserved
1225        assert_eq!(s.get(0, 2).unwrap().char, 'H');
1226        assert_eq!(s.get(0, 7).unwrap().char, ' '); // space between Hello and World
1227        assert_eq!(s.get(0, 8).unwrap().char, 'W');
1228    }
1229
1230    #[test]
1231    fn test_screen_write_str_wrapped_skip_clipped_multirow() {
1232        // Test a long message that wraps, with skip_rows
1233        let mut s = Screen::new(10, 5);
1234        // "ABCDEFGH" wraps to "ABCDEFGH" then "IJ"
1235        // With width 10: "ABCDEFGHIJ" fits on one row
1236        // Let's use something longer: "ABCDEFGHIJKLMNO"
1237        // Row 0: "ABCDEFGHIJ" (10 chars)
1238        // Row 1: "KLMNO" (5 chars)
1239        // Skip 1 row, render only row 1 at screen row 0
1240        s.write_str_wrapped_skip_clipped(
1241            0,
1242            0,
1243            "ABCDEFGHIJKLMNO",
1244            Color::WHITE,
1245            Color::Default,
1246            Style::default(),
1247            0,  // left_margin
1248            4,  // max_row
1249            10, // wrap_col
1250            1,  // skip 1 row (skip "ABCDEFGHIJ")
1251        );
1252        // Row 0 should have "KLMNO"
1253        assert_eq!(s.get(0, 0).unwrap().char, 'K');
1254        assert_eq!(s.get(0, 1).unwrap().char, 'L');
1255        assert_eq!(s.get(0, 4).unwrap().char, 'O');
1256    }
1257
1258    #[test]
1259    fn test_screen_render_diff_dedupes_styles() {
1260        // Verify that render_diff doesn't emit redundant style/fg/bg
1261        // sequences for consecutive cells with the same style.
1262        let s1 = Screen::new(80, 24);
1263        let mut s2 = Screen::new(80, 24);
1264        // Write 10 consecutive characters with the SAME style
1265        s2.write_str(
1266            5,
1267            0,
1268            "ABCDEFGHIJ",
1269            Color::WHITE,
1270            Color::Default,
1271            Style::default(),
1272        );
1273
1274        let diff = s2.diff_from(&s1);
1275        let rendered = Screen::render_diff(&diff, 80);
1276
1277        // With the optimized render_diff, consecutive cells with the same
1278        // style should NOT repeat the fg/bg escape sequences.
1279        // For default style + WHITE fg + Default bg, we expect:
1280        // - 1 cursor move to start
1281        // - 1 reset + style + fg (since bg is default, no bg escape needed)
1282        // - 9 plain characters (no extra escapes)
1283        // - 1 reset at end
1284        let fg_count = rendered.matches("\x1b[37m").count(); // WHITE = Ansi(7) = \x1b[37m
1285        let reset_count = rendered.matches("\x1b[0m").count();
1286
1287        // FG should only be set once (for the first cell), not 10 times
1288        assert!(
1289            fg_count <= 2,
1290            "Expected at most 2 fg sequences (one for first cell + one at final reset), got {}",
1291            fg_count
1292        );
1293        // Reset should be emitted at most once per style change + once at end
1294        assert!(
1295            reset_count <= 2,
1296            "Expected at most 2 resets (initial + final), got {}",
1297            reset_count
1298        );
1299    }
1300
1301    #[test]
1302    fn test_screen_render_diff_preserves_correct_output() {
1303        // Verify that the optimized render_diff still produces correct output
1304        let s1 = Screen::new(80, 24);
1305        let mut s2 = Screen::new(80, 24);
1306        s2.write_str(
1307            5,
1308            0,
1309            "wrong chars",
1310            Color::WHITE,
1311            Color::Default,
1312            Style::default(),
1313        );
1314
1315        let diff = s2.diff_from(&s1);
1316        let rendered = Screen::render_diff(&diff, 80);
1317
1318        // The output should contain the actual characters in order
1319        // Extract just the printable characters from the output
1320        let printable: String = rendered
1321            .chars()
1322            .filter(|c| !c.is_control() && *c != '\x1b')
1323            .collect();
1324        // Should contain "wrong chars"
1325        assert!(
1326            printable.contains("wrong chars"),
1327            "Output should contain 'wrong chars', got printable: {:?}",
1328            printable
1329        );
1330    }
1331
1332    #[test]
1333    fn test_screen_render_diff_style_change_forces_reset() {
1334        // When style changes (e.g., bold to dim), a reset must be emitted
1335        let s1 = Screen::new(80, 24);
1336        let mut s2 = Screen::new(80, 24);
1337        s2.write_str(0, 0, "AB", Color::WHITE, Color::Default, Style::bold());
1338        s2.write_str(0, 2, "CD", Color::WHITE, Color::Default, Style::dim());
1339
1340        let diff = s2.diff_from(&s1);
1341        let rendered = Screen::render_diff(&diff, 80);
1342
1343        // Should contain at least one reset (to switch from bold to dim)
1344        let reset_count = rendered.matches("\x1b[0m").count();
1345        assert!(
1346            reset_count >= 1,
1347            "Expected at least 1 reset for style change, got {}",
1348            reset_count
1349        );
1350    }
1351
1352    #[test]
1353    fn test_screen_wide_char_does_not_overflow_last_column() {
1354        // A wide character at the last column should not be written as a
1355        // half-width glyph — it should be skipped entirely.
1356        let mut s = Screen::new(3, 1);
1357        // '一' has width 2. At col 2 (last column of a 3-wide screen),
1358        // it needs cols 2-3 but only col 2 exists.
1359        s.write_str(0, 2, "一", Color::Default, Color::Default, Style::new());
1360        // The cell at col 2 should remain default (space) — the wide char
1361        // was skipped because it didn't fully fit.
1362        assert_eq!(s.get(0, 2).unwrap().char, ' ');
1363        assert!(!s.get(0, 2).unwrap().wide);
1364    }
1365
1366    #[test]
1367    fn test_screen_combining_mark_after_wide_char() {
1368        // A combining mark after a wide character should merge into the
1369        // wide character's primary cell, not the continuation cell.
1370        let mut s = Screen::new(10, 1);
1371        // '一' (width 2) + combining acute (U+0301, width 0)
1372        s.write_str(
1373            0,
1374            0,
1375            "一\u{0301}",
1376            Color::Default,
1377            Color::Default,
1378            Style::new(),
1379        );
1380
1381        // The combining mark should be in col 0 (the wide char's primary cell),
1382        // not col 1 (the continuation cell).
1383        let cell_0 = s.get(0, 0).unwrap();
1384        assert_eq!(
1385            cell_0.char, '\u{0301}',
1386            "combining mark should be in primary cell"
1387        );
1388        assert!(!cell_0.wide);
1389
1390        // Col 1 should still be the continuation cell
1391        let cell_1 = s.get(0, 1).unwrap();
1392        assert!(
1393            cell_1.wide,
1394            "col 1 should still be a wide continuation cell"
1395        );
1396    }
1397
1398    #[test]
1399    fn test_screen_write_str_wide_char_at_last_col_breaks() {
1400        // "ab一" on a 3-wide screen: 'a' at 0, 'b' at 1, '一' at 2 needs 2-3.
1401        // Since col 3 doesn't exist, '一' should be skipped.
1402        let mut s = Screen::new(3, 1);
1403        s.write_str(0, 0, "ab一", Color::Default, Color::Default, Style::new());
1404        assert_eq!(s.get(0, 0).unwrap().char, 'a');
1405        assert_eq!(s.get(0, 1).unwrap().char, 'b');
1406        assert_eq!(s.get(0, 2).unwrap().char, ' '); // '一' was skipped
1407    }
1408
1409    #[test]
1410    fn test_screen_write_wrapped_wide_char_at_last_col() {
1411        // In wrapped mode, a wide char at the last column should wrap to the
1412        // next line rather than being written as a half-width glyph.
1413        let mut s = Screen::new(3, 3);
1414        s.write_str_wrapped(
1415            0,
1416            0,
1417            "ab一c",
1418            Color::Default,
1419            Color::Default,
1420            Style::new(),
1421            true,
1422        );
1423        // Row 0: "ab" (cols 0-1), '一' doesn't fit at col 2, wraps to row 1
1424        assert_eq!(s.get(0, 0).unwrap().char, 'a');
1425        assert_eq!(s.get(0, 1).unwrap().char, 'b');
1426        assert_eq!(s.get(0, 2).unwrap().char, ' '); // empty (wide char wrapped)
1427        // Row 1: "一" (cols 0-1), then 'c' at col 2
1428        assert_eq!(s.get(1, 0).unwrap().char, '一');
1429        assert!(s.get(1, 1).unwrap().wide);
1430        assert_eq!(s.get(1, 2).unwrap().char, 'c');
1431    }
1432}