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, grapheme-cluster storage, 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            tail_len: 0,
33            tail_utf8: [0; TERMINAL_CELL_TAIL_CAPACITY],
34        }
35    }
36
37    /// Creates a trailing continuation cell (`width == 0`) paired with a wide character lead cell.
38    ///
39    /// # Arguments
40    ///
41    /// - `Option<Color>` - Inherited foreground color.
42    /// - `Option<Color>` - Inherited background color.
43    /// - `bool` - Inherited bold flag.
44    /// - `bool` - Inherited reverse-video flag.
45    /// - `bool` - Inherited underline flag.
46    ///
47    /// # Returns
48    ///
49    /// - `Self` - Zero-width continuation cell.
50    #[must_use]
51    pub const fn continuation(
52        fg: Option<Color>,
53        bg: Option<Color>,
54        bold: bool,
55        reverse: bool,
56        underline: bool,
57    ) -> Self {
58        Self {
59            ch: '\0',
60            width: 0,
61            fg,
62            bg,
63            bold,
64            reverse,
65            underline,
66            tail_len: 0,
67            tail_utf8: [0; TERMINAL_CELL_TAIL_CAPACITY],
68        }
69    }
70
71    /// Creates a styled single-scalar character cell with explicit display width and ANSI flags.
72    ///
73    /// # Arguments
74    ///
75    /// - `char` - Character scalar value.
76    /// - `u8` - Display width (`1` or `2`).
77    /// - `Option<Color>` - Optional foreground color.
78    /// - `Option<Color>` - Optional background color.
79    /// - `bool` - Bold flag.
80    /// - `bool` - Reverse-video flag.
81    /// - `bool` - Underline flag.
82    ///
83    /// # Returns
84    ///
85    /// - `Self` - Constructed styled cell.
86    #[must_use]
87    pub const fn styled(
88        ch: char,
89        width: u8,
90        fg: Option<Color>,
91        bg: Option<Color>,
92        bold: bool,
93        reverse: bool,
94        underline: bool,
95    ) -> Self {
96        Self {
97            ch,
98            width,
99            fg,
100            bg,
101            bold,
102            reverse,
103            underline,
104            tail_len: 0,
105            tail_utf8: [0; TERMINAL_CELL_TAIL_CAPACITY],
106        }
107    }
108
109    /// Creates a styled cell from an Extended Grapheme Cluster (retaining combining marks, variation selectors, and ZWJ emoji inline without heap allocation).
110    ///
111    /// # Arguments
112    ///
113    /// - `&str` - Non-empty Extended Grapheme Cluster slice.
114    /// - `u8` - Precomputed display width (`1` or `2`).
115    /// - `Self` - Style template supplying colors and SGR emphasis flags.
116    ///
117    /// # Returns
118    ///
119    /// - `Self` - Constructed grapheme cell.
120    #[must_use]
121    pub fn from_grapheme(cluster: &str, width: u8, style: Self) -> Self {
122        let mut iter: Chars<'_> = cluster.chars();
123        let Some(first) = iter.next() else {
124            return Self::blank();
125        };
126        let tail_str: &str = &cluster[first.len_utf8()..];
127        let mut tail_utf8: [u8; TERMINAL_CELL_TAIL_CAPACITY] = [0; TERMINAL_CELL_TAIL_CAPACITY];
128        let mut tail_len: usize = 0;
129        for ch in tail_str.chars() {
130            let mut enc: [u8; 4] = [0; 4];
131            let encoded: &str = ch.encode_utf8(&mut enc);
132            let bytes: &[u8] = encoded.as_bytes();
133            if tail_len + bytes.len() > TERMINAL_CELL_TAIL_CAPACITY {
134                break;
135            }
136            tail_utf8[tail_len..(tail_len + bytes.len())].copy_from_slice(bytes);
137            tail_len += bytes.len();
138        }
139        Self {
140            ch: first,
141            width,
142            fg: style.fg_color(),
143            bg: style.bg_color(),
144            bold: style.get_bold(),
145            reverse: style.get_reverse(),
146            underline: style.get_underline(),
147            tail_len: tail_len as u8,
148            tail_utf8,
149        }
150    }
151
152    /// Returns the inline UTF-8 tail bytes for combining/ZWJ scalars attached to `ch`.
153    ///
154    /// # Arguments
155    ///
156    /// - `&Self` - Cell reference.
157    ///
158    /// # Returns
159    ///
160    /// - `&[u8]` - Valid UTF-8 tail byte slice (empty for single-scalar cells).
161    #[must_use]
162    pub fn tail_bytes(&self) -> &[u8] {
163        let Self {
164            tail_len,
165            tail_utf8,
166            ..
167        } = self;
168        let len: usize = (*tail_len as usize).min(TERMINAL_CELL_TAIL_CAPACITY);
169        &tail_utf8[..len]
170    }
171
172    /// Appends the complete Extended Grapheme Cluster stored in this cell into `out`.
173    ///
174    /// # Arguments
175    ///
176    /// - `&Self` - Cell reference.
177    /// - `&mut String` - Destination UTF-8 output buffer.
178    pub fn push_grapheme_to(&self, out: &mut String) {
179        let ch: char = self.get_ch();
180        if ch == '\x1b' || ch == '\0' {
181            return;
182        }
183        out.push(ch);
184        let tail: &[u8] = self.tail_bytes();
185        if !tail.is_empty()
186            && let Ok(text) = from_utf8(tail)
187        {
188            out.push_str(text);
189        }
190    }
191
192    /// Returns the optional 24-bit foreground color.
193    ///
194    /// # Arguments
195    ///
196    /// - `&Self` - Cell reference.
197    ///
198    /// # Returns
199    ///
200    /// - `Option<Color>` - Foreground color when specified.
201    #[must_use]
202    pub const fn fg_color(&self) -> Option<Color> {
203        let Self { fg, .. } = *self;
204        fg
205    }
206
207    /// Returns the optional 24-bit background color.
208    ///
209    /// # Arguments
210    ///
211    /// - `&Self` - Cell reference.
212    ///
213    /// # Returns
214    ///
215    /// - `Option<Color>` - Background color when specified.
216    #[must_use]
217    pub const fn bg_color(&self) -> Option<Color> {
218        let Self { bg, .. } = *self;
219        bg
220    }
221
222    /// Returns `true` when this cell is the trailing half of a wide character.
223    ///
224    /// # Arguments
225    ///
226    /// - `&Self` - Cell reference.
227    ///
228    /// # Returns
229    ///
230    /// - `bool` - `true` iff `width == 0`.
231    #[must_use]
232    pub const fn is_continuation(&self) -> bool {
233        let Self { width, .. } = *self;
234        width == 0
235    }
236
237    /// Returns `true` when this cell is the leading cell of a double-width character.
238    ///
239    /// # Arguments
240    ///
241    /// - `&Self` - Cell reference.
242    ///
243    /// # Returns
244    ///
245    /// - `bool` - `true` iff `width == 2`.
246    #[must_use]
247    pub const fn is_wide_lead(&self) -> bool {
248        let Self { width, .. } = *self;
249        width == 2
250    }
251
252    /// Returns `true` when two cells share identical SGR styling attributes.
253    ///
254    /// # Arguments
255    ///
256    /// - `&Self` - First cell reference.
257    /// - `&Self` - Second cell reference.
258    ///
259    /// # Returns
260    ///
261    /// - `bool` - `true` when foreground, background, bold, reverse, and underline match.
262    #[must_use]
263    pub fn same_style(&self, other: &Self) -> bool {
264        self.fg_color() == other.fg_color()
265            && self.bg_color() == other.bg_color()
266            && self.get_bold() == other.get_bold()
267            && self.get_reverse() == other.get_reverse()
268            && self.get_underline() == other.get_underline()
269    }
270}
271
272/// Accessors for `TerminalFrameFingerprint`.
273impl TerminalFrameFingerprint {
274    /// Returns the focused scene node handle recorded in this fingerprint.
275    ///
276    /// # Arguments
277    ///
278    /// - `&Self` - Fingerprint reference.
279    ///
280    /// # Returns
281    ///
282    /// - `Option<NodeId>` - Focused node identifier, if any.
283    #[must_use]
284    pub const fn focused_node(&self) -> Option<NodeId> {
285        let Self { focused, .. } = *self;
286        focused
287    }
288}
289
290/// Accessors and constructors for `TerminalWriteResult`.
291impl TerminalWriteResult {
292    /// Returns the optional write error message when `status != CliWriteStatus::Written`.
293    ///
294    /// # Arguments
295    ///
296    /// - `&Self` - Write result reference.
297    ///
298    /// # Returns
299    ///
300    /// - `Option<&str>` - Error description if present.
301    #[must_use]
302    pub fn error_message(&self) -> Option<&str> {
303        let Self { error_message, .. } = self;
304        error_message.as_deref()
305    }
306}
307
308/// Grid allocation, grapheme-aware wide-char-safe writing, row hashing, box drawing, and plain-text serialization for `TerminalCellGrid`.
309impl TerminalCellGrid {
310    /// Allocates a blank `cols x rows` terminal cell grid (clamped to at least `1 x 1`).
311    ///
312    /// # Arguments
313    ///
314    /// - `u16` - Column count.
315    /// - `u16` - Row count.
316    ///
317    /// # Returns
318    ///
319    /// - `Self` - Blank grid with precomputed blank row hashes.
320    #[must_use]
321    pub fn allocate(cols: u16, rows: u16) -> Self {
322        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
323        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
324        let total: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
325        let cells: Vec<TerminalCell> = vec![TerminalCell::blank(); total];
326        let blank_hash: u64 = hash_terminal_row(&cells[..(clamped_cols as usize)]);
327        Self {
328            cols: clamped_cols,
329            rows: clamped_rows,
330            cells,
331            row_hashes: vec![blank_hash; clamped_rows as usize],
332            dirty_rows: vec![false; clamped_rows as usize],
333            blank_row_hash: blank_hash,
334        }
335    }
336
337    /// Resizes and clears the grid to `cols x rows`, reusing existing allocation capacity when dimensions match.
338    ///
339    /// # Arguments
340    ///
341    /// - `&Self` - Mutable grid.
342    /// - `u16` - Target column count.
343    /// - `u16` - Target row count.
344    pub fn reset(&mut self, cols: u16, rows: u16) {
345        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
346        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
347        let total: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
348        let rows_usize: usize = clamped_rows as usize;
349        let cols_usize: usize = clamped_cols as usize;
350        let same_shape: bool = self.get_cols() == clamped_cols
351            && self.get_rows() == clamped_rows
352            && self.get_cells().len() == total
353            && self.get_row_hashes().len() == rows_usize
354            && self.get_dirty_rows().len() == rows_usize;
355        if same_shape {
356            let blank_hash: u64 = self.get_blank_row_hash();
357            let Self {
358                cells,
359                row_hashes,
360                dirty_rows,
361                ..
362            } = self;
363            for row in 0..rows_usize {
364                if dirty_rows[row] {
365                    let start: usize = row * cols_usize;
366                    cells[start..(start + cols_usize)].fill(TerminalCell::blank());
367                    row_hashes[row] = blank_hash;
368                    dirty_rows[row] = false;
369                }
370            }
371            return;
372        }
373        let cols_changed: bool = self.get_cols() != clamped_cols || self.get_cells().is_empty();
374        self.set_cols(clamped_cols);
375        self.set_rows(clamped_rows);
376        let cells: &mut Vec<TerminalCell> = self.get_mut_cells();
377        if cells.len() == total {
378            cells.fill(TerminalCell::blank());
379        } else {
380            cells.clear();
381            cells.resize(total, TerminalCell::blank());
382        }
383        let blank_hash: u64 = if cols_changed {
384            let computed: u64 = hash_terminal_row(&self.get_cells()[..cols_usize]);
385            self.set_blank_row_hash(computed);
386            computed
387        } else {
388            self.get_blank_row_hash()
389        };
390        let row_hashes: &mut Vec<u64> = self.get_mut_row_hashes();
391        if row_hashes.len() == rows_usize {
392            row_hashes.fill(blank_hash);
393        } else {
394            row_hashes.clear();
395            row_hashes.resize(rows_usize, blank_hash);
396        }
397        let dirty_rows: &mut Vec<bool> = self.get_mut_dirty_rows();
398        if dirty_rows.len() == rows_usize {
399            dirty_rows.fill(false);
400        } else {
401            dirty_rows.clear();
402            dirty_rows.resize(rows_usize, false);
403        }
404    }
405
406    /// Recomputes FNV-1a row hashes only for rows written during the current projection pass.
407    ///
408    /// # Arguments
409    ///
410    /// - `&Self` - Mutable grid.
411    pub fn finalize_row_hashes(&mut self) {
412        let cols: usize = self.get_cols() as usize;
413        let rows: usize = self.get_rows() as usize;
414        let Self {
415            cells,
416            row_hashes,
417            dirty_rows,
418            ..
419        } = self;
420        for row in 0..rows {
421            if !dirty_rows.get(row).copied().unwrap_or(false) {
422                continue;
423            }
424            let start: usize = row * cols;
425            let end: usize = (start + cols).min(cells.len());
426            if let Some(slot) = row_hashes.get_mut(row) {
427                *slot = hash_terminal_row(&cells[start..end]);
428            }
429        }
430    }
431
432    /// Returns total number of character cells in the grid.
433    ///
434    /// # Arguments
435    ///
436    /// - `&Self` - Grid reference.
437    ///
438    /// # Returns
439    ///
440    /// - `usize` - Total cell count (`cols * rows`).
441    #[must_use]
442    pub fn total_cells(&self) -> usize {
443        self.get_cells().len()
444    }
445
446    /// Returns the flat vector index for `(col, row)` if within grid bounds.
447    ///
448    /// # Arguments
449    ///
450    /// - `&Self` - Grid reference.
451    /// - `u16` - Zero-based column coordinate.
452    /// - `u16` - Zero-based row coordinate.
453    ///
454    /// # Returns
455    ///
456    /// - `Option<usize>` - Linear cell index if in bounds.
457    #[must_use]
458    fn cell_index(&self, col: u16, row: u16) -> Option<usize> {
459        let cols: u16 = self.get_cols();
460        let rows: u16 = self.get_rows();
461        if col >= cols || row >= rows {
462            return None;
463        }
464        Some((row as usize) * (cols as usize) + (col as usize))
465    }
466
467    /// Marks `row` as modified for incremental hash recomputation.
468    ///
469    /// # Arguments
470    ///
471    /// - `&Self` - Mutable grid.
472    /// - `u16` - Zero-based row coordinate.
473    fn mark_row_dirty(&mut self, row: u16) {
474        if let Some(flag) = self.get_mut_dirty_rows().get_mut(row as usize) {
475            *flag = true;
476        }
477    }
478
479    /// Reads the `TerminalCell` stored at `(col, row)`.
480    ///
481    /// # Arguments
482    ///
483    /// - `&Self` - Grid reference.
484    /// - `u16` - Zero-based column coordinate.
485    /// - `u16` - Zero-based row coordinate.
486    ///
487    /// # Returns
488    ///
489    /// - `Option<TerminalCell>` - Cell copy if within bounds.
490    #[must_use]
491    pub fn cell(&self, col: u16, row: u16) -> Option<TerminalCell> {
492        let idx: usize = self.cell_index(col, row)?;
493        self.get_cells().get(idx).copied()
494    }
495
496    /// Clears both cells of any wide-character pair occupying `(col, row)` before overwriting that coordinate.
497    ///
498    /// # Arguments
499    ///
500    /// - `&Self` - Mutable grid.
501    /// - `u16` - Zero-based column coordinate.
502    /// - `u16` - Zero-based row coordinate.
503    fn clear_wide_conflict(&mut self, col: u16, row: u16) {
504        let Some(existing) = self.cell(col, row) else {
505            return;
506        };
507        if existing.is_continuation() && col > 0 {
508            if let Some(lead_idx) = self.cell_index(col - 1, row)
509                && let Some(slot) = self.get_mut_cells().get_mut(lead_idx)
510            {
511                *slot = TerminalCell::blank();
512            }
513            if let Some(cur_idx) = self.cell_index(col, row)
514                && let Some(slot) = self.get_mut_cells().get_mut(cur_idx)
515            {
516                *slot = TerminalCell::blank();
517            }
518            self.mark_row_dirty(row);
519        } else if existing.is_wide_lead() {
520            if let Some(trail_idx) = self.cell_index(col.saturating_add(1), row)
521                && let Some(slot) = self.get_mut_cells().get_mut(trail_idx)
522            {
523                *slot = TerminalCell::blank();
524            }
525            if let Some(cur_idx) = self.cell_index(col, row)
526                && let Some(slot) = self.get_mut_cells().get_mut(cur_idx)
527            {
528                *slot = TerminalCell::blank();
529            }
530            self.mark_row_dirty(row);
531        }
532    }
533
534    /// Writes a single narrow or wide `TerminalCell` at `(col, row)`, cleanly clearing overwritten wide neighbors and clipping cleanly at the right edge.
535    ///
536    /// # Arguments
537    ///
538    /// - `&Self` - Mutable grid.
539    /// - `u16` - Zero-based column coordinate.
540    /// - `u16` - Zero-based row coordinate.
541    /// - `TerminalCell` - Cell value to write.
542    ///
543    /// # Returns
544    ///
545    /// - `u16` - Number of columns consumed (`0`, `1`, or `2`).
546    pub fn put_cell(&mut self, col: u16, row: u16, cell: TerminalCell) -> u16 {
547        let cols: u16 = self.get_cols();
548        let rows: u16 = self.get_rows();
549        if col >= cols || row >= rows || cell.is_continuation() {
550            return 0;
551        }
552        if cell.is_wide_lead() {
553            if col.saturating_add(1) >= cols {
554                self.clear_wide_conflict(col, row);
555                if let Some(idx) = self.cell_index(col, row)
556                    && let Some(slot) = self.get_mut_cells().get_mut(idx)
557                {
558                    *slot = TerminalCell::blank();
559                }
560                self.mark_row_dirty(row);
561                return 0;
562            }
563            self.clear_wide_conflict(col, row);
564            self.clear_wide_conflict(col + 1, row);
565            if let Some(lead_idx) = self.cell_index(col, row)
566                && let Some(slot) = self.get_mut_cells().get_mut(lead_idx)
567            {
568                *slot = cell;
569            }
570            if let Some(trail_idx) = self.cell_index(col + 1, row)
571                && let Some(slot) = self.get_mut_cells().get_mut(trail_idx)
572            {
573                *slot = TerminalCell::continuation(
574                    cell.fg_color(),
575                    cell.bg_color(),
576                    cell.get_bold(),
577                    cell.get_reverse(),
578                    cell.get_underline(),
579                );
580            }
581            self.mark_row_dirty(row);
582            return 2;
583        }
584        self.clear_wide_conflict(col, row);
585        if let Some(idx) = self.cell_index(col, row)
586            && let Some(slot) = self.get_mut_cells().get_mut(idx)
587        {
588            *slot = cell;
589        }
590        self.mark_row_dirty(row);
591        1
592    }
593
594    /// Writes a printable ASCII slice directly into `row` starting at `col`, avoiding grapheme segmentation while preserving wide-character cleanup.
595    ///
596    /// # Arguments
597    ///
598    /// - `&Self` - Mutable grid.
599    /// - `u16` - Starting zero-based column coordinate.
600    /// - `u16` - Target zero-based row coordinate.
601    /// - `&[u8]` - Printable ASCII byte slice (`0x20..=0x7E`, already truncated to fit row width).
602    /// - `TerminalCell` - Style template supplying colors and SGR emphasis flags.
603    ///
604    /// # Returns
605    ///
606    /// - `u16` - Number of columns written.
607    fn write_printable_ascii_run(
608        &mut self,
609        col: u16,
610        row: u16,
611        bytes: &[u8],
612        style_cell: TerminalCell,
613    ) -> u16 {
614        let cols: usize = self.get_cols() as usize;
615        let rows: usize = self.get_rows() as usize;
616        let col_usize: usize = col as usize;
617        let row_usize: usize = row as usize;
618        if col_usize >= cols || row_usize >= rows || bytes.is_empty() {
619            return 0;
620        }
621        let write_len: usize = bytes.len().min(cols - col_usize);
622        let row_start: usize = row_usize * cols;
623        let mut base: TerminalCell = TerminalCell::styled(
624            ' ',
625            1,
626            style_cell.fg_color(),
627            style_cell.bg_color(),
628            style_cell.get_bold(),
629            style_cell.get_reverse(),
630            style_cell.get_underline(),
631        );
632        let Self {
633            cells, dirty_rows, ..
634        } = self;
635        let row_slice: &mut [TerminalCell] = &mut cells[row_start..(row_start + cols)];
636        for (offset, byte) in bytes[..write_len].iter().copied().enumerate() {
637            let idx: usize = col_usize + offset;
638            let existing_w: u8 = row_slice[idx].get_width();
639            if existing_w == 0 && idx > 0 {
640                row_slice[idx - 1] = TerminalCell::blank();
641            } else if existing_w == 2 && idx + 1 < cols {
642                row_slice[idx + 1] = TerminalCell::blank();
643            }
644            base.set_ch(byte as char);
645            row_slice[idx] = base;
646        }
647        if let Some(flag) = dirty_rows.get_mut(row_usize) {
648            *flag = true;
649        }
650        write_len as u16
651    }
652
653    /// Writes UTF-8 `text` onto `row` starting at `col` within `max_cols`, preserving Extended Grapheme Clusters (CJK wide glyphs, combining marks, ZWJ emoji) and clean right-edge truncation.
654    ///
655    /// # Arguments
656    ///
657    /// - `&Self` - Mutable grid.
658    /// - `u16` - Starting zero-based column coordinate.
659    /// - `u16` - Target zero-based row coordinate.
660    /// - `u16` - Maximum display columns allowed for this write.
661    /// - `&str` - UTF-8 text slice to write.
662    /// - `TerminalCell` - Style template supplying foreground, background, bold, reverse, and underline flags.
663    ///
664    /// # Returns
665    ///
666    /// - `u16` - Total display columns written.
667    pub fn write_styled_text(
668        &mut self,
669        col: u16,
670        row: u16,
671        max_cols: u16,
672        text: &str,
673        style_cell: TerminalCell,
674    ) -> u16 {
675        let cols: u16 = self.get_cols();
676        let rows: u16 = self.get_rows();
677        if col >= cols || row >= rows || max_cols == 0 {
678            return 0;
679        }
680        let limit: u16 = max_cols.min(cols.saturating_sub(col));
681        let raw_bytes: &[u8] = text.as_bytes();
682        let check_len: usize = raw_bytes.len().min(limit as usize);
683        if text.is_ascii()
684            && raw_bytes[..check_len]
685                .iter()
686                .all(|b: &u8| (0x20..=0x7E).contains(b))
687        {
688            return self.write_printable_ascii_run(col, row, &raw_bytes[..check_len], style_cell);
689        }
690        let mut used: u16 = 0;
691        let mut rest: &str = text;
692        while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
693            rest = next_rest;
694            if cluster.starts_with('\n') || cluster.starts_with('\r') {
695                break;
696            }
697            let width: u8 = grapheme_display_width(cluster);
698            if width == 0 {
699                continue;
700            }
701            let w_u16: u16 = width as u16;
702            if used.saturating_add(w_u16) > limit {
703                break;
704            }
705            let cell: TerminalCell = TerminalCell::from_grapheme(cluster, width, style_cell);
706            let consumed: u16 = self.put_cell(col + used, row, cell);
707            if consumed == 0 {
708                break;
709            }
710            used = used.saturating_add(consumed);
711        }
712        used
713    }
714
715    /// Writes UTF-8 `text` onto `row` starting at `col` using default terminal style within `max_cols`.
716    ///
717    /// # Arguments
718    ///
719    /// - `&Self` - Mutable grid.
720    /// - `u16` - Starting zero-based column coordinate.
721    /// - `u16` - Target zero-based row coordinate.
722    /// - `u16` - Maximum display columns allowed.
723    /// - `&str` - UTF-8 text slice to write.
724    ///
725    /// # Returns
726    ///
727    /// - `u16` - Total display columns written.
728    pub fn write_text(&mut self, col: u16, row: u16, max_cols: u16, text: &str) -> u16 {
729        self.write_styled_text(col, row, max_cols, text, TerminalCell::blank())
730    }
731
732    /// Draws a Unicode box-drawing border frame covering `[x, x + w) x [y, y + h)`.
733    ///
734    /// # Arguments
735    ///
736    /// - `&Self` - Mutable grid.
737    /// - `u16` - Left column coordinate.
738    /// - `u16` - Top row coordinate.
739    /// - `u16` - Box width in columns.
740    /// - `u16` - Box height in rows.
741    /// - `TerminalCell` - Style template supplying foreground, background, bold, and reverse flags.
742    pub fn draw_box(&mut self, x: u16, y: u16, w: u16, h: u16, style_cell: TerminalCell) {
743        if w < 2 || h < 2 {
744            return;
745        }
746        let right: u16 = x.saturating_add(w - 1);
747        let bottom: u16 = y.saturating_add(h - 1);
748        let fg: Option<Color> = style_cell.fg_color();
749        let bg: Option<Color> = style_cell.bg_color();
750        let bold: bool = style_cell.get_bold();
751        let rev: bool = style_cell.get_reverse();
752        let ul: bool = style_cell.get_underline();
753        let _: u16 = self.put_cell(
754            x,
755            y,
756            TerminalCell::styled(TERMINAL_BOX_TOP_LEFT, 1, fg, bg, bold, rev, ul),
757        );
758        let _: u16 = self.put_cell(
759            right,
760            y,
761            TerminalCell::styled(TERMINAL_BOX_TOP_RIGHT, 1, fg, bg, bold, rev, ul),
762        );
763        let _: u16 = self.put_cell(
764            x,
765            bottom,
766            TerminalCell::styled(TERMINAL_BOX_BOTTOM_LEFT, 1, fg, bg, bold, rev, ul),
767        );
768        let _: u16 = self.put_cell(
769            right,
770            bottom,
771            TerminalCell::styled(TERMINAL_BOX_BOTTOM_RIGHT, 1, fg, bg, bold, rev, ul),
772        );
773        let horiz: TerminalCell =
774            TerminalCell::styled(TERMINAL_BOX_HORIZONTAL, 1, fg, bg, bold, rev, ul);
775        let mut cx: u16 = x + 1;
776        while cx < right {
777            let _: u16 = self.put_cell(cx, y, horiz);
778            let _: u16 = self.put_cell(cx, bottom, horiz);
779            cx += 1;
780        }
781        let vert: TerminalCell =
782            TerminalCell::styled(TERMINAL_BOX_VERTICAL, 1, fg, bg, bold, rev, ul);
783        let mut cy: u16 = y + 1;
784        while cy < bottom {
785            let _: u16 = self.put_cell(x, cy, vert);
786            let _: u16 = self.put_cell(right, cy, vert);
787            cy += 1;
788        }
789    }
790
791    /// Serializes the grid into clean UTF-8 lines with full Extended Grapheme Clusters and zero ANSI escape sequences for piped CLI stdout.
792    ///
793    /// # Arguments
794    ///
795    /// - `&Self` - Grid reference.
796    ///
797    /// # Returns
798    ///
799    /// - `String` - Plain-text UTF-8 representation trimmed of trailing whitespace per line and trailing blank lines.
800    #[must_use]
801    pub fn to_plain_text(&self) -> String {
802        let cols: usize = self.get_cols() as usize;
803        let rows: usize = self.get_rows() as usize;
804        let cells: &[TerminalCell] = self.get_cells().as_slice();
805        let mut lines: Vec<String> = Vec::with_capacity(rows);
806        for row in 0..rows {
807            let start: usize = row * cols;
808            let end: usize = (start + cols).min(cells.len());
809            let mut line: String = String::with_capacity(cols);
810            for cell in &cells[start..end] {
811                if cell.is_continuation() {
812                    continue;
813                }
814                cell.push_grapheme_to(&mut line);
815            }
816            let trimmed_len: usize = line.trim_end().len();
817            line.truncate(trimmed_len);
818            lines.push(line);
819        }
820        while let Some(last) = lines.last() {
821            if last.is_empty() {
822                let _: Option<String> = lines.pop();
823            } else {
824                break;
825            }
826        }
827        lines.join("\n")
828    }
829}
830
831/// Session lifecycle entry and idempotent ANSI state restoration for `TerminalSessionGuard`.
832impl TerminalSessionGuard {
833    /// Builds the escape sequence required to enter the configured interactive terminal modes.
834    ///
835    /// # Arguments
836    ///
837    /// - `bool` - Whether to enter the alternate screen buffer.
838    /// - `bool` - Whether to hide the terminal cursor.
839    /// - `bool` - Whether to enable raw bracketed input mode.
840    ///
841    /// # Returns
842    ///
843    /// - `String` - Concatenated ANSI enter sequence.
844    #[must_use]
845    pub fn build_enter_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
846        let mut out: String = String::new();
847        if alt_screen {
848            out.push_str(ANSI_ENTER_ALT_SCREEN);
849        }
850        if cursor_hidden {
851            out.push_str(ANSI_HIDE_CURSOR);
852        }
853        if raw_mode {
854            out.push_str(ANSI_ENTER_RAW_MODES);
855        }
856        out
857    }
858
859    /// Builds the escape sequence required to cleanly restore terminal state upon exit or unwind.
860    ///
861    /// # Arguments
862    ///
863    /// - `bool` - Whether alternate screen mode was entered.
864    /// - `bool` - Whether cursor visibility was hidden.
865    /// - `bool` - Whether raw input modes were enabled.
866    ///
867    /// # Returns
868    ///
869    /// - `String` - Concatenated ANSI restoration sequence.
870    #[must_use]
871    pub fn build_restore_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
872        let mut out: String = String::from(ANSI_RESET_STYLE);
873        if raw_mode {
874            out.push_str(ANSI_LEAVE_RAW_MODES);
875        }
876        if cursor_hidden {
877            out.push_str(ANSI_SHOW_CURSOR);
878        }
879        if alt_screen {
880            out.push_str(ANSI_LEAVE_ALT_SCREEN);
881        }
882        out
883    }
884
885    /// Enters an interactive terminal session writing enter/restore sequences to an optional capture buffer.
886    ///
887    /// # Arguments
888    ///
889    /// - `bool` - Enter alternate screen buffer.
890    /// - `bool` - Hide terminal cursor.
891    /// - `bool` - Enable raw input tracking modes.
892    /// - `Option<Rc<RefCell<String>>>` - Optional capture buffer for deterministic testing or virtual PTYs.
893    ///
894    /// # Returns
895    ///
896    /// - `Self` - Active RAII session guard.
897    #[must_use]
898    pub fn enter_captured(
899        alt_screen: bool,
900        cursor_hidden: bool,
901        raw_mode: bool,
902        sink: Option<Rc<RefCell<String>>>,
903    ) -> Self {
904        let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
905        if let Some(buf) = sink.as_ref()
906            && let Ok(mut guard) = buf.try_borrow_mut()
907        {
908            guard.push_str(&enter_seq);
909        }
910        Self {
911            alt_screen,
912            cursor_hidden,
913            raw_mode,
914            restored: false,
915            write_to_stdout: false,
916            sink,
917        }
918    }
919
920    /// Enters an interactive terminal session flushing enter and restore sequences directly to stdout on native targets.
921    ///
922    /// # Arguments
923    ///
924    /// - `bool` - Enter alternate screen buffer.
925    /// - `bool` - Hide terminal cursor.
926    /// - `bool` - Enable raw input tracking modes.
927    ///
928    /// # Returns
929    ///
930    /// - `Self` - Active RAII session guard bound to stdout.
931    #[must_use]
932    pub fn enter_stdout(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> Self {
933        let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
934        #[cfg(not(target_arch = "wasm32"))]
935        {
936            let mut stdout: io::Stdout = io::stdout();
937            let _: io::Result<()> = stdout.write_all(enter_seq.as_bytes());
938            let _: io::Result<()> = stdout.flush();
939        }
940        #[cfg(target_arch = "wasm32")]
941        let _: &String = &enter_seq;
942        Self {
943            alt_screen,
944            cursor_hidden,
945            raw_mode,
946            restored: false,
947            write_to_stdout: true,
948            sink: None,
949        }
950    }
951
952    /// Restores terminal state immediately if not already restored and returns the emitted ANSI sequence.
953    ///
954    /// # Arguments
955    ///
956    /// - `&Self` - Mutable session guard.
957    ///
958    /// # Returns
959    ///
960    /// - `String` - Restoration escape sequence emitted (empty if already restored).
961    pub fn restore_now(&mut self) -> String {
962        if self.get_restored() {
963            return String::new();
964        }
965        self.set_restored(true);
966        let seq: String = Self::build_restore_sequence(
967            self.get_alt_screen(),
968            self.get_cursor_hidden(),
969            self.get_raw_mode(),
970        );
971        let write_stdout: bool = self.get_write_to_stdout();
972        let Self { sink, .. } = self;
973        if let Some(buf) = sink.as_ref()
974            && let Ok(mut guard) = buf.try_borrow_mut()
975        {
976            guard.push_str(&seq);
977        }
978        #[cfg(not(target_arch = "wasm32"))]
979        if write_stdout {
980            let mut stdout: io::Stdout = io::stdout();
981            let _: io::Result<()> = stdout.write_all(seq.as_bytes());
982            let _: io::Result<()> = stdout.flush();
983        }
984        #[cfg(target_arch = "wasm32")]
985        let _: bool = write_stdout;
986        seq
987    }
988}
989
990/// Guaranteed RAII restoration of cursor, raw mode, and alternate screen on normal exit or panic unwind.
991impl Drop for TerminalSessionGuard {
992    /// Restores terminal modes automatically when the guard leaves scope.
993    ///
994    /// # Arguments
995    ///
996    /// - `&Self` - Mutable session guard being dropped.
997    fn drop(&mut self) {
998        let _: String = self.restore_now();
999    }
1000}
1001
1002/// Double-buffered semantic scene projection, zero-work idle short-circuit, virtualized scroll projection, and coalesced ANSI diff encoding for `TerminalRenderer`.
1003impl TerminalRenderer {
1004    /// Creates a fresh `TerminalRenderer` with empty diff history.
1005    ///
1006    /// # Returns
1007    ///
1008    /// - `Self` - Initialized terminal renderer.
1009    #[must_use]
1010    pub fn new() -> Self {
1011        Self::default()
1012    }
1013
1014    /// Returns `true` when the persistent previous-frame back buffer has been allocated and holds a committed interactive frame.
1015    ///
1016    /// # Arguments
1017    ///
1018    /// - `&Self` - Terminal renderer reference.
1019    ///
1020    /// # Returns
1021    ///
1022    /// - `bool` - `true` iff a committed previous grid exists (always `false` in `StaticPlainText`-only runs).
1023    #[must_use]
1024    pub fn has_previous_frame(&self) -> bool {
1025        self.get_previous_valid() && !self.get_previous().get_cells().is_empty()
1026    }
1027
1028    /// Returns the last committed frame fingerprint used for O(1) idle short-circuiting.
1029    ///
1030    /// # Arguments
1031    ///
1032    /// - `&Self` - Terminal renderer reference.
1033    ///
1034    /// # Returns
1035    ///
1036    /// - `Option<TerminalFrameFingerprint>` - Cached frame fingerprint if valid.
1037    #[must_use]
1038    pub const fn last_fingerprint(&self) -> Option<TerminalFrameFingerprint> {
1039        let Self {
1040            last_fingerprint, ..
1041        } = *self;
1042        last_fingerprint
1043    }
1044
1045    /// Marks the previous-frame back buffer invalid without deallocating its storage, forcing a clean full synchronization on the next interactive render.
1046    ///
1047    /// # Arguments
1048    ///
1049    /// - `&Self` - Mutable terminal renderer.
1050    pub fn invalidate(&mut self) {
1051        self.set_previous_valid(false);
1052        let Self {
1053            last_fingerprint, ..
1054        } = self;
1055        *last_fingerprint = None;
1056    }
1057
1058    /// Computes an O(1) (plus O(#scroll_views)) frame fingerprint capturing scene revision, focus, caret blink, input caret offset, scroll offsets, viewport dimensions, and mode.
1059    ///
1060    /// # Arguments
1061    ///
1062    /// - `&Self` - Terminal renderer reference.
1063    /// - `&SceneTree` - Retained UI scene tree.
1064    /// - `u16` - Clamped terminal column count.
1065    /// - `u16` - Clamped terminal row count.
1066    /// - `TerminalRenderMode` - Active render mode.
1067    ///
1068    /// # Returns
1069    ///
1070    /// - `TerminalFrameFingerprint` - Frame fingerprint for idle detection.
1071    #[must_use]
1072    fn compute_fingerprint(
1073        &self,
1074        tree: &SceneTree,
1075        cols: u16,
1076        rows: u16,
1077        mode: TerminalRenderMode,
1078    ) -> TerminalFrameFingerprint {
1079        let focused: Option<NodeId> = tree.get_focus().focused_node();
1080        let focused_caret_offset: usize = focused
1081            .and_then(|id: NodeId| tree.get_node(id))
1082            .map(|node: &SceneNode| match node.get_kind() {
1083                NodeKind::Input(inp) => inp.get_caret(),
1084                _ => 0,
1085            })
1086            .unwrap_or(0);
1087        let mut scroll_hash: u64 = TERMINAL_FNV_OFFSET_BASIS;
1088        for scroll_id in self.get_tracked_scroll_nodes().iter().copied() {
1089            if let Some(node) = tree.get_node(scroll_id) {
1090                let off: Point = node.get_layout_box().get_scroll_offset();
1091                scroll_hash = fnv1a_mix_u64(scroll_hash, off.get_x().to_bits() as u64);
1092                scroll_hash = fnv1a_mix_u64(scroll_hash, off.get_y().to_bits() as u64);
1093            }
1094        }
1095        TerminalFrameFingerprint {
1096            scene_revision: tree.get_revision(),
1097            focused,
1098            caret_visible: tree.get_caret_visible(),
1099            focused_caret_offset,
1100            scroll_hash,
1101            cols,
1102            rows,
1103            mode,
1104        }
1105    }
1106
1107    /// Projects `tree` into a `cols x rows` character grid and returns either coalesced ANSI TUI diffs (committing via zero-clone double-buffer `swap`) or zero-ANSI static plain text.
1108    ///
1109    /// # Arguments
1110    ///
1111    /// - `&Self` - Mutable terminal renderer.
1112    /// - `&SceneTree` - Retained UI scene tree to project.
1113    /// - `u16` - Terminal viewport width in columns.
1114    /// - `u16` - Terminal viewport height in rows.
1115    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
1116    ///
1117    /// # Returns
1118    ///
1119    /// - `(String, TerminalDiffStats)` - Rendered UTF-8 terminal payload and cell-diff telemetry.
1120    pub fn render_tree(
1121        &mut self,
1122        tree: &SceneTree,
1123        cols: u16,
1124        rows: u16,
1125        mode: TerminalRenderMode,
1126    ) -> (String, TerminalDiffStats) {
1127        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1128        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1129        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1130        if mode == TerminalRenderMode::InteractiveTui {
1131            let fp: TerminalFrameFingerprint =
1132                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1133            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1134                self.set_last_projected_rows(0);
1135                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1136                self.set_skipped_idle_frames(next_skipped);
1137                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1138                self.set_frames_rendered(next_frames);
1139                return (
1140                    String::new(),
1141                    TerminalDiffStats::new(total_cells, 0, 0, true, false),
1142                );
1143            }
1144        }
1145        let stats: TerminalDiffStats =
1146            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1147        let output: String = self.get_ansi_scratch().clone();
1148        self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1149        (output, stats)
1150    }
1151
1152    /// Projects `tree` into a `cols x rows` character grid and returns a zero-allocation borrowed view of the encoded ANSI or plain-text payload.
1153    ///
1154    /// # Arguments
1155    ///
1156    /// - `&Self` - Mutable terminal renderer.
1157    /// - `&SceneTree` - Retained UI scene tree to project.
1158    /// - `u16` - Terminal viewport width in columns.
1159    /// - `u16` - Terminal viewport height in rows.
1160    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
1161    ///
1162    /// # Returns
1163    ///
1164    /// - `(&str, TerminalDiffStats)` - Borrowed UTF-8 terminal payload and cell-diff telemetry.
1165    pub fn render_tree_borrowed(
1166        &mut self,
1167        tree: &SceneTree,
1168        cols: u16,
1169        rows: u16,
1170        mode: TerminalRenderMode,
1171    ) -> (&str, TerminalDiffStats) {
1172        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1173        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1174        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1175        if mode == TerminalRenderMode::InteractiveTui {
1176            let fp: TerminalFrameFingerprint =
1177                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1178            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1179                self.set_last_projected_rows(0);
1180                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1181                self.set_skipped_idle_frames(next_skipped);
1182                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1183                self.set_frames_rendered(next_frames);
1184                self.get_mut_ansi_scratch().clear();
1185                return (
1186                    self.get_ansi_scratch().as_str(),
1187                    TerminalDiffStats::new(total_cells, 0, 0, true, false),
1188                );
1189            }
1190        }
1191        let stats: TerminalDiffStats =
1192            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1193        self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1194        (self.get_ansi_scratch().as_str(), stats)
1195    }
1196
1197    /// Projects `tree`, encodes the batched output into an internal scratch buffer, flushes it in one write call to `writer`, and swaps double-buffer ownership ONLY when writing succeeds.
1198    ///
1199    /// # Arguments
1200    ///
1201    /// - `&Self` - Mutable terminal renderer.
1202    /// - `&SceneTree` - Retained UI scene tree to project.
1203    /// - `u16` - Terminal viewport width in columns.
1204    /// - `u16` - Terminal viewport height in rows.
1205    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
1206    /// - `&mut W` - Output writer receiving the single batched write.
1207    ///
1208    /// # Returns
1209    ///
1210    /// - `TerminalWriteResult` - Write status, diff stats, and whether double-buffer ownership was swapped.
1211    #[cfg(not(target_arch = "wasm32"))]
1212    pub fn render_tree_to_writer<W>(
1213        &mut self,
1214        tree: &SceneTree,
1215        cols: u16,
1216        rows: u16,
1217        mode: TerminalRenderMode,
1218        writer: &mut W,
1219    ) -> TerminalWriteResult
1220    where
1221        W: Write,
1222    {
1223        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1224        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1225        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1226        if mode == TerminalRenderMode::InteractiveTui {
1227            let fp: TerminalFrameFingerprint =
1228                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1229            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1230                self.set_last_projected_rows(0);
1231                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1232                self.set_skipped_idle_frames(next_skipped);
1233                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1234                self.set_frames_rendered(next_frames);
1235                return TerminalWriteResult {
1236                    status: CliWriteStatus::Written,
1237                    stats: TerminalDiffStats::new(total_cells, 0, 0, true, false),
1238                    swapped: false,
1239                    error_message: None,
1240                };
1241            }
1242        }
1243        let stats: TerminalDiffStats =
1244            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1245        let payload_bytes: &[u8] = self.get_ansi_scratch().as_bytes();
1246        if !payload_bytes.is_empty() {
1247            if let Err(err) = writer.write_all(payload_bytes) {
1248                let status: CliWriteStatus = classify_io_error(&err);
1249                self.invalidate();
1250                return TerminalWriteResult {
1251                    status,
1252                    stats,
1253                    swapped: false,
1254                    error_message: Some(err.to_string()),
1255                };
1256            }
1257            if let Err(err) = writer.flush() {
1258                let status: CliWriteStatus = classify_io_error(&err);
1259                self.invalidate();
1260                return TerminalWriteResult {
1261                    status,
1262                    stats,
1263                    swapped: false,
1264                    error_message: Some(err.to_string()),
1265                };
1266            }
1267        }
1268        let swapped: bool = self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1269        TerminalWriteResult {
1270            status: CliWriteStatus::Written,
1271            stats,
1272            swapped,
1273            error_message: None,
1274        }
1275    }
1276
1277    /// Projects `tree` into `current` and encodes the payload into `ansi_scratch` without mutating `previous`.
1278    ///
1279    /// # Arguments
1280    ///
1281    /// - `&Self` - Mutable terminal renderer.
1282    /// - `&SceneTree` - Retained UI scene tree.
1283    /// - `u16` - Clamped terminal columns.
1284    /// - `u16` - Clamped terminal rows.
1285    /// - `TerminalRenderMode` - Active render mode.
1286    ///
1287    /// # Returns
1288    ///
1289    /// - `TerminalDiffStats` - Per-frame cell diff telemetry.
1290    fn project_and_encode_into_scratch(
1291        &mut self,
1292        tree: &SceneTree,
1293        clamped_cols: u16,
1294        clamped_rows: u16,
1295        mode: TerminalRenderMode,
1296    ) -> TerminalDiffStats {
1297        self.get_mut_current().reset(clamped_cols, clamped_rows);
1298        self.get_mut_tracked_scroll_nodes().clear();
1299        let focused: Option<NodeId> = tree.get_focus().focused_node();
1300        let mut cursor_y: u16 = 0;
1301        let root_region: TerminalRegion =
1302            TerminalRegion::new(0, clamped_cols, clamped_rows, focused);
1303        self.project_node(tree, tree.get_root(), root_region, &mut cursor_y);
1304        self.set_last_projected_rows(cursor_y as usize);
1305        self.get_mut_current().finalize_row_hashes();
1306        let total_cells: usize = self.get_current().total_cells();
1307        self.get_mut_ansi_scratch().clear();
1308        match mode {
1309            TerminalRenderMode::StaticPlainText => {
1310                let plain: String = self.get_current().to_plain_text();
1311                let bytes: usize = plain.len();
1312                self.get_mut_ansi_scratch().push_str(&plain);
1313                TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
1314            }
1315            TerminalRenderMode::InteractiveTui => {
1316                let resized_or_first: bool = !self.get_previous_valid()
1317                    || self.get_last_cols() != clamped_cols
1318                    || self.get_last_rows() != clamped_rows
1319                    || self.get_previous().total_cells() != total_cells;
1320                if resized_or_first {
1321                    self.encode_full_frame_into_scratch();
1322                    let bytes: usize = self.get_ansi_scratch().len();
1323                    TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
1324                } else {
1325                    self.encode_diff_frame_into_scratch()
1326                }
1327            }
1328        }
1329    }
1330
1331    /// Commits double-buffer ownership via zero-clone `swap` after a confirmed interactive write (leaving `previous` untouched in `StaticPlainText` mode).
1332    ///
1333    /// # Arguments
1334    ///
1335    /// - `&Self` - Mutable terminal renderer.
1336    /// - `&SceneTree` - Rendered scene tree.
1337    /// - `u16` - Clamped terminal columns.
1338    /// - `u16` - Clamped terminal rows.
1339    /// - `TerminalRenderMode` - Active render mode.
1340    ///
1341    /// # Returns
1342    ///
1343    /// - `bool` - `true` when `current` and `previous` were swapped.
1344    fn commit_after_write(
1345        &mut self,
1346        tree: &SceneTree,
1347        clamped_cols: u16,
1348        clamped_rows: u16,
1349        mode: TerminalRenderMode,
1350    ) -> bool {
1351        self.set_last_cols(clamped_cols);
1352        self.set_last_rows(clamped_rows);
1353        let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1354        self.set_frames_rendered(next_frames);
1355        if mode == TerminalRenderMode::StaticPlainText {
1356            self.set_previous_valid(false);
1357            let Self {
1358                last_fingerprint, ..
1359            } = self;
1360            *last_fingerprint = None;
1361            return false;
1362        }
1363        let fp: TerminalFrameFingerprint =
1364            self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1365        let Self {
1366            previous,
1367            current,
1368            previous_valid,
1369            last_fingerprint,
1370            ..
1371        } = self;
1372        swap(current, previous);
1373        let target_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1374        if current.total_cells() != target_cells {
1375            current.reset(clamped_cols, clamped_rows);
1376        }
1377        *previous_valid = true;
1378        *last_fingerprint = Some(fp);
1379        true
1380    }
1381
1382    /// Processes a terminal keyboard event (`Tab`, `Shift+Tab`, arrows, `Enter`, `Escape`, `Ctrl+C`) against `tree`.
1383    ///
1384    /// # Arguments
1385    ///
1386    /// - `&Self` - Mutable terminal renderer.
1387    /// - `&mut SceneTree` - Retained UI scene tree to update focus, scroll, or activation on.
1388    /// - `KeyEvent` - Normalized keyboard event.
1389    ///
1390    /// # Returns
1391    ///
1392    /// - `TerminalNavAction` - Resulting focus, scroll, activation, or exit action.
1393    pub fn handle_key(&mut self, tree: &mut SceneTree, key: KeyEvent) -> TerminalNavAction {
1394        let code: KeyCode = key.get_code();
1395        let mods: Modifiers = key.get_modifiers();
1396        if code == KeyCode::Escape
1397            || (mods.get_ctrl()
1398                && matches!(code, KeyCode::Character('c') | KeyCode::Character('C')))
1399        {
1400            self.set_exit_requested(true);
1401            return TerminalNavAction::ExitRequested;
1402        }
1403        if code == KeyCode::Tab {
1404            let focusables: Vec<NodeId> = Self::collect_focusables(tree);
1405            if focusables.is_empty() {
1406                return TerminalNavAction::Ignored;
1407            }
1408            let current: Option<NodeId> = tree.get_focus().focused_node();
1409            let next_target: NodeId = match current
1410                .and_then(|cur: NodeId| focusables.iter().position(|id: &NodeId| *id == cur))
1411            {
1412                Some(idx) => {
1413                    let next_idx: usize = if mods.get_shift() {
1414                        if idx == 0 {
1415                            focusables.len() - 1
1416                        } else {
1417                            idx - 1
1418                        }
1419                    } else {
1420                        (idx + 1) % focusables.len()
1421                    };
1422                    focusables[next_idx]
1423                }
1424                None => {
1425                    if mods.get_shift() {
1426                        focusables[focusables.len() - 1]
1427                    } else {
1428                        focusables[0]
1429                    }
1430                }
1431            };
1432            let callbacks: Vec<(UiEventHandler, UiEvent)> = tree.update_focus(Some(next_target));
1433            for (handler, ev) in callbacks.into_iter() {
1434                if let Ok(mut cb) = handler.try_borrow_mut() {
1435                    cb(&ev);
1436                }
1437            }
1438            return TerminalNavAction::FocusMoved(next_target);
1439        }
1440        if code == KeyCode::ArrowDown || code == KeyCode::ArrowUp {
1441            let delta_rows: i16 = if code == KeyCode::ArrowDown { 1 } else { -1 };
1442            if let Some(scroll_id) = Self::find_first_scroll_view(tree) {
1443                let current_y: f32 = tree
1444                    .get_node(scroll_id)
1445                    .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
1446                    .unwrap_or(0.0);
1447                let next_y: f32 =
1448                    (current_y + (delta_rows as f32) * TERMINAL_SCROLL_STEP_PX).max(0.0);
1449                tree.set_scroll_offset(scroll_id, Point::new(0.0, next_y));
1450                return TerminalNavAction::Scrolled(delta_rows);
1451            }
1452            return TerminalNavAction::Ignored;
1453        }
1454        if code == KeyCode::Enter {
1455            if let Some(target) = tree.get_focus().focused_node() {
1456                let click_kind: UiEventKind = UiEventKind::Click(Point::default());
1457                let handler_opt: Option<UiEventHandler> = tree
1458                    .get_node(target)
1459                    .and_then(|node: &SceneNode| node.get_handlers().handler_for(&click_kind));
1460                if let Some(handler) = handler_opt
1461                    && let Ok(mut cb) = handler.try_borrow_mut()
1462                {
1463                    let click_ev: UiEvent = UiEvent::new(target, click_kind);
1464                    cb(&click_ev);
1465                }
1466                return TerminalNavAction::Activated(target);
1467            }
1468            return TerminalNavAction::Ignored;
1469        }
1470        TerminalNavAction::Ignored
1471    }
1472
1473    /// Collects all visible focusable or clickable node handles in pre-order traversal.
1474    ///
1475    /// # Arguments
1476    ///
1477    /// - `&SceneTree` - Retained UI scene tree.
1478    ///
1479    /// # Returns
1480    ///
1481    /// - `Vec<NodeId>` - Ordered focus ring candidates.
1482    #[must_use]
1483    fn collect_focusables(tree: &SceneTree) -> Vec<NodeId> {
1484        let mut out: Vec<NodeId> = Vec::new();
1485        let mut stack: Vec<NodeId> = vec![tree.get_root()];
1486        while let Some(id) = stack.pop() {
1487            let Some(node) = tree.get_node(id) else {
1488                continue;
1489            };
1490            if node.style_ref().get_layout().get_display() == Display::None
1491                || node.style_ref().get_paint().get_opacity() <= 0.0
1492            {
1493                continue;
1494            }
1495            if Self::is_focusable_or_interactive(node) {
1496                out.push(id);
1497            }
1498            for child in tree.children_iter(id).rev() {
1499                stack.push(child);
1500            }
1501        }
1502        out
1503    }
1504
1505    /// Finds the first visible `NodeKind::ScrollView` node in pre-order traversal.
1506    ///
1507    /// # Arguments
1508    ///
1509    /// - `&SceneTree` - Retained UI scene tree.
1510    ///
1511    /// # Returns
1512    ///
1513    /// - `Option<NodeId>` - First visible scroll container handle.
1514    #[must_use]
1515    fn find_first_scroll_view(tree: &SceneTree) -> Option<NodeId> {
1516        let mut stack: Vec<NodeId> = vec![tree.get_root()];
1517        while let Some(id) = stack.pop() {
1518            let Some(node) = tree.get_node(id) else {
1519                continue;
1520            };
1521            if node.style_ref().get_layout().get_display() == Display::None {
1522                continue;
1523            }
1524            if matches!(node.get_kind(), NodeKind::ScrollView) {
1525                return Some(id);
1526            }
1527            for child in tree.children_iter(id).rev() {
1528                stack.push(child);
1529            }
1530        }
1531        None
1532    }
1533
1534    /// Returns `true` when `node` should participate in terminal focus and clickable affordances.
1535    ///
1536    /// # Arguments
1537    ///
1538    /// - `&SceneNode` - Candidate scene node.
1539    ///
1540    /// # Returns
1541    ///
1542    /// - `bool` - Whether the node is focusable or interactive.
1543    #[must_use]
1544    fn is_focusable_or_interactive(node: &SceneNode) -> bool {
1545        node.get_interaction().get_focusable()
1546            || matches!(node.get_kind(), NodeKind::Input(_))
1547            || Self::is_clickable_node(node)
1548    }
1549
1550    /// Returns `true` when `node` acts as a clickable button or interactive trigger.
1551    ///
1552    /// # Arguments
1553    ///
1554    /// - `&SceneNode` - Candidate scene node.
1555    ///
1556    /// # Returns
1557    ///
1558    /// - `bool` - Whether the node has click semantics.
1559    #[must_use]
1560    fn is_clickable_node(node: &SceneNode) -> bool {
1561        node.get_handlers()
1562            .handler_for(&UiEventKind::Click(Point::default()))
1563            .is_some()
1564            || node.style_ref().get_paint().get_cursor() == CursorIcon::Pointer
1565            || node
1566                .a11y_props()
1567                .is_some_and(|a: A11yProps| a.get_role() == A11yRole::Button)
1568    }
1569
1570    /// Returns `true` when a child node is visible for terminal projection.
1571    ///
1572    /// # Arguments
1573    ///
1574    /// - `&SceneTree` - Retained UI scene tree.
1575    /// - `NodeId` - Candidate node handle.
1576    ///
1577    /// # Returns
1578    ///
1579    /// - `bool` - `true` iff node exists, `display != None`, and `opacity > 0.0`.
1580    #[must_use]
1581    fn is_node_visible(tree: &SceneTree, node_id: NodeId) -> bool {
1582        tree.get_node(node_id).is_some_and(|c: &SceneNode| {
1583            c.style_ref().get_layout().get_display() != Display::None
1584                && c.style_ref().get_paint().get_opacity() > 0.0
1585        })
1586    }
1587
1588    /// Collects direct/descendant display label text for a clickable container button.
1589    ///
1590    /// # Arguments
1591    ///
1592    /// - `&SceneTree` - Retained UI scene tree.
1593    /// - `NodeId` - Button container node identifier.
1594    ///
1595    /// # Returns
1596    ///
1597    /// - `String` - Resolved button caption text.
1598    #[must_use]
1599    fn collect_button_label(tree: &SceneTree, node_id: NodeId) -> String {
1600        let Some(node) = tree.get_node(node_id) else {
1601            return String::new();
1602        };
1603        let mut parts: Vec<String> = Vec::new();
1604        let mut stack: Vec<NodeId> = tree.children_iter(node_id).rev().collect();
1605        while let Some(cid) = stack.pop() {
1606            let Some(child) = tree.get_node(cid) else {
1607                continue;
1608            };
1609            if child.style_ref().get_layout().get_display() == Display::None {
1610                continue;
1611            }
1612            if let NodeKind::Text(text) = child.get_kind() {
1613                let trimmed: &str = text.trim();
1614                if !trimmed.is_empty() {
1615                    parts.push(trimmed.to_string());
1616                }
1617            }
1618            for grand in tree.children_iter(cid).rev() {
1619                stack.push(grand);
1620            }
1621        }
1622        if !parts.is_empty() {
1623            return parts.join(" ");
1624        }
1625        node.a11y_props()
1626            .map(|a: A11yProps| a.get_label().clone())
1627            .unwrap_or_default()
1628    }
1629
1630    /// Projects a single scene node subtree into the current `TerminalCellGrid` using terminal character coordinates directly.
1631    ///
1632    /// # Arguments
1633    ///
1634    /// - `&Self` - Mutable terminal renderer.
1635    /// - `&SceneTree` - Retained scene tree.
1636    /// - `NodeId` - Target node handle to project.
1637    /// - `TerminalRegion` - Active character-grid region and focus context.
1638    /// - `&mut u16` - Mutable current row cursor advanced as content is laid out.
1639    fn project_node(
1640        &mut self,
1641        tree: &SceneTree,
1642        node_id: NodeId,
1643        region: TerminalRegion,
1644        y: &mut u16,
1645    ) {
1646        let x: u16 = region.get_x();
1647        let avail_w: u16 = region.get_width();
1648        let max_y: u16 = region.get_max_y();
1649        let focused: Option<NodeId> = region.get_focused();
1650        if *y >= max_y || avail_w == 0 {
1651            return;
1652        }
1653        let Some(node) = tree.get_node(node_id) else {
1654            return;
1655        };
1656        let style: &Style = node.style_ref();
1657        let layout: LayoutStyle = style.get_layout();
1658        let paint: PaintStyle = style.get_paint();
1659        let text_style: TextStyle = style.get_text();
1660        if layout.get_display() == Display::None || paint.get_opacity() <= 0.0 {
1661            return;
1662        }
1663        let is_focused: bool = focused == Some(node_id) || node.get_interaction().get_focused();
1664        let is_bold: bool = matches!(
1665            text_style.get_weight(),
1666            FontWeight::SemiBold | FontWeight::Bold
1667        );
1668        let fg: Option<Color> = Some(text_style.get_color());
1669        let bg: Option<Color> = paint.background_color();
1670        let template: TerminalCell = TerminalCell::styled(
1671            ' ',
1672            1,
1673            fg,
1674            bg,
1675            is_bold,
1676            is_focused,
1677            text_style.get_underline(),
1678        );
1679        match node.get_kind() {
1680            NodeKind::Text(content) => {
1681                if Self::is_clickable_node(node) {
1682                    let display_str: String = if is_focused {
1683                        format!("> [ {content} ]")
1684                    } else {
1685                        format!("[ {content} ]")
1686                    };
1687                    self.write_wrapped_text(region, y, &display_str, template);
1688                } else {
1689                    self.write_wrapped_text(region, y, content.as_str(), template);
1690                }
1691            }
1692            NodeKind::Input(inp) => {
1693                let inner: String = if inp.get_value().is_empty() {
1694                    inp.get_placeholder().clone()
1695                } else if inp.get_password() {
1696                    let count: usize = inp.get_value().chars().count();
1697                    "*".repeat(count)
1698                } else {
1699                    inp.get_value().clone()
1700                };
1701                let formatted: String = if is_focused {
1702                    if tree.get_caret_visible() {
1703                        format!("> [ {inner}| ]")
1704                    } else {
1705                        format!("> [ {inner}  ]")
1706                    }
1707                } else {
1708                    format!("[ {inner} ]")
1709                };
1710                let _: u16 = self
1711                    .get_mut_current()
1712                    .write_styled_text(x, *y, avail_w, &formatted, template);
1713                *y = y.saturating_add(1);
1714            }
1715            NodeKind::Image(img) => {
1716                let alt: String = node
1717                    .a11y_props()
1718                    .map(|a: A11yProps| a.get_label().clone())
1719                    .filter(|s: &String| !s.is_empty())
1720                    .map(|lbl: String| format!("{TERMINAL_IMAGE_FALLBACK_PREFIX}{lbl}]"))
1721                    .unwrap_or_else(|| {
1722                        format!(
1723                            "{TERMINAL_IMAGE_DIM_PREFIX}{}x{}]",
1724                            img.get_width(),
1725                            img.get_height()
1726                        )
1727                    });
1728                let _: u16 = self
1729                    .get_mut_current()
1730                    .write_styled_text(x, *y, avail_w, &alt, template);
1731                *y = y.saturating_add(1);
1732            }
1733            NodeKind::Canvas(_) => {
1734                let alt: String = node
1735                    .a11y_props()
1736                    .map(|a: A11yProps| a.get_label().clone())
1737                    .filter(|s: &String| !s.is_empty())
1738                    .map(|lbl: String| format!("{TERMINAL_CANVAS_FALLBACK_PREFIX}{lbl}]"))
1739                    .unwrap_or_else(|| TERMINAL_CANVAS_FALLBACK.to_string());
1740                let _: u16 = self
1741                    .get_mut_current()
1742                    .write_styled_text(x, *y, avail_w, &alt, template);
1743                *y = y.saturating_add(1);
1744            }
1745            NodeKind::Fragment => {
1746                for child_id in tree.children_iter(node_id) {
1747                    if *y >= max_y {
1748                        break;
1749                    }
1750                    self.project_node(tree, child_id, region, y);
1751                }
1752            }
1753            NodeKind::ScrollView => {
1754                self.project_scroll_view(tree, node_id, region, y);
1755            }
1756            NodeKind::View | NodeKind::Portal => {
1757                let is_root: bool = node_id == tree.get_root();
1758                if !is_root && Self::is_clickable_node(node) {
1759                    let caption: String = Self::collect_button_label(tree, node_id);
1760                    if !caption.is_empty() {
1761                        let formatted: String = if is_focused {
1762                            format!("> [ {caption} ]")
1763                        } else {
1764                            format!("[ {caption} ]")
1765                        };
1766                        let _: u16 = self
1767                            .get_mut_current()
1768                            .write_styled_text(x, *y, avail_w, &formatted, template);
1769                        *y = y.saturating_add(1);
1770                        return;
1771                    }
1772                }
1773                let has_border: bool = !is_root
1774                    && (paint.get_border().get_width() > 0.0
1775                        || matches!(node.get_kind(), NodeKind::Portal))
1776                    && avail_w >= 4
1777                    && max_y.saturating_sub(*y) >= 3;
1778                if has_border {
1779                    let top_y: u16 = *y;
1780                    let inner_region: TerminalRegion = TerminalRegion::new(
1781                        x.saturating_add(1),
1782                        avail_w.saturating_sub(2),
1783                        max_y.saturating_sub(1),
1784                        focused,
1785                    );
1786                    let mut child_y: u16 = top_y.saturating_add(1);
1787                    self.project_children_flow(tree, node_id, node, inner_region, &mut child_y);
1788                    let box_h: u16 = child_y
1789                        .saturating_sub(top_y)
1790                        .saturating_add(1)
1791                        .max(3)
1792                        .min(max_y.saturating_sub(top_y));
1793                    let border_cell: TerminalCell = TerminalCell::styled(
1794                        ' ',
1795                        1,
1796                        Some(paint.get_border().get_color()),
1797                        bg,
1798                        false,
1799                        is_focused,
1800                        false,
1801                    );
1802                    self.get_mut_current()
1803                        .draw_box(x, top_y, avail_w, box_h, border_cell);
1804                    *y = top_y.saturating_add(box_h);
1805                } else {
1806                    self.project_children_flow(tree, node_id, node, region, y);
1807                }
1808            }
1809        }
1810    }
1811
1812    /// Projects children of a container respecting row, column, and grid directions directly in character columns.
1813    ///
1814    /// # Arguments
1815    ///
1816    /// - `&Self` - Mutable terminal renderer.
1817    /// - `&SceneTree` - Retained scene tree.
1818    /// - `NodeId` - Container scene node handle.
1819    /// - `&SceneNode` - Container scene node.
1820    /// - `TerminalRegion` - Active character-grid region and focus context.
1821    /// - `&mut u16` - Mutable current row cursor.
1822    fn project_children_flow(
1823        &mut self,
1824        tree: &SceneTree,
1825        node_id: NodeId,
1826        node: &SceneNode,
1827        region: TerminalRegion,
1828        y: &mut u16,
1829    ) {
1830        let x: u16 = region.get_x();
1831        let avail_w: u16 = region.get_width();
1832        let max_y: u16 = region.get_max_y();
1833        let focused: Option<NodeId> = region.get_focused();
1834        let layout: LayoutStyle = node.style_ref().get_layout();
1835        let is_row: bool = matches!(
1836            layout.get_flex_direction(),
1837            FlexDirection::Row | FlexDirection::RowReverse
1838        ) && layout.get_display() == Display::Flex;
1839        if is_row {
1840            let visible_count: usize = tree
1841                .children_iter(node_id)
1842                .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
1843                .count();
1844            if visible_count > 1 && avail_w >= (visible_count as u16).saturating_mul(2) {
1845                let count: u16 = visible_count as u16;
1846                let total_gaps: u16 = count.saturating_sub(1).saturating_mul(TERMINAL_ROW_GAP);
1847                let slot_w: u16 = avail_w.saturating_sub(total_gaps) / count;
1848                if slot_w >= 2 {
1849                    let row_start_y: u16 = *y;
1850                    let mut max_child_end: u16 = row_start_y;
1851                    let mut visible_idx: usize = 0;
1852                    for child_id in tree.children_iter(node_id) {
1853                        if !Self::is_node_visible(tree, child_id) {
1854                            continue;
1855                        }
1856                        let cx: u16 =
1857                            x.saturating_add((visible_idx as u16).saturating_mul(slot_w + 1));
1858                        let rem_w: u16 = avail_w.saturating_sub(cx.saturating_sub(x));
1859                        let col_w: u16 = if visible_idx + 1 == visible_count {
1860                            rem_w
1861                        } else {
1862                            slot_w.min(rem_w)
1863                        };
1864                        let mut cy: u16 = row_start_y;
1865                        let child_region: TerminalRegion =
1866                            TerminalRegion::new(cx, col_w, max_y, focused);
1867                        self.project_node(tree, child_id, child_region, &mut cy);
1868                        if cy > max_child_end {
1869                            max_child_end = cy;
1870                        }
1871                        visible_idx += 1;
1872                    }
1873                    *y = max_child_end;
1874                    return;
1875                }
1876            }
1877        }
1878        for child_id in tree.children_iter(node_id) {
1879            if *y >= max_y {
1880                break;
1881            }
1882            if Self::is_node_visible(tree, child_id) {
1883                self.project_node(tree, child_id, region, y);
1884            }
1885        }
1886    }
1887
1888    /// Projects a `NodeKind::ScrollView` container with zero-allocation visible-range virtualization and a Unicode scrollbar rail.
1889    ///
1890    /// # Arguments
1891    ///
1892    /// - `&Self` - Mutable terminal renderer.
1893    /// - `&SceneTree` - Retained scene tree.
1894    /// - `NodeId` - Scroll container node handle.
1895    /// - `TerminalRegion` - Active character-grid region and focus context.
1896    /// - `&mut u16` - Mutable current row cursor.
1897    fn project_scroll_view(
1898        &mut self,
1899        tree: &SceneTree,
1900        node_id: NodeId,
1901        region: TerminalRegion,
1902        y: &mut u16,
1903    ) {
1904        self.get_mut_tracked_scroll_nodes().push(node_id);
1905        let x: u16 = region.get_x();
1906        let avail_w: u16 = region.get_width();
1907        let max_y: u16 = region.get_max_y();
1908        let focused: Option<NodeId> = region.get_focused();
1909        let Some(node) = tree.get_node(node_id) else {
1910            return;
1911        };
1912        let total_visible: usize = tree
1913            .children_iter(node_id)
1914            .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
1915            .count();
1916        let avail_h: u16 = max_y.saturating_sub(*y);
1917        if avail_h == 0 || total_visible == 0 {
1918            return;
1919        }
1920        let scroll_y: f32 = node.get_layout_box().get_scroll_offset().get_y().max(0.0);
1921        let skip_items: usize = ((scroll_y / TERMINAL_SCROLL_STEP_PX).floor() as usize)
1922            .min(total_visible.saturating_sub(1));
1923        let needs_rail: bool = total_visible > (avail_h as usize) && avail_w >= 3;
1924        let inner_w: u16 = if needs_rail {
1925            avail_w.saturating_sub(1)
1926        } else {
1927            avail_w
1928        };
1929        let child_region: TerminalRegion = TerminalRegion::new(x, inner_w, max_y, focused);
1930        let start_y: u16 = *y;
1931        let mut seen_visible: usize = 0;
1932        for child_id in tree.children_iter(node_id) {
1933            if !Self::is_node_visible(tree, child_id) {
1934                continue;
1935            }
1936            if seen_visible < skip_items {
1937                seen_visible += 1;
1938                continue;
1939            }
1940            if *y >= max_y {
1941                break;
1942            }
1943            self.project_node(tree, child_id, child_region, y);
1944            seen_visible += 1;
1945        }
1946        if needs_rail {
1947            let rail_x: u16 = x.saturating_add(inner_w);
1948            let total_items: usize = total_visible.max(1);
1949            let thumb_offset: u16 = ((skip_items * (avail_h as usize)) / total_items)
1950                .min((avail_h - 1) as usize) as u16;
1951            for offset in 0..avail_h {
1952                let glyph: char = if offset == thumb_offset {
1953                    TERMINAL_SCROLL_THUMB
1954                } else {
1955                    TERMINAL_SCROLL_TRACK
1956                };
1957                let _: u16 = self.get_mut_current().put_cell(
1958                    rail_x,
1959                    start_y.saturating_add(offset),
1960                    TerminalCell::styled(glyph, 1, None, None, false, false, false),
1961                );
1962            }
1963        }
1964    }
1965
1966    /// Writes `text` wrapped across consecutive terminal rows within `region` by Extended Grapheme Clusters without breaking CJK wide glyphs or ZWJ emoji sequences.
1967    ///
1968    /// # Arguments
1969    ///
1970    /// - `&Self` - Mutable terminal renderer.
1971    /// - `TerminalRegion` - Active character-grid region.
1972    /// - `&mut u16` - Mutable current row cursor.
1973    /// - `&str` - UTF-8 text to wrap.
1974    /// - `TerminalCell` - Style template cell.
1975    fn write_wrapped_text(
1976        &mut self,
1977        region: TerminalRegion,
1978        y: &mut u16,
1979        text: &str,
1980        template: TerminalCell,
1981    ) {
1982        let x: u16 = region.get_x();
1983        let avail_w: u16 = region.get_width();
1984        let max_y: u16 = region.get_max_y();
1985        if *y >= max_y || avail_w == 0 {
1986            return;
1987        }
1988        let mut wrote_any_line: bool = false;
1989        for raw_line in text.split('\n') {
1990            if *y >= max_y {
1991                break;
1992            }
1993            if raw_line.is_empty() {
1994                *y = y.saturating_add(1);
1995                wrote_any_line = true;
1996                continue;
1997            }
1998            let raw_bytes: &[u8] = raw_line.as_bytes();
1999            if raw_line.is_ascii() && raw_bytes.iter().all(|b: &u8| (0x20..=0x7E).contains(b)) {
2000                let chunk_len: usize = avail_w as usize;
2001                let mut offset: usize = 0;
2002                while offset < raw_bytes.len() {
2003                    if *y >= max_y {
2004                        return;
2005                    }
2006                    let end: usize = (offset + chunk_len).min(raw_bytes.len());
2007                    let _: u16 = self.get_mut_current().write_printable_ascii_run(
2008                        x,
2009                        *y,
2010                        &raw_bytes[offset..end],
2011                        template,
2012                    );
2013                    offset = end;
2014                    if offset < raw_bytes.len() {
2015                        *y = y.saturating_add(1);
2016                    }
2017                }
2018                *y = y.saturating_add(1);
2019                wrote_any_line = true;
2020                continue;
2021            }
2022            let mut cur_col: u16 = 0;
2023            let mut rest: &str = raw_line;
2024            while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
2025                rest = next_rest;
2026                if cluster.starts_with('\r') {
2027                    continue;
2028                }
2029                let width: u8 = grapheme_display_width(cluster);
2030                if width == 0 {
2031                    continue;
2032                }
2033                let w_u16: u16 = width as u16;
2034                if w_u16 > avail_w {
2035                    continue;
2036                }
2037                if cur_col.saturating_add(w_u16) > avail_w {
2038                    *y = y.saturating_add(1);
2039                    if *y >= max_y {
2040                        return;
2041                    }
2042                    cur_col = 0;
2043                }
2044                let cell: TerminalCell = TerminalCell::from_grapheme(cluster, width, template);
2045                let consumed: u16 = self.get_mut_current().put_cell(x + cur_col, *y, cell);
2046                cur_col = cur_col.saturating_add(consumed);
2047            }
2048            *y = y.saturating_add(1);
2049            wrote_any_line = true;
2050        }
2051        if !wrote_any_line {
2052            *y = y.saturating_add(1);
2053        }
2054    }
2055
2056    /// Encodes the full current grid into `ansi_scratch` using zero-allocation cursor and SGR delta sequences.
2057    ///
2058    /// # Arguments
2059    ///
2060    /// - `&Self` - Mutable terminal renderer.
2061    fn encode_full_frame_into_scratch(&mut self) {
2062        let sync_mode: bool = self.get_sync_output_mode();
2063        let Self {
2064            current,
2065            ansi_scratch,
2066            ..
2067        } = self;
2068        let cols: u16 = current.get_cols();
2069        let rows: u16 = current.get_rows();
2070        let needed: usize = current.total_cells().saturating_mul(2);
2071        if ansi_scratch.capacity() < needed {
2072            ansi_scratch.reserve(needed - ansi_scratch.capacity());
2073        }
2074        if sync_mode {
2075            ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
2076        }
2077        ansi_scratch.push_str(ANSI_CLEAR_AND_HOME);
2078        let mut active_style: Option<TerminalCell> = None;
2079        let mut cursor_pos: Option<(u16, u16)> = Some((0, 0));
2080        for row in 0..rows {
2081            append_cursor_move_smart(ansi_scratch, cursor_pos, 0, row);
2082            cursor_pos = Some((0, row));
2083            let mut col: u16 = 0;
2084            while col < cols {
2085                let Some(cell) = current.cell(col, row) else {
2086                    col += 1;
2087                    continue;
2088                };
2089                if cell.is_continuation() {
2090                    col += 1;
2091                    continue;
2092                }
2093                append_sgr_delta(ansi_scratch, active_style, &cell);
2094                active_style = Some(cell);
2095                cell.push_grapheme_to(ansi_scratch);
2096                let step: u16 = cell.get_width().max(1) as u16;
2097                cursor_pos = Some((col.saturating_add(step), row));
2098                col = col.saturating_add(step);
2099            }
2100        }
2101        ansi_scratch.push_str(ANSI_RESET_STYLE);
2102        if sync_mode {
2103            ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
2104        }
2105    }
2106
2107    /// Encodes only cells changed relative to `previous` into `ansi_scratch`, skipping unchanged rows via row hashes and coalescing short runs and SGR deltas.
2108    ///
2109    /// # Arguments
2110    ///
2111    /// - `&Self` - Mutable terminal renderer.
2112    ///
2113    /// # Returns
2114    ///
2115    /// - `TerminalDiffStats` - Incremental diff telemetry (`is_idle == true` and `0` bytes when identical).
2116    fn encode_diff_frame_into_scratch(&mut self) -> TerminalDiffStats {
2117        let sync_mode: bool = self.get_sync_output_mode();
2118        let Self {
2119            previous,
2120            current,
2121            ansi_scratch,
2122            ..
2123        } = self;
2124        let total_cells: usize = current.total_cells();
2125        let cols: u16 = current.get_cols();
2126        let rows: u16 = current.get_rows();
2127        let mut changed_cells: usize = 0;
2128        let mut active_style: Option<TerminalCell> = None;
2129        let mut cursor_pos: Option<(u16, u16)> = None;
2130        let mut emitted_any: bool = false;
2131        for row in 0..rows {
2132            let row_idx: usize = row as usize;
2133            let cur_hash: Option<u64> = current.get_row_hashes().get(row_idx).copied();
2134            let prev_hash: Option<u64> = previous.get_row_hashes().get(row_idx).copied();
2135            if cur_hash.is_some() && cur_hash == prev_hash {
2136                continue;
2137            }
2138            let mut col: u16 = 0;
2139            while col < cols {
2140                let Some(cur_cell) = current.cell(col, row) else {
2141                    col += 1;
2142                    continue;
2143                };
2144                let Some(prev_cell) = previous.cell(col, row) else {
2145                    col += 1;
2146                    continue;
2147                };
2148                if cur_cell.is_continuation() {
2149                    col += 1;
2150                    continue;
2151                }
2152                let mut cell_dirty: bool =
2153                    Self::is_cell_dirty(current, previous, col, row, cur_cell, prev_cell);
2154                if !cell_dirty
2155                    && let Some((cur_cx, cur_cy)) = cursor_pos
2156                    && cur_cy == row
2157                    && cur_cx == col
2158                    && let Some(active) = active_style
2159                    && active.same_style(&cur_cell)
2160                    && Self::has_dirty_within_gap(current, previous, col, row, cols)
2161                {
2162                    cell_dirty = true;
2163                }
2164                if !cell_dirty {
2165                    col = col.saturating_add(cur_cell.get_width().max(1) as u16);
2166                    continue;
2167                }
2168                if !emitted_any && sync_mode {
2169                    ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
2170                }
2171                emitted_any = true;
2172                let step: u16 = cur_cell.get_width().max(1) as u16;
2173                if cur_cell != prev_cell {
2174                    changed_cells = changed_cells.saturating_add(step as usize);
2175                }
2176                append_cursor_move_smart(ansi_scratch, cursor_pos, col, row);
2177                append_sgr_delta(ansi_scratch, active_style, &cur_cell);
2178                active_style = Some(cur_cell);
2179                cur_cell.push_grapheme_to(ansi_scratch);
2180                cursor_pos = Some((col.saturating_add(step), row));
2181                col = col.saturating_add(step);
2182            }
2183        }
2184        if !emitted_any {
2185            return TerminalDiffStats::new(total_cells, 0, 0, true, false);
2186        }
2187        ansi_scratch.push_str(ANSI_RESET_STYLE);
2188        if sync_mode {
2189            ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
2190        }
2191        let output_bytes: usize = ansi_scratch.len();
2192        TerminalDiffStats::new(
2193            total_cells,
2194            changed_cells.max(1),
2195            output_bytes,
2196            false,
2197            false,
2198        )
2199    }
2200
2201    /// Determines whether cell `(col, row)` must be emitted, including wide-character partner invalidation on both lead and continuation columns.
2202    ///
2203    /// # Arguments
2204    ///
2205    /// - `&TerminalCellGrid` - Active grid.
2206    /// - `&TerminalCellGrid` - Committed previous grid.
2207    /// - `u16` - Zero-based column coordinate.
2208    /// - `u16` - Zero-based row coordinate.
2209    /// - `TerminalCell` - Current cell value.
2210    /// - `TerminalCell` - Previous cell value.
2211    ///
2212    /// # Returns
2213    ///
2214    /// - `bool` - `true` when `(col, row)` requires re-emission.
2215    #[must_use]
2216    fn is_cell_dirty(
2217        current: &TerminalCellGrid,
2218        previous: &TerminalCellGrid,
2219        col: u16,
2220        row: u16,
2221        cur_cell: TerminalCell,
2222        prev_cell: TerminalCell,
2223    ) -> bool {
2224        if cur_cell != prev_cell {
2225            return true;
2226        }
2227        if cur_cell.is_wide_lead()
2228            && col.saturating_add(1) < current.get_cols()
2229            && current.cell(col + 1, row) != previous.cell(col + 1, row)
2230        {
2231            return true;
2232        }
2233        if prev_cell.is_continuation() && !cur_cell.is_continuation() {
2234            return true;
2235        }
2236        if col > 0
2237            && let Some(prev_left) = previous.cell(col - 1, row)
2238            && prev_left.is_wide_lead()
2239            && current.cell(col - 1, row) != Some(prev_left)
2240        {
2241            return true;
2242        }
2243        false
2244    }
2245
2246    /// Checks whether another dirty cell appears within `TERMINAL_COALESCE_GAP_MAX` columns so short same-style gaps avoid expensive cursor-move escapes.
2247    ///
2248    /// # Arguments
2249    ///
2250    /// - `&TerminalCellGrid` - Active grid.
2251    /// - `&TerminalCellGrid` - Committed previous grid.
2252    /// - `u16` - Starting column coordinate.
2253    /// - `u16` - Zero-based row coordinate.
2254    /// - `u16` - Total columns in the grid.
2255    ///
2256    /// # Returns
2257    ///
2258    /// - `bool` - `true` if coalescing across the current cell saves cursor movement.
2259    #[must_use]
2260    fn has_dirty_within_gap(
2261        current: &TerminalCellGrid,
2262        previous: &TerminalCellGrid,
2263        start_col: u16,
2264        row: u16,
2265        cols: u16,
2266    ) -> bool {
2267        let mut probe: u16 = start_col.saturating_add(1);
2268        let max_probe: u16 = start_col
2269            .saturating_add(TERMINAL_COALESCE_GAP_MAX)
2270            .min(cols.saturating_sub(1));
2271        while probe <= max_probe {
2272            if let (Some(c), Some(p)) = (current.cell(probe, row), previous.cell(probe, row))
2273                && !c.is_continuation()
2274                && Self::is_cell_dirty(current, previous, probe, row, c, p)
2275            {
2276                return true;
2277            }
2278            probe = probe.saturating_add(1);
2279        }
2280        false
2281    }
2282}