Skip to main content

euv_core/render/terminal/
impl.rs

1use super::*;
2
3/// Blank default cell (`' '`, width `1`, default terminal attributes).
4impl Default for TerminalCell {
5    /// Creates a blank space terminal cell.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Blank cell.
10    fn default() -> Self {
11        Self::blank()
12    }
13}
14
15/// Construction and style inspection helpers for `TerminalCell`.
16impl TerminalCell {
17    /// Creates an empty single-column space cell with default attributes.
18    ///
19    /// # Returns
20    ///
21    /// - `Self` - Blank cell.
22    #[must_use]
23    pub const fn blank() -> Self {
24        Self {
25            ch: ' ',
26            width: 1,
27            fg: None,
28            bg: None,
29            bold: false,
30            reverse: false,
31            underline: false,
32        }
33    }
34
35    /// Creates a trailing continuation cell (`width == 0`) paired with a wide character lead cell.
36    ///
37    /// # Arguments
38    ///
39    /// - `Option<Color>` - Inherited foreground color.
40    /// - `Option<Color>` - Inherited background color.
41    /// - `bool` - Inherited bold flag.
42    /// - `bool` - Inherited reverse-video flag.
43    /// - `bool` - Inherited underline flag.
44    ///
45    /// # Returns
46    ///
47    /// - `Self` - Zero-width continuation cell.
48    #[must_use]
49    pub const fn continuation(
50        fg: Option<Color>,
51        bg: Option<Color>,
52        bold: bool,
53        reverse: bool,
54        underline: bool,
55    ) -> Self {
56        Self {
57            ch: '\0',
58            width: 0,
59            fg,
60            bg,
61            bold,
62            reverse,
63            underline,
64        }
65    }
66
67    /// Creates a styled character cell with explicit display width and ANSI flags.
68    ///
69    /// # Arguments
70    ///
71    /// - `char` - Character scalar value.
72    /// - `u8` - Display width (`1` or `2`).
73    /// - `Option<Color>` - Optional foreground color.
74    /// - `Option<Color>` - Optional background color.
75    /// - `bool` - Bold flag.
76    /// - `bool` - Reverse-video flag.
77    /// - `bool` - Underline flag.
78    ///
79    /// # Returns
80    ///
81    /// - `Self` - Constructed styled cell.
82    #[must_use]
83    pub const fn styled(
84        ch: char,
85        width: u8,
86        fg: Option<Color>,
87        bg: Option<Color>,
88        bold: bool,
89        reverse: bool,
90        underline: bool,
91    ) -> Self {
92        Self {
93            ch,
94            width,
95            fg,
96            bg,
97            bold,
98            reverse,
99            underline,
100        }
101    }
102
103    /// Returns the optional 24-bit foreground color.
104    ///
105    /// # Arguments
106    ///
107    /// - `&Self` - Cell reference.
108    ///
109    /// # Returns
110    ///
111    /// - `Option<Color>` - Foreground color when specified.
112    #[must_use]
113    pub const fn fg_color(&self) -> Option<Color> {
114        let Self { fg, .. } = *self;
115        fg
116    }
117
118    /// Returns the optional 24-bit background color.
119    ///
120    /// # Arguments
121    ///
122    /// - `&Self` - Cell reference.
123    ///
124    /// # Returns
125    ///
126    /// - `Option<Color>` - Background color when specified.
127    #[must_use]
128    pub const fn bg_color(&self) -> Option<Color> {
129        let Self { bg, .. } = *self;
130        bg
131    }
132
133    /// Returns `true` when this cell is the trailing half of a wide character.
134    ///
135    /// # Arguments
136    ///
137    /// - `&Self` - Cell reference.
138    ///
139    /// # Returns
140    ///
141    /// - `bool` - `true` iff `width == 0`.
142    #[must_use]
143    pub const fn is_continuation(&self) -> bool {
144        let Self { width, .. } = *self;
145        width == 0
146    }
147
148    /// Returns `true` when this cell is the leading cell of a double-width character.
149    ///
150    /// # Arguments
151    ///
152    /// - `&Self` - Cell reference.
153    ///
154    /// # Returns
155    ///
156    /// - `bool` - `true` iff `width == 2`.
157    #[must_use]
158    pub const fn is_wide_lead(&self) -> bool {
159        let Self { width, .. } = *self;
160        width == 2
161    }
162
163    /// Returns `true` when two cells share identical SGR styling attributes.
164    ///
165    /// # Arguments
166    ///
167    /// - `&Self` - First cell reference.
168    /// - `&Self` - Second cell reference.
169    ///
170    /// # Returns
171    ///
172    /// - `bool` - `true` when foreground, background, bold, reverse, and underline match.
173    #[must_use]
174    pub fn same_style(&self, other: &Self) -> bool {
175        self.fg_color() == other.fg_color()
176            && self.bg_color() == other.bg_color()
177            && self.get_bold() == other.get_bold()
178            && self.get_reverse() == other.get_reverse()
179            && self.get_underline() == other.get_underline()
180    }
181}
182
183/// Grid allocation, wide-char-safe writing, box drawing, and plain-text serialization for `TerminalCellGrid`.
184impl TerminalCellGrid {
185    /// Allocates a blank `cols x rows` terminal cell grid (clamped to at least `1 x 1`).
186    ///
187    /// # Arguments
188    ///
189    /// - `u16` - Column count.
190    /// - `u16` - Row count.
191    ///
192    /// # Returns
193    ///
194    /// - `Self` - Blank grid.
195    #[must_use]
196    pub fn allocate(cols: u16, rows: u16) -> Self {
197        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
198        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
199        let total: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
200        Self {
201            cols: clamped_cols,
202            rows: clamped_rows,
203            cells: vec![TerminalCell::blank(); total],
204        }
205    }
206
207    /// Resizes and clears the grid to `cols x rows`, reusing existing capacity when unchanged.
208    ///
209    /// # Arguments
210    ///
211    /// - `&Self` - Mutable grid.
212    /// - `u16` - Target column count.
213    /// - `u16` - Target row count.
214    pub fn reset(&mut self, cols: u16, rows: u16) {
215        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
216        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
217        let total: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
218        self.set_cols(clamped_cols);
219        self.set_rows(clamped_rows);
220        let cells: &mut Vec<TerminalCell> = self.get_mut_cells();
221        if cells.len() == total {
222            cells.fill(TerminalCell::blank());
223        } else {
224            cells.clear();
225            cells.resize(total, TerminalCell::blank());
226        }
227    }
228
229    /// Returns total number of character cells in the grid.
230    ///
231    /// # Arguments
232    ///
233    /// - `&Self` - Grid reference.
234    ///
235    /// # Returns
236    ///
237    /// - `usize` - Total cell count (`cols * rows`).
238    #[must_use]
239    pub fn total_cells(&self) -> usize {
240        self.get_cells().len()
241    }
242
243    /// Returns the flat vector index for `(col, row)` if within grid bounds.
244    ///
245    /// # Arguments
246    ///
247    /// - `&Self` - Grid reference.
248    /// - `u16` - Zero-based column coordinate.
249    /// - `u16` - Zero-based row coordinate.
250    ///
251    /// # Returns
252    ///
253    /// - `Option<usize>` - Linear cell index if in bounds.
254    #[must_use]
255    fn cell_index(&self, col: u16, row: u16) -> Option<usize> {
256        let cols: u16 = self.get_cols();
257        let rows: u16 = self.get_rows();
258        if col >= cols || row >= rows {
259            return None;
260        }
261        Some((row as usize) * (cols as usize) + (col as usize))
262    }
263
264    /// Reads the `TerminalCell` stored at `(col, row)`.
265    ///
266    /// # Arguments
267    ///
268    /// - `&Self` - Grid reference.
269    /// - `u16` - Zero-based column coordinate.
270    /// - `u16` - Zero-based row coordinate.
271    ///
272    /// # Returns
273    ///
274    /// - `Option<TerminalCell>` - Cell copy if within bounds.
275    #[must_use]
276    pub fn cell(&self, col: u16, row: u16) -> Option<TerminalCell> {
277        let idx: usize = self.cell_index(col, row)?;
278        self.get_cells().get(idx).copied()
279    }
280
281    /// Clears any wide-character partner occupying `(col, row)` before overwriting that coordinate.
282    ///
283    /// # Arguments
284    ///
285    /// - `&Self` - Mutable grid.
286    /// - `u16` - Zero-based column coordinate.
287    /// - `u16` - Zero-based row coordinate.
288    fn clear_wide_conflict(&mut self, col: u16, row: u16) {
289        let Some(existing) = self.cell(col, row) else {
290            return;
291        };
292        if existing.is_continuation() && col > 0 {
293            if let Some(lead_idx) = self.cell_index(col - 1, row)
294                && let Some(slot) = self.get_mut_cells().get_mut(lead_idx)
295            {
296                *slot = TerminalCell::blank();
297            }
298            if let Some(cur_idx) = self.cell_index(col, row)
299                && let Some(slot) = self.get_mut_cells().get_mut(cur_idx)
300            {
301                *slot = TerminalCell::blank();
302            }
303        } else if existing.is_wide_lead() {
304            if let Some(trail_idx) = self.cell_index(col.saturating_add(1), row)
305                && let Some(slot) = self.get_mut_cells().get_mut(trail_idx)
306            {
307                *slot = TerminalCell::blank();
308            }
309            if let Some(cur_idx) = self.cell_index(col, row)
310                && let Some(slot) = self.get_mut_cells().get_mut(cur_idx)
311            {
312                *slot = TerminalCell::blank();
313            }
314        }
315    }
316
317    /// Writes a single narrow or wide `TerminalCell` at `(col, row)`, cleanly clearing overwritten wide neighbors and clipping cleanly at the right edge.
318    ///
319    /// # Arguments
320    ///
321    /// - `&Self` - Mutable grid.
322    /// - `u16` - Zero-based column coordinate.
323    /// - `u16` - Zero-based row coordinate.
324    /// - `TerminalCell` - Cell value to write.
325    ///
326    /// # Returns
327    ///
328    /// - `u16` - Number of columns consumed (`0`, `1`, or `2`).
329    pub fn put_cell(&mut self, col: u16, row: u16, cell: TerminalCell) -> u16 {
330        let cols: u16 = self.get_cols();
331        let rows: u16 = self.get_rows();
332        if col >= cols || row >= rows || cell.is_continuation() {
333            return 0;
334        }
335        if cell.is_wide_lead() {
336            if col.saturating_add(1) >= cols {
337                self.clear_wide_conflict(col, row);
338                if let Some(idx) = self.cell_index(col, row)
339                    && let Some(slot) = self.get_mut_cells().get_mut(idx)
340                {
341                    *slot = TerminalCell::blank();
342                }
343                return 0;
344            }
345            self.clear_wide_conflict(col, row);
346            self.clear_wide_conflict(col + 1, row);
347            if let Some(lead_idx) = self.cell_index(col, row)
348                && let Some(slot) = self.get_mut_cells().get_mut(lead_idx)
349            {
350                *slot = cell;
351            }
352            if let Some(trail_idx) = self.cell_index(col + 1, row)
353                && let Some(slot) = self.get_mut_cells().get_mut(trail_idx)
354            {
355                *slot = TerminalCell::continuation(
356                    cell.fg_color(),
357                    cell.bg_color(),
358                    cell.get_bold(),
359                    cell.get_reverse(),
360                    cell.get_underline(),
361                );
362            }
363            return 2;
364        }
365        self.clear_wide_conflict(col, row);
366        if let Some(idx) = self.cell_index(col, row)
367            && let Some(slot) = self.get_mut_cells().get_mut(idx)
368        {
369            *slot = cell;
370        }
371        1
372    }
373
374    /// Writes UTF-8 `text` onto `row` starting at `col` within `max_cols`, honoring CJK double-width glyphs, zero-width combining marks, and clean edge truncation.
375    ///
376    /// # Arguments
377    ///
378    /// - `&Self` - Mutable grid.
379    /// - `u16` - Starting zero-based column coordinate.
380    /// - `u16` - Target zero-based row coordinate.
381    /// - `u16` - Maximum display columns allowed for this write.
382    /// - `&str` - UTF-8 text slice to write.
383    /// - `TerminalCell` - Style template supplying foreground, background, bold, reverse, and underline flags.
384    ///
385    /// # Returns
386    ///
387    /// - `u16` - Total display columns written.
388    pub fn write_styled_text(
389        &mut self,
390        col: u16,
391        row: u16,
392        max_cols: u16,
393        text: &str,
394        style_cell: TerminalCell,
395    ) -> u16 {
396        let cols: u16 = self.get_cols();
397        let rows: u16 = self.get_rows();
398        if col >= cols || row >= rows || max_cols == 0 {
399            return 0;
400        }
401        let limit: u16 = max_cols.min(cols.saturating_sub(col));
402        let mut used: u16 = 0;
403        for ch in text.chars() {
404            if ch == '\n' || ch == '\r' {
405                break;
406            }
407            let width: u8 = terminal_char_width(ch);
408            if width == 0 {
409                continue;
410            }
411            let w_u16: u16 = width as u16;
412            if used.saturating_add(w_u16) > limit {
413                break;
414            }
415            let cell: TerminalCell = TerminalCell::styled(
416                ch,
417                width,
418                style_cell.fg_color(),
419                style_cell.bg_color(),
420                style_cell.get_bold(),
421                style_cell.get_reverse(),
422                style_cell.get_underline(),
423            );
424            let consumed: u16 = self.put_cell(col + used, row, cell);
425            if consumed == 0 {
426                break;
427            }
428            used = used.saturating_add(consumed);
429        }
430        used
431    }
432
433    /// Writes UTF-8 `text` onto `row` starting at `col` using default terminal style within `max_cols`.
434    ///
435    /// # Arguments
436    ///
437    /// - `&Self` - Mutable grid.
438    /// - `u16` - Starting zero-based column coordinate.
439    /// - `u16` - Target zero-based row coordinate.
440    /// - `u16` - Maximum display columns allowed.
441    /// - `&str` - UTF-8 text slice to write.
442    ///
443    /// # Returns
444    ///
445    /// - `u16` - Total display columns written.
446    pub fn write_text(&mut self, col: u16, row: u16, max_cols: u16, text: &str) -> u16 {
447        self.write_styled_text(col, row, max_cols, text, TerminalCell::blank())
448    }
449
450    /// Draws a Unicode box-drawing border frame covering `[x, x + w) x [y, y + h)`.
451    ///
452    /// # Arguments
453    ///
454    /// - `&Self` - Mutable grid.
455    /// - `u16` - Left column coordinate.
456    /// - `u16` - Top row coordinate.
457    /// - `u16` - Box width in columns.
458    /// - `u16` - Box height in rows.
459    /// - `TerminalCell` - Style template supplying foreground, background, bold, and reverse flags.
460    pub fn draw_box(&mut self, x: u16, y: u16, w: u16, h: u16, style_cell: TerminalCell) {
461        if w < 2 || h < 2 {
462            return;
463        }
464        let right: u16 = x.saturating_add(w - 1);
465        let bottom: u16 = y.saturating_add(h - 1);
466        let fg: Option<Color> = style_cell.fg_color();
467        let bg: Option<Color> = style_cell.bg_color();
468        let bold: bool = style_cell.get_bold();
469        let rev: bool = style_cell.get_reverse();
470        let ul: bool = style_cell.get_underline();
471        let _: u16 = self.put_cell(
472            x,
473            y,
474            TerminalCell::styled(TERMINAL_BOX_TOP_LEFT, 1, fg, bg, bold, rev, ul),
475        );
476        let _: u16 = self.put_cell(
477            right,
478            y,
479            TerminalCell::styled(TERMINAL_BOX_TOP_RIGHT, 1, fg, bg, bold, rev, ul),
480        );
481        let _: u16 = self.put_cell(
482            x,
483            bottom,
484            TerminalCell::styled(TERMINAL_BOX_BOTTOM_LEFT, 1, fg, bg, bold, rev, ul),
485        );
486        let _: u16 = self.put_cell(
487            right,
488            bottom,
489            TerminalCell::styled(TERMINAL_BOX_BOTTOM_RIGHT, 1, fg, bg, bold, rev, ul),
490        );
491        let horiz: TerminalCell =
492            TerminalCell::styled(TERMINAL_BOX_HORIZONTAL, 1, fg, bg, bold, rev, ul);
493        let mut cx: u16 = x + 1;
494        while cx < right {
495            let _: u16 = self.put_cell(cx, y, horiz);
496            let _: u16 = self.put_cell(cx, bottom, horiz);
497            cx += 1;
498        }
499        let vert: TerminalCell =
500            TerminalCell::styled(TERMINAL_BOX_VERTICAL, 1, fg, bg, bold, rev, ul);
501        let mut cy: u16 = y + 1;
502        while cy < bottom {
503            let _: u16 = self.put_cell(x, cy, vert);
504            let _: u16 = self.put_cell(right, cy, vert);
505            cy += 1;
506        }
507    }
508
509    /// Serializes the grid into clean UTF-8 lines with zero ANSI escape sequences for piped CLI stdout.
510    ///
511    /// # Arguments
512    ///
513    /// - `&Self` - Grid reference.
514    ///
515    /// # Returns
516    ///
517    /// - `String` - Plain-text UTF-8 representation trimmed of trailing whitespace per line and trailing blank lines.
518    #[must_use]
519    pub fn to_plain_text(&self) -> String {
520        let cols: usize = self.get_cols() as usize;
521        let rows: usize = self.get_rows() as usize;
522        let cells: &[TerminalCell] = self.get_cells().as_slice();
523        let mut lines: Vec<String> = Vec::with_capacity(rows);
524        for row in 0..rows {
525            let start: usize = row * cols;
526            let end: usize = (start + cols).min(cells.len());
527            let mut line: String = String::with_capacity(cols);
528            for cell in &cells[start..end] {
529                if cell.is_continuation() {
530                    continue;
531                }
532                let ch: char = cell.get_ch();
533                if ch != '\x1b' && ch != '\0' {
534                    line.push(ch);
535                }
536            }
537            let trimmed_len: usize = line.trim_end().len();
538            line.truncate(trimmed_len);
539            lines.push(line);
540        }
541        while let Some(last) = lines.last() {
542            if last.is_empty() {
543                let _: Option<String> = lines.pop();
544            } else {
545                break;
546            }
547        }
548        lines.join("\n")
549    }
550}
551
552/// Session lifecycle entry and idempotent ANSI state restoration for `TerminalSessionGuard`.
553impl TerminalSessionGuard {
554    /// Builds the escape sequence required to enter the configured interactive terminal modes.
555    ///
556    /// # Arguments
557    ///
558    /// - `bool` - Whether to enter the alternate screen buffer.
559    /// - `bool` - Whether to hide the terminal cursor.
560    /// - `bool` - Whether to enable raw bracketed input mode.
561    ///
562    /// # Returns
563    ///
564    /// - `String` - Concatenated ANSI enter sequence.
565    #[must_use]
566    pub fn build_enter_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
567        let mut out: String = String::new();
568        if alt_screen {
569            out.push_str(ANSI_ENTER_ALT_SCREEN);
570        }
571        if cursor_hidden {
572            out.push_str(ANSI_HIDE_CURSOR);
573        }
574        if raw_mode {
575            out.push_str(ANSI_ENTER_RAW_MODES);
576        }
577        out
578    }
579
580    /// Builds the escape sequence required to cleanly restore terminal state upon exit or unwind.
581    ///
582    /// # Arguments
583    ///
584    /// - `bool` - Whether alternate screen mode was entered.
585    /// - `bool` - Whether cursor visibility was hidden.
586    /// - `bool` - Whether raw input modes were enabled.
587    ///
588    /// # Returns
589    ///
590    /// - `String` - Concatenated ANSI restoration sequence.
591    #[must_use]
592    pub fn build_restore_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
593        let mut out: String = String::from(ANSI_RESET_STYLE);
594        if raw_mode {
595            out.push_str(ANSI_LEAVE_RAW_MODES);
596        }
597        if cursor_hidden {
598            out.push_str(ANSI_SHOW_CURSOR);
599        }
600        if alt_screen {
601            out.push_str(ANSI_LEAVE_ALT_SCREEN);
602        }
603        out
604    }
605
606    /// Enters an interactive terminal session writing enter/restore sequences to an optional capture buffer.
607    ///
608    /// # Arguments
609    ///
610    /// - `bool` - Enter alternate screen buffer.
611    /// - `bool` - Hide terminal cursor.
612    /// - `bool` - Enable raw input tracking modes.
613    /// - `Option<Rc<RefCell<String>>>` - Optional capture buffer for deterministic testing or virtual PTYs.
614    ///
615    /// # Returns
616    ///
617    /// - `Self` - Active RAII session guard.
618    #[must_use]
619    pub fn enter_captured(
620        alt_screen: bool,
621        cursor_hidden: bool,
622        raw_mode: bool,
623        sink: Option<Rc<RefCell<String>>>,
624    ) -> Self {
625        let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
626        if let Some(buf) = sink.as_ref()
627            && let Ok(mut guard) = buf.try_borrow_mut()
628        {
629            guard.push_str(&enter_seq);
630        }
631        Self {
632            alt_screen,
633            cursor_hidden,
634            raw_mode,
635            restored: false,
636            write_to_stdout: false,
637            sink,
638        }
639    }
640
641    /// Enters an interactive terminal session flushing enter and restore sequences directly to stdout on native targets.
642    ///
643    /// # Arguments
644    ///
645    /// - `bool` - Enter alternate screen buffer.
646    /// - `bool` - Hide terminal cursor.
647    /// - `bool` - Enable raw input tracking modes.
648    ///
649    /// # Returns
650    ///
651    /// - `Self` - Active RAII session guard bound to stdout.
652    #[must_use]
653    pub fn enter_stdout(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> Self {
654        let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
655        #[cfg(not(target_arch = "wasm32"))]
656        {
657            let mut stdout: io::Stdout = io::stdout();
658            let _: io::Result<()> = stdout.write_all(enter_seq.as_bytes());
659            let _: io::Result<()> = stdout.flush();
660        }
661        #[cfg(target_arch = "wasm32")]
662        let _: &String = &enter_seq;
663        Self {
664            alt_screen,
665            cursor_hidden,
666            raw_mode,
667            restored: false,
668            write_to_stdout: true,
669            sink: None,
670        }
671    }
672
673    /// Restores terminal state immediately if not already restored and returns the emitted ANSI sequence.
674    ///
675    /// # Arguments
676    ///
677    /// - `&Self` - Mutable session guard.
678    ///
679    /// # Returns
680    ///
681    /// - `String` - Restoration escape sequence emitted (empty if already restored).
682    pub fn restore_now(&mut self) -> String {
683        if self.get_restored() {
684            return String::new();
685        }
686        self.set_restored(true);
687        let seq: String = Self::build_restore_sequence(
688            self.get_alt_screen(),
689            self.get_cursor_hidden(),
690            self.get_raw_mode(),
691        );
692        let write_stdout: bool = self.get_write_to_stdout();
693        let Self { sink, .. } = self;
694        if let Some(buf) = sink.as_ref()
695            && let Ok(mut guard) = buf.try_borrow_mut()
696        {
697            guard.push_str(&seq);
698        }
699        #[cfg(not(target_arch = "wasm32"))]
700        if write_stdout {
701            let mut stdout: io::Stdout = io::stdout();
702            let _: io::Result<()> = stdout.write_all(seq.as_bytes());
703            let _: io::Result<()> = stdout.flush();
704        }
705        #[cfg(target_arch = "wasm32")]
706        let _: bool = write_stdout;
707        seq
708    }
709}
710
711/// Guaranteed RAII restoration of cursor, raw mode, and alternate screen on normal exit or panic unwind.
712impl Drop for TerminalSessionGuard {
713    /// Restores terminal modes automatically when the guard leaves scope.
714    ///
715    /// # Arguments
716    ///
717    /// - `&Self` - Mutable session guard being dropped.
718    fn drop(&mut self) {
719        let _: String = self.restore_now();
720    }
721}
722
723/// Semantic scene projection, keyboard focus navigation, and incremental ANSI cell-diffing for `TerminalRenderer`.
724impl TerminalRenderer {
725    /// Creates a fresh `TerminalRenderer` with empty diff history.
726    ///
727    /// # Returns
728    ///
729    /// - `Self` - Initialized terminal renderer.
730    #[must_use]
731    pub fn new() -> Self {
732        Self::default()
733    }
734
735    /// Clears cached previous frame state, forcing the next interactive render to emit a full synchronization frame.
736    ///
737    /// # Arguments
738    ///
739    /// - `&Self` - Mutable terminal renderer.
740    pub fn invalidate(&mut self) {
741        let Self { previous, .. } = self;
742        *previous = None;
743    }
744
745    /// Projects `tree` into a `cols x rows` character grid and emits either incremental ANSI TUI output or zero-ANSI static plain text.
746    ///
747    /// # Arguments
748    ///
749    /// - `&Self` - Mutable terminal renderer.
750    /// - `&SceneTree` - Retained UI scene tree to project.
751    /// - `u16` - Terminal viewport width in columns.
752    /// - `u16` - Terminal viewport height in rows.
753    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
754    ///
755    /// # Returns
756    ///
757    /// - `(String, TerminalDiffStats)` - Rendered UTF-8 terminal payload and cell-diff telemetry.
758    pub fn render_tree(
759        &mut self,
760        tree: &SceneTree,
761        cols: u16,
762        rows: u16,
763        mode: TerminalRenderMode,
764    ) -> (String, TerminalDiffStats) {
765        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
766        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
767        self.get_mut_current().reset(clamped_cols, clamped_rows);
768        let focused: Option<NodeId> = tree.get_focus().focused_node();
769        let mut cursor_y: u16 = 0;
770        let root_region: TerminalRegion =
771            TerminalRegion::new(0, clamped_cols, clamped_rows, focused);
772        self.project_node(tree, tree.get_root(), root_region, &mut cursor_y);
773        let total_cells: usize = self.get_current().total_cells();
774        let prev_missing: bool = {
775            let Self { previous, .. } = self;
776            previous.is_none()
777        };
778        let resized_or_first: bool = prev_missing
779            || self.get_last_cols() != clamped_cols
780            || self.get_last_rows() != clamped_rows;
781        let (output, stats): (String, TerminalDiffStats) = match mode {
782            TerminalRenderMode::StaticPlainText => {
783                let changed: usize = self.count_changed_cells(resized_or_first);
784                let plain: String = self.get_current().to_plain_text();
785                let bytes: usize = plain.len();
786                let diff_stats: TerminalDiffStats =
787                    TerminalDiffStats::new(total_cells, changed, bytes, false, resized_or_first);
788                (plain, diff_stats)
789            }
790            TerminalRenderMode::InteractiveTui => {
791                if resized_or_first {
792                    let full_out: String = self.encode_full_frame();
793                    let bytes: usize = full_out.len();
794                    let diff_stats: TerminalDiffStats =
795                        TerminalDiffStats::new(total_cells, total_cells, bytes, false, true);
796                    (full_out, diff_stats)
797                } else {
798                    self.encode_diff_frame()
799                }
800            }
801        };
802        let snapshot: TerminalCellGrid = self.get_current().clone();
803        let Self { previous, .. } = self;
804        *previous = Some(snapshot);
805        self.set_last_cols(clamped_cols);
806        self.set_last_rows(clamped_rows);
807        let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
808        self.set_frames_rendered(next_frames);
809        (output, stats)
810    }
811
812    /// Processes a terminal keyboard event (`Tab`, `Shift+Tab`, arrows, `Enter`, `Escape`, `Ctrl+C`) against `tree`.
813    ///
814    /// # Arguments
815    ///
816    /// - `&Self` - Mutable terminal renderer.
817    /// - `&mut SceneTree` - Retained UI scene tree to update focus, scroll, or activation on.
818    /// - `KeyEvent` - Normalized keyboard event.
819    ///
820    /// # Returns
821    ///
822    /// - `TerminalNavAction` - Resulting focus, scroll, activation, or exit action.
823    pub fn handle_key(&mut self, tree: &mut SceneTree, key: KeyEvent) -> TerminalNavAction {
824        let code: KeyCode = key.get_code();
825        let mods: Modifiers = key.get_modifiers();
826        if code == KeyCode::Escape
827            || (mods.get_ctrl()
828                && matches!(code, KeyCode::Character('c') | KeyCode::Character('C')))
829        {
830            self.set_exit_requested(true);
831            return TerminalNavAction::ExitRequested;
832        }
833        if code == KeyCode::Tab {
834            let focusables: Vec<NodeId> = Self::collect_focusables(tree);
835            if focusables.is_empty() {
836                return TerminalNavAction::Ignored;
837            }
838            let current: Option<NodeId> = tree.get_focus().focused_node();
839            let next_target: NodeId = match current
840                .and_then(|cur: NodeId| focusables.iter().position(|id: &NodeId| *id == cur))
841            {
842                Some(idx) => {
843                    let next_idx: usize = if mods.get_shift() {
844                        if idx == 0 {
845                            focusables.len() - 1
846                        } else {
847                            idx - 1
848                        }
849                    } else {
850                        (idx + 1) % focusables.len()
851                    };
852                    focusables[next_idx]
853                }
854                None => {
855                    if mods.get_shift() {
856                        focusables[focusables.len() - 1]
857                    } else {
858                        focusables[0]
859                    }
860                }
861            };
862            let callbacks: Vec<(UiEventHandler, UiEvent)> = tree.update_focus(Some(next_target));
863            for (handler, ev) in callbacks.into_iter() {
864                if let Ok(mut cb) = handler.try_borrow_mut() {
865                    cb(&ev);
866                }
867            }
868            return TerminalNavAction::FocusMoved(next_target);
869        }
870        if code == KeyCode::ArrowDown || code == KeyCode::ArrowUp {
871            let delta_rows: i16 = if code == KeyCode::ArrowDown { 1 } else { -1 };
872            if let Some(scroll_id) = Self::find_first_scroll_view(tree) {
873                let current_y: f32 = tree
874                    .get_node(scroll_id)
875                    .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
876                    .unwrap_or(0.0);
877                let next_y: f32 =
878                    (current_y + (delta_rows as f32) * TERMINAL_SCROLL_STEP_PX).max(0.0);
879                tree.set_scroll_offset(scroll_id, Point::new(0.0, next_y));
880                return TerminalNavAction::Scrolled(delta_rows);
881            }
882            return TerminalNavAction::Ignored;
883        }
884        if code == KeyCode::Enter {
885            if let Some(target) = tree.get_focus().focused_node() {
886                let click_kind: UiEventKind = UiEventKind::Click(Point::default());
887                let handler_opt: Option<UiEventHandler> = tree
888                    .get_node(target)
889                    .and_then(|node: &SceneNode| node.get_handlers().handler_for(&click_kind));
890                if let Some(handler) = handler_opt
891                    && let Ok(mut cb) = handler.try_borrow_mut()
892                {
893                    let click_ev: UiEvent = UiEvent::new(target, click_kind);
894                    cb(&click_ev);
895                }
896                return TerminalNavAction::Activated(target);
897            }
898            return TerminalNavAction::Ignored;
899        }
900        TerminalNavAction::Ignored
901    }
902
903    /// Collects all visible focusable or clickable node handles in pre-order traversal.
904    ///
905    /// # Arguments
906    ///
907    /// - `&SceneTree` - Retained UI scene tree.
908    ///
909    /// # Returns
910    ///
911    /// - `Vec<NodeId>` - Ordered focus ring candidates.
912    #[must_use]
913    fn collect_focusables(tree: &SceneTree) -> Vec<NodeId> {
914        let mut out: Vec<NodeId> = Vec::new();
915        let mut stack: Vec<NodeId> = vec![tree.get_root()];
916        while let Some(id) = stack.pop() {
917            let Some(node) = tree.get_node(id) else {
918                continue;
919            };
920            if node.style_ref().get_layout().get_display() == Display::None
921                || node.style_ref().get_paint().get_opacity() <= 0.0
922            {
923                continue;
924            }
925            if Self::is_focusable_or_interactive(node) {
926                out.push(id);
927            }
928            for child in node.get_children().iter().rev().copied() {
929                stack.push(child);
930            }
931        }
932        out
933    }
934
935    /// Finds the first visible `NodeKind::ScrollView` node in pre-order traversal.
936    ///
937    /// # Arguments
938    ///
939    /// - `&SceneTree` - Retained UI scene tree.
940    ///
941    /// # Returns
942    ///
943    /// - `Option<NodeId>` - First visible scroll container handle.
944    #[must_use]
945    fn find_first_scroll_view(tree: &SceneTree) -> Option<NodeId> {
946        let mut stack: Vec<NodeId> = vec![tree.get_root()];
947        while let Some(id) = stack.pop() {
948            let Some(node) = tree.get_node(id) else {
949                continue;
950            };
951            if node.style_ref().get_layout().get_display() == Display::None {
952                continue;
953            }
954            if matches!(node.get_kind(), NodeKind::ScrollView) {
955                return Some(id);
956            }
957            for child in node.get_children().iter().rev().copied() {
958                stack.push(child);
959            }
960        }
961        None
962    }
963
964    /// Returns `true` when `node` should participate in terminal focus and clickable affordances.
965    ///
966    /// # Arguments
967    ///
968    /// - `&SceneNode` - Candidate scene node.
969    ///
970    /// # Returns
971    ///
972    /// - `bool` - Whether the node is focusable or interactive.
973    #[must_use]
974    fn is_focusable_or_interactive(node: &SceneNode) -> bool {
975        node.get_interaction().get_focusable()
976            || matches!(node.get_kind(), NodeKind::Input(_))
977            || Self::is_clickable_node(node)
978    }
979
980    /// Returns `true` when `node` acts as a clickable button or interactive trigger.
981    ///
982    /// # Arguments
983    ///
984    /// - `&SceneNode` - Candidate scene node.
985    ///
986    /// # Returns
987    ///
988    /// - `bool` - Whether the node has click semantics.
989    #[must_use]
990    fn is_clickable_node(node: &SceneNode) -> bool {
991        node.get_handlers()
992            .handler_for(&UiEventKind::Click(Point::default()))
993            .is_some()
994            || node.style_ref().get_paint().get_cursor() == CursorIcon::Pointer
995            || node
996                .a11y_props()
997                .is_some_and(|a: A11yProps| a.get_role() == A11yRole::Button)
998    }
999
1000    /// Collects direct/descendant display label text for a clickable container button.
1001    ///
1002    /// # Arguments
1003    ///
1004    /// - `&SceneTree` - Retained UI scene tree.
1005    /// - `NodeId` - Button container node identifier.
1006    ///
1007    /// # Returns
1008    ///
1009    /// - `String` - Resolved button caption text.
1010    #[must_use]
1011    fn collect_button_label(tree: &SceneTree, node_id: NodeId) -> String {
1012        let Some(node) = tree.get_node(node_id) else {
1013            return String::new();
1014        };
1015        let mut parts: Vec<String> = Vec::new();
1016        let mut stack: Vec<NodeId> = node.get_children().iter().rev().copied().collect();
1017        while let Some(cid) = stack.pop() {
1018            let Some(child) = tree.get_node(cid) else {
1019                continue;
1020            };
1021            if child.style_ref().get_layout().get_display() == Display::None {
1022                continue;
1023            }
1024            if let NodeKind::Text(text) = child.get_kind() {
1025                let trimmed: &str = text.trim();
1026                if !trimmed.is_empty() {
1027                    parts.push(trimmed.to_string());
1028                }
1029            }
1030            for grand in child.get_children().iter().rev().copied() {
1031                stack.push(grand);
1032            }
1033        }
1034        if !parts.is_empty() {
1035            return parts.join(" ");
1036        }
1037        node.a11y_props()
1038            .map(|a: A11yProps| a.get_label().clone())
1039            .unwrap_or_default()
1040    }
1041
1042    /// Projects a single scene node subtree into the current `TerminalCellGrid` using terminal character coordinates directly.
1043    ///
1044    /// # Arguments
1045    ///
1046    /// - `&Self` - Mutable terminal renderer.
1047    /// - `&SceneTree` - Retained scene tree.
1048    /// - `NodeId` - Target node handle to project.
1049    /// - `TerminalRegion` - Active character-grid region and focus context.
1050    /// - `&mut u16` - Mutable current row cursor advanced as content is laid out.
1051    fn project_node(
1052        &mut self,
1053        tree: &SceneTree,
1054        node_id: NodeId,
1055        region: TerminalRegion,
1056        y: &mut u16,
1057    ) {
1058        let x: u16 = region.get_x();
1059        let avail_w: u16 = region.get_width();
1060        let max_y: u16 = region.get_max_y();
1061        let focused: Option<NodeId> = region.get_focused();
1062        if *y >= max_y || avail_w == 0 {
1063            return;
1064        }
1065        let Some(node) = tree.get_node(node_id) else {
1066            return;
1067        };
1068        let style: &Style = node.style_ref();
1069        let layout: LayoutStyle = style.get_layout();
1070        let paint: PaintStyle = style.get_paint();
1071        let text_style: TextStyle = style.get_text();
1072        if layout.get_display() == Display::None || paint.get_opacity() <= 0.0 {
1073            return;
1074        }
1075        let is_focused: bool = focused == Some(node_id) || node.get_interaction().get_focused();
1076        let is_bold: bool = matches!(
1077            text_style.get_weight(),
1078            FontWeight::SemiBold | FontWeight::Bold
1079        );
1080        let fg: Option<Color> = Some(text_style.get_color());
1081        let bg: Option<Color> = paint.background_color();
1082        let template: TerminalCell = TerminalCell::styled(
1083            ' ',
1084            1,
1085            fg,
1086            bg,
1087            is_bold,
1088            is_focused,
1089            text_style.get_underline(),
1090        );
1091        match node.get_kind() {
1092            NodeKind::Text(content) => {
1093                let display_str: String = if Self::is_clickable_node(node) {
1094                    if is_focused {
1095                        format!("> [ {content} ]")
1096                    } else {
1097                        format!("[ {content} ]")
1098                    }
1099                } else {
1100                    content.clone()
1101                };
1102                self.write_wrapped_text(region, y, &display_str, template);
1103            }
1104            NodeKind::Input(inp) => {
1105                let inner: String = if inp.get_value().is_empty() {
1106                    inp.get_placeholder().clone()
1107                } else if inp.get_password() {
1108                    let count: usize = inp.get_value().chars().count();
1109                    "*".repeat(count)
1110                } else {
1111                    inp.get_value().clone()
1112                };
1113                let formatted: String = if is_focused {
1114                    format!("> [ {inner}| ]")
1115                } else {
1116                    format!("[ {inner} ]")
1117                };
1118                let _: u16 = self
1119                    .get_mut_current()
1120                    .write_styled_text(x, *y, avail_w, &formatted, template);
1121                *y = y.saturating_add(1);
1122            }
1123            NodeKind::Image(img) => {
1124                let alt: String = node
1125                    .a11y_props()
1126                    .map(|a: A11yProps| a.get_label().clone())
1127                    .filter(|s: &String| !s.is_empty())
1128                    .map(|lbl: String| format!("{TERMINAL_IMAGE_FALLBACK_PREFIX}{lbl}]"))
1129                    .unwrap_or_else(|| {
1130                        format!(
1131                            "{TERMINAL_IMAGE_DIM_PREFIX}{}x{}]",
1132                            img.get_width(),
1133                            img.get_height()
1134                        )
1135                    });
1136                let _: u16 = self
1137                    .get_mut_current()
1138                    .write_styled_text(x, *y, avail_w, &alt, template);
1139                *y = y.saturating_add(1);
1140            }
1141            NodeKind::Canvas => {
1142                let alt: String = node
1143                    .a11y_props()
1144                    .map(|a: A11yProps| a.get_label().clone())
1145                    .filter(|s: &String| !s.is_empty())
1146                    .map(|lbl: String| format!("{TERMINAL_CANVAS_FALLBACK_PREFIX}{lbl}]"))
1147                    .unwrap_or_else(|| TERMINAL_CANVAS_FALLBACK.to_string());
1148                let _: u16 = self
1149                    .get_mut_current()
1150                    .write_styled_text(x, *y, avail_w, &alt, template);
1151                *y = y.saturating_add(1);
1152            }
1153            NodeKind::Fragment => {
1154                for child_id in node.get_children().iter().copied() {
1155                    if *y >= max_y {
1156                        break;
1157                    }
1158                    self.project_node(tree, child_id, region, y);
1159                }
1160            }
1161            NodeKind::ScrollView => {
1162                self.project_scroll_view(tree, node_id, region, y);
1163            }
1164            NodeKind::View | NodeKind::Portal => {
1165                let is_root: bool = node_id == tree.get_root();
1166                if !is_root && Self::is_clickable_node(node) {
1167                    let caption: String = Self::collect_button_label(tree, node_id);
1168                    if !caption.is_empty() {
1169                        let formatted: String = if is_focused {
1170                            format!("> [ {caption} ]")
1171                        } else {
1172                            format!("[ {caption} ]")
1173                        };
1174                        let _: u16 = self
1175                            .get_mut_current()
1176                            .write_styled_text(x, *y, avail_w, &formatted, template);
1177                        *y = y.saturating_add(1);
1178                        return;
1179                    }
1180                }
1181                let has_border: bool = !is_root
1182                    && (paint.get_border().get_width() > 0.0
1183                        || matches!(node.get_kind(), NodeKind::Portal))
1184                    && avail_w >= 4
1185                    && max_y.saturating_sub(*y) >= 3;
1186                if has_border {
1187                    let top_y: u16 = *y;
1188                    let inner_region: TerminalRegion = TerminalRegion::new(
1189                        x.saturating_add(1),
1190                        avail_w.saturating_sub(2),
1191                        max_y.saturating_sub(1),
1192                        focused,
1193                    );
1194                    let mut child_y: u16 = top_y.saturating_add(1);
1195                    self.project_children_flow(tree, node, inner_region, &mut child_y);
1196                    let box_h: u16 = child_y
1197                        .saturating_sub(top_y)
1198                        .saturating_add(1)
1199                        .max(3)
1200                        .min(max_y.saturating_sub(top_y));
1201                    let border_cell: TerminalCell = TerminalCell::styled(
1202                        ' ',
1203                        1,
1204                        Some(paint.get_border().get_color()),
1205                        bg,
1206                        false,
1207                        is_focused,
1208                        false,
1209                    );
1210                    self.get_mut_current()
1211                        .draw_box(x, top_y, avail_w, box_h, border_cell);
1212                    *y = top_y.saturating_add(box_h);
1213                } else {
1214                    self.project_children_flow(tree, node, region, y);
1215                }
1216            }
1217        }
1218    }
1219
1220    /// Projects children of a container respecting row, column, and grid directions directly in character columns.
1221    ///
1222    /// # Arguments
1223    ///
1224    /// - `&Self` - Mutable terminal renderer.
1225    /// - `&SceneTree` - Retained scene tree.
1226    /// - `&SceneNode` - Container scene node.
1227    /// - `TerminalRegion` - Active character-grid region and focus context.
1228    /// - `&mut u16` - Mutable current row cursor.
1229    fn project_children_flow(
1230        &mut self,
1231        tree: &SceneTree,
1232        node: &SceneNode,
1233        region: TerminalRegion,
1234        y: &mut u16,
1235    ) {
1236        let x: u16 = region.get_x();
1237        let avail_w: u16 = region.get_width();
1238        let max_y: u16 = region.get_max_y();
1239        let focused: Option<NodeId> = region.get_focused();
1240        let visible_children: Vec<NodeId> = node
1241            .get_children()
1242            .iter()
1243            .copied()
1244            .filter(|cid: &NodeId| {
1245                tree.get_node(*cid).is_some_and(|c: &SceneNode| {
1246                    c.style_ref().get_layout().get_display() != Display::None
1247                        && c.style_ref().get_paint().get_opacity() > 0.0
1248                })
1249            })
1250            .collect();
1251        if visible_children.is_empty() {
1252            return;
1253        }
1254        let layout: LayoutStyle = node.style_ref().get_layout();
1255        let is_row: bool = matches!(
1256            layout.get_flex_direction(),
1257            FlexDirection::Row | FlexDirection::RowReverse
1258        ) && layout.get_display() == Display::Flex;
1259        if is_row && visible_children.len() > 1 && avail_w >= (visible_children.len() as u16) * 2 {
1260            let count: u16 = visible_children.len() as u16;
1261            let total_gaps: u16 = count.saturating_sub(1).saturating_mul(TERMINAL_ROW_GAP);
1262            let slot_w: u16 = avail_w.saturating_sub(total_gaps) / count;
1263            if slot_w >= 2 {
1264                let row_start_y: u16 = *y;
1265                let mut max_child_end: u16 = row_start_y;
1266                for (idx, child_id) in visible_children.iter().copied().enumerate() {
1267                    let cx: u16 = x.saturating_add((idx as u16).saturating_mul(slot_w + 1));
1268                    let rem_w: u16 = avail_w.saturating_sub(cx.saturating_sub(x));
1269                    let col_w: u16 = if idx + 1 == visible_children.len() {
1270                        rem_w
1271                    } else {
1272                        slot_w.min(rem_w)
1273                    };
1274                    let mut cy: u16 = row_start_y;
1275                    let child_region: TerminalRegion =
1276                        TerminalRegion::new(cx, col_w, max_y, focused);
1277                    self.project_node(tree, child_id, child_region, &mut cy);
1278                    if cy > max_child_end {
1279                        max_child_end = cy;
1280                    }
1281                }
1282                *y = max_child_end;
1283                return;
1284            }
1285        }
1286        for child_id in visible_children.into_iter() {
1287            if *y >= max_y {
1288                break;
1289            }
1290            self.project_node(tree, child_id, region, y);
1291        }
1292    }
1293
1294    /// Projects a `NodeKind::ScrollView` container with row-level scroll skipping and an ASCII/Unicode scrollbar rail.
1295    ///
1296    /// # Arguments
1297    ///
1298    /// - `&Self` - Mutable terminal renderer.
1299    /// - `&SceneTree` - Retained scene tree.
1300    /// - `NodeId` - Scroll container node handle.
1301    /// - `TerminalRegion` - Active character-grid region and focus context.
1302    /// - `&mut u16` - Mutable current row cursor.
1303    fn project_scroll_view(
1304        &mut self,
1305        tree: &SceneTree,
1306        node_id: NodeId,
1307        region: TerminalRegion,
1308        y: &mut u16,
1309    ) {
1310        let x: u16 = region.get_x();
1311        let avail_w: u16 = region.get_width();
1312        let max_y: u16 = region.get_max_y();
1313        let focused: Option<NodeId> = region.get_focused();
1314        let Some(node) = tree.get_node(node_id) else {
1315            return;
1316        };
1317        let visible_children: Vec<NodeId> = node
1318            .get_children()
1319            .iter()
1320            .copied()
1321            .filter(|cid: &NodeId| {
1322                tree.get_node(*cid).is_some_and(|c: &SceneNode| {
1323                    c.style_ref().get_layout().get_display() != Display::None
1324                        && c.style_ref().get_paint().get_opacity() > 0.0
1325                })
1326            })
1327            .collect();
1328        let avail_h: u16 = max_y.saturating_sub(*y);
1329        if avail_h == 0 || visible_children.is_empty() {
1330            return;
1331        }
1332        let scroll_y: f32 = node.get_layout_box().get_scroll_offset().get_y().max(0.0);
1333        let skip_items: usize = ((scroll_y / TERMINAL_SCROLL_STEP_PX).floor() as usize)
1334            .min(visible_children.len().saturating_sub(1));
1335        let needs_rail: bool = visible_children.len() > (avail_h as usize) && avail_w >= 3;
1336        let inner_w: u16 = if needs_rail {
1337            avail_w.saturating_sub(1)
1338        } else {
1339            avail_w
1340        };
1341        let child_region: TerminalRegion = TerminalRegion::new(x, inner_w, max_y, focused);
1342        let start_y: u16 = *y;
1343        for child_id in visible_children.iter().skip(skip_items).copied() {
1344            if *y >= max_y {
1345                break;
1346            }
1347            self.project_node(tree, child_id, child_region, y);
1348        }
1349        if needs_rail {
1350            let rail_x: u16 = x.saturating_add(inner_w);
1351            let total_items: usize = visible_children.len().max(1);
1352            let thumb_offset: u16 = ((skip_items * (avail_h as usize)) / total_items)
1353                .min((avail_h - 1) as usize) as u16;
1354            for offset in 0..avail_h {
1355                let glyph: char = if offset == thumb_offset {
1356                    TERMINAL_SCROLL_THUMB
1357                } else {
1358                    TERMINAL_SCROLL_TRACK
1359                };
1360                let _: u16 = self.get_mut_current().put_cell(
1361                    rail_x,
1362                    start_y.saturating_add(offset),
1363                    TerminalCell::styled(glyph, 1, None, None, false, false, false),
1364                );
1365            }
1366        }
1367    }
1368
1369    /// Writes `text` wrapped across consecutive terminal rows within `region` without breaking CJK double-width cells.
1370    ///
1371    /// # Arguments
1372    ///
1373    /// - `&Self` - Mutable terminal renderer.
1374    /// - `TerminalRegion` - Active character-grid region.
1375    /// - `&mut u16` - Mutable current row cursor.
1376    /// - `&str` - UTF-8 text to wrap.
1377    /// - `TerminalCell` - Style template cell.
1378    fn write_wrapped_text(
1379        &mut self,
1380        region: TerminalRegion,
1381        y: &mut u16,
1382        text: &str,
1383        template: TerminalCell,
1384    ) {
1385        let x: u16 = region.get_x();
1386        let avail_w: u16 = region.get_width();
1387        let max_y: u16 = region.get_max_y();
1388        if *y >= max_y || avail_w == 0 {
1389            return;
1390        }
1391        let mut wrote_any_line: bool = false;
1392        for raw_line in text.split('\n') {
1393            if *y >= max_y {
1394                break;
1395            }
1396            if raw_line.is_empty() {
1397                *y = y.saturating_add(1);
1398                wrote_any_line = true;
1399                continue;
1400            }
1401            let mut cur_col: u16 = 0;
1402            for ch in raw_line.chars() {
1403                if ch == '\r' {
1404                    continue;
1405                }
1406                let width: u8 = terminal_char_width(ch);
1407                if width == 0 {
1408                    continue;
1409                }
1410                let w_u16: u16 = width as u16;
1411                if w_u16 > avail_w {
1412                    continue;
1413                }
1414                if cur_col.saturating_add(w_u16) > avail_w {
1415                    *y = y.saturating_add(1);
1416                    if *y >= max_y {
1417                        return;
1418                    }
1419                    cur_col = 0;
1420                }
1421                let cell: TerminalCell = TerminalCell::styled(
1422                    ch,
1423                    width,
1424                    template.fg_color(),
1425                    template.bg_color(),
1426                    template.get_bold(),
1427                    template.get_reverse(),
1428                    template.get_underline(),
1429                );
1430                let consumed: u16 = self.get_mut_current().put_cell(x + cur_col, *y, cell);
1431                cur_col = cur_col.saturating_add(consumed);
1432            }
1433            *y = y.saturating_add(1);
1434            wrote_any_line = true;
1435        }
1436        if !wrote_any_line {
1437            *y = y.saturating_add(1);
1438        }
1439    }
1440
1441    /// Counts how many cells differ between `current` and `previous`.
1442    ///
1443    /// # Arguments
1444    ///
1445    /// - `&Self` - Terminal renderer reference.
1446    /// - `bool` - Whether the entire frame is treated as changed (first frame or resize).
1447    ///
1448    /// # Returns
1449    ///
1450    /// - `usize` - Number of differing cells.
1451    #[must_use]
1452    fn count_changed_cells(&self, full_sync: bool) -> usize {
1453        if full_sync {
1454            return self.get_current().total_cells();
1455        }
1456        let Self {
1457            previous, current, ..
1458        } = self;
1459        let Some(prev_grid) = previous.as_ref() else {
1460            return current.total_cells();
1461        };
1462        let cur_cells: &[TerminalCell] = current.get_cells().as_slice();
1463        let prev_cells: &[TerminalCell] = prev_grid.get_cells().as_slice();
1464        if cur_cells.len() != prev_cells.len() {
1465            return cur_cells.len();
1466        }
1467        cur_cells
1468            .iter()
1469            .zip(prev_cells.iter())
1470            .filter(|(a, b): &(&TerminalCell, &TerminalCell)| a != b)
1471            .count()
1472    }
1473
1474    /// Encodes the full current grid into a single ANSI clear-and-draw payload.
1475    ///
1476    /// # Arguments
1477    ///
1478    /// - `&Self` - Terminal renderer reference.
1479    ///
1480    /// # Returns
1481    ///
1482    /// - `String` - Full-sync ANSI output payload.
1483    #[must_use]
1484    fn encode_full_frame(&self) -> String {
1485        let grid: &TerminalCellGrid = self.get_current();
1486        let cols: u16 = grid.get_cols();
1487        let rows: u16 = grid.get_rows();
1488        let mut out: String = String::with_capacity(grid.total_cells().saturating_mul(2));
1489        out.push_str(ANSI_CLEAR_AND_HOME);
1490        let mut active_style: Option<TerminalCell> = None;
1491        for row in 0..rows {
1492            append_cursor_move(&mut out, 0, row);
1493            for col in 0..cols {
1494                let Some(cell) = grid.cell(col, row) else {
1495                    continue;
1496                };
1497                if cell.is_continuation() {
1498                    continue;
1499                }
1500                let style_changed: bool = match active_style {
1501                    Some(prev) => !prev.same_style(&cell),
1502                    None => true,
1503                };
1504                if style_changed {
1505                    append_sgr_style(
1506                        &mut out,
1507                        cell.fg_color(),
1508                        cell.bg_color(),
1509                        cell.get_bold(),
1510                        cell.get_reverse(),
1511                        cell.get_underline(),
1512                    );
1513                    active_style = Some(cell);
1514                }
1515                out.push(cell.get_ch());
1516            }
1517        }
1518        out.push_str(ANSI_RESET_STYLE);
1519        out
1520    }
1521
1522    /// Encodes only cells changed relative to `previous`, returning an empty string (`0` bytes) when idle.
1523    ///
1524    /// # Arguments
1525    ///
1526    /// - `&Self` - Terminal renderer reference.
1527    ///
1528    /// # Returns
1529    ///
1530    /// - `(String, TerminalDiffStats)` - Incremental ANSI diff payload and diff telemetry.
1531    #[must_use]
1532    fn encode_diff_frame(&self) -> (String, TerminalDiffStats) {
1533        let Self {
1534            previous, current, ..
1535        } = self;
1536        let total_cells: usize = current.total_cells();
1537        let Some(prev_grid) = previous.as_ref() else {
1538            let full: String = self.encode_full_frame();
1539            let len: usize = full.len();
1540            return (
1541                full,
1542                TerminalDiffStats::new(total_cells, total_cells, len, false, true),
1543            );
1544        };
1545        let cols: u16 = current.get_cols();
1546        let rows: u16 = current.get_rows();
1547        let mut out: String = String::new();
1548        let mut changed_cells: usize = 0;
1549        let mut active_style: Option<TerminalCell> = None;
1550        let mut cursor_pos: Option<(u16, u16)> = None;
1551        for row in 0..rows {
1552            let mut col: u16 = 0;
1553            while col < cols {
1554                let Some(cur_cell) = current.cell(col, row) else {
1555                    col += 1;
1556                    continue;
1557                };
1558                let Some(prev_cell) = prev_grid.cell(col, row) else {
1559                    col += 1;
1560                    continue;
1561                };
1562                if cur_cell.is_continuation() {
1563                    col += 1;
1564                    continue;
1565                }
1566                let mut cell_dirty: bool = cur_cell != prev_cell;
1567                if cur_cell.is_wide_lead() && col + 1 < cols {
1568                    let cur_trail: Option<TerminalCell> = current.cell(col + 1, row);
1569                    let prev_trail: Option<TerminalCell> = prev_grid.cell(col + 1, row);
1570                    if cur_trail != prev_trail {
1571                        cell_dirty = true;
1572                    }
1573                }
1574                if !cell_dirty {
1575                    col += cur_cell.get_width().max(1) as u16;
1576                    continue;
1577                }
1578                let step: u16 = cur_cell.get_width().max(1) as u16;
1579                changed_cells = changed_cells.saturating_add(step as usize);
1580                if cursor_pos != Some((col, row)) {
1581                    append_cursor_move(&mut out, col, row);
1582                }
1583                let style_changed: bool = match active_style {
1584                    Some(prev) => !prev.same_style(&cur_cell),
1585                    None => true,
1586                };
1587                if style_changed {
1588                    append_sgr_style(
1589                        &mut out,
1590                        cur_cell.fg_color(),
1591                        cur_cell.bg_color(),
1592                        cur_cell.get_bold(),
1593                        cur_cell.get_reverse(),
1594                        cur_cell.get_underline(),
1595                    );
1596                    active_style = Some(cur_cell);
1597                }
1598                out.push(cur_cell.get_ch());
1599                cursor_pos = Some((col.saturating_add(step), row));
1600                col = col.saturating_add(step);
1601            }
1602        }
1603        if changed_cells == 0 {
1604            return (
1605                String::new(),
1606                TerminalDiffStats::new(total_cells, 0, 0, true, false),
1607            );
1608        }
1609        out.push_str(ANSI_RESET_STYLE);
1610        let output_bytes: usize = out.len();
1611        (
1612            out,
1613            TerminalDiffStats::new(total_cells, changed_cells, output_bytes, false, false),
1614        )
1615    }
1616}