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`, 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.
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    /// - `&mut W` - Output writer receiving the single batched write.
1162    ///
1163    /// # Returns
1164    ///
1165    /// - `TerminalWriteResult` - Write status, diff stats, and whether double-buffer ownership was swapped.
1166    #[cfg(not(target_arch = "wasm32"))]
1167    pub fn render_tree_to_writer<W>(
1168        &mut self,
1169        tree: &SceneTree,
1170        cols: u16,
1171        rows: u16,
1172        mode: TerminalRenderMode,
1173        writer: &mut W,
1174    ) -> TerminalWriteResult
1175    where
1176        W: Write,
1177    {
1178        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1179        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1180        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1181        if mode == TerminalRenderMode::InteractiveTui {
1182            let fp: TerminalFrameFingerprint =
1183                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1184            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1185                self.set_last_projected_rows(0);
1186                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1187                self.set_skipped_idle_frames(next_skipped);
1188                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1189                self.set_frames_rendered(next_frames);
1190                return TerminalWriteResult {
1191                    status: CliWriteStatus::Written,
1192                    stats: TerminalDiffStats::new(total_cells, 0, 0, true, false),
1193                    swapped: false,
1194                    error_message: None,
1195                };
1196            }
1197        }
1198        let stats: TerminalDiffStats =
1199            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1200        let payload_bytes: &[u8] = self.get_ansi_scratch().as_bytes();
1201        if !payload_bytes.is_empty() {
1202            if let Err(err) = writer.write_all(payload_bytes) {
1203                let status: CliWriteStatus = classify_io_error(&err);
1204                self.invalidate();
1205                return TerminalWriteResult {
1206                    status,
1207                    stats,
1208                    swapped: false,
1209                    error_message: Some(err.to_string()),
1210                };
1211            }
1212            if let Err(err) = writer.flush() {
1213                let status: CliWriteStatus = classify_io_error(&err);
1214                self.invalidate();
1215                return TerminalWriteResult {
1216                    status,
1217                    stats,
1218                    swapped: false,
1219                    error_message: Some(err.to_string()),
1220                };
1221            }
1222        }
1223        let swapped: bool = self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1224        TerminalWriteResult {
1225            status: CliWriteStatus::Written,
1226            stats,
1227            swapped,
1228            error_message: None,
1229        }
1230    }
1231
1232    /// Projects `tree` into `current` and encodes the payload into `ansi_scratch` without mutating `previous`.
1233    ///
1234    /// # Arguments
1235    ///
1236    /// - `&Self` - Mutable terminal renderer.
1237    /// - `&SceneTree` - Retained UI scene tree.
1238    /// - `u16` - Clamped terminal columns.
1239    /// - `u16` - Clamped terminal rows.
1240    /// - `TerminalRenderMode` - Active render mode.
1241    ///
1242    /// # Returns
1243    ///
1244    /// - `TerminalDiffStats` - Per-frame cell diff telemetry.
1245    fn project_and_encode_into_scratch(
1246        &mut self,
1247        tree: &SceneTree,
1248        clamped_cols: u16,
1249        clamped_rows: u16,
1250        mode: TerminalRenderMode,
1251    ) -> TerminalDiffStats {
1252        self.get_mut_current().reset(clamped_cols, clamped_rows);
1253        self.get_mut_tracked_scroll_nodes().clear();
1254        let focused: Option<NodeId> = tree.get_focus().focused_node();
1255        let mut cursor_y: u16 = 0;
1256        let root_region: TerminalRegion =
1257            TerminalRegion::new(0, clamped_cols, clamped_rows, focused);
1258        self.project_node(tree, tree.get_root(), root_region, &mut cursor_y);
1259        self.set_last_projected_rows(cursor_y as usize);
1260        self.get_mut_current().finalize_row_hashes();
1261        let total_cells: usize = self.get_current().total_cells();
1262        self.get_mut_ansi_scratch().clear();
1263        match mode {
1264            TerminalRenderMode::StaticPlainText => {
1265                let plain: String = self.get_current().to_plain_text();
1266                let bytes: usize = plain.len();
1267                self.get_mut_ansi_scratch().push_str(&plain);
1268                TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
1269            }
1270            TerminalRenderMode::InteractiveTui => {
1271                let resized_or_first: bool = !self.get_previous_valid()
1272                    || self.get_last_cols() != clamped_cols
1273                    || self.get_last_rows() != clamped_rows
1274                    || self.get_previous().total_cells() != total_cells;
1275                if resized_or_first {
1276                    self.encode_full_frame_into_scratch();
1277                    let bytes: usize = self.get_ansi_scratch().len();
1278                    TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
1279                } else {
1280                    self.encode_diff_frame_into_scratch()
1281                }
1282            }
1283        }
1284    }
1285
1286    /// Commits double-buffer ownership via zero-clone `swap` after a confirmed interactive write (leaving `previous` untouched in `StaticPlainText` mode).
1287    ///
1288    /// # Arguments
1289    ///
1290    /// - `&Self` - Mutable terminal renderer.
1291    /// - `&SceneTree` - Rendered scene tree.
1292    /// - `u16` - Clamped terminal columns.
1293    /// - `u16` - Clamped terminal rows.
1294    /// - `TerminalRenderMode` - Active render mode.
1295    ///
1296    /// # Returns
1297    ///
1298    /// - `bool` - `true` when `current` and `previous` were swapped.
1299    fn commit_after_write(
1300        &mut self,
1301        tree: &SceneTree,
1302        clamped_cols: u16,
1303        clamped_rows: u16,
1304        mode: TerminalRenderMode,
1305    ) -> bool {
1306        self.set_last_cols(clamped_cols);
1307        self.set_last_rows(clamped_rows);
1308        let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1309        self.set_frames_rendered(next_frames);
1310        if mode == TerminalRenderMode::StaticPlainText {
1311            self.set_previous_valid(false);
1312            let Self {
1313                last_fingerprint, ..
1314            } = self;
1315            *last_fingerprint = None;
1316            return false;
1317        }
1318        let fp: TerminalFrameFingerprint =
1319            self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1320        let Self {
1321            previous,
1322            current,
1323            previous_valid,
1324            last_fingerprint,
1325            ..
1326        } = self;
1327        swap(current, previous);
1328        *previous_valid = true;
1329        *last_fingerprint = Some(fp);
1330        true
1331    }
1332
1333    /// Processes a terminal keyboard event (`Tab`, `Shift+Tab`, arrows, `Enter`, `Escape`, `Ctrl+C`) against `tree`.
1334    ///
1335    /// # Arguments
1336    ///
1337    /// - `&Self` - Mutable terminal renderer.
1338    /// - `&mut SceneTree` - Retained UI scene tree to update focus, scroll, or activation on.
1339    /// - `KeyEvent` - Normalized keyboard event.
1340    ///
1341    /// # Returns
1342    ///
1343    /// - `TerminalNavAction` - Resulting focus, scroll, activation, or exit action.
1344    pub fn handle_key(&mut self, tree: &mut SceneTree, key: KeyEvent) -> TerminalNavAction {
1345        let code: KeyCode = key.get_code();
1346        let mods: Modifiers = key.get_modifiers();
1347        if code == KeyCode::Escape
1348            || (mods.get_ctrl()
1349                && matches!(code, KeyCode::Character('c') | KeyCode::Character('C')))
1350        {
1351            self.set_exit_requested(true);
1352            return TerminalNavAction::ExitRequested;
1353        }
1354        if code == KeyCode::Tab {
1355            let focusables: Vec<NodeId> = Self::collect_focusables(tree);
1356            if focusables.is_empty() {
1357                return TerminalNavAction::Ignored;
1358            }
1359            let current: Option<NodeId> = tree.get_focus().focused_node();
1360            let next_target: NodeId = match current
1361                .and_then(|cur: NodeId| focusables.iter().position(|id: &NodeId| *id == cur))
1362            {
1363                Some(idx) => {
1364                    let next_idx: usize = if mods.get_shift() {
1365                        if idx == 0 {
1366                            focusables.len() - 1
1367                        } else {
1368                            idx - 1
1369                        }
1370                    } else {
1371                        (idx + 1) % focusables.len()
1372                    };
1373                    focusables[next_idx]
1374                }
1375                None => {
1376                    if mods.get_shift() {
1377                        focusables[focusables.len() - 1]
1378                    } else {
1379                        focusables[0]
1380                    }
1381                }
1382            };
1383            let callbacks: Vec<(UiEventHandler, UiEvent)> = tree.update_focus(Some(next_target));
1384            for (handler, ev) in callbacks.into_iter() {
1385                if let Ok(mut cb) = handler.try_borrow_mut() {
1386                    cb(&ev);
1387                }
1388            }
1389            return TerminalNavAction::FocusMoved(next_target);
1390        }
1391        if code == KeyCode::ArrowDown || code == KeyCode::ArrowUp {
1392            let delta_rows: i16 = if code == KeyCode::ArrowDown { 1 } else { -1 };
1393            if let Some(scroll_id) = Self::find_first_scroll_view(tree) {
1394                let current_y: f32 = tree
1395                    .get_node(scroll_id)
1396                    .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
1397                    .unwrap_or(0.0);
1398                let next_y: f32 =
1399                    (current_y + (delta_rows as f32) * TERMINAL_SCROLL_STEP_PX).max(0.0);
1400                tree.set_scroll_offset(scroll_id, Point::new(0.0, next_y));
1401                return TerminalNavAction::Scrolled(delta_rows);
1402            }
1403            return TerminalNavAction::Ignored;
1404        }
1405        if code == KeyCode::Enter {
1406            if let Some(target) = tree.get_focus().focused_node() {
1407                let click_kind: UiEventKind = UiEventKind::Click(Point::default());
1408                let handler_opt: Option<UiEventHandler> = tree
1409                    .get_node(target)
1410                    .and_then(|node: &SceneNode| node.get_handlers().handler_for(&click_kind));
1411                if let Some(handler) = handler_opt
1412                    && let Ok(mut cb) = handler.try_borrow_mut()
1413                {
1414                    let click_ev: UiEvent = UiEvent::new(target, click_kind);
1415                    cb(&click_ev);
1416                }
1417                return TerminalNavAction::Activated(target);
1418            }
1419            return TerminalNavAction::Ignored;
1420        }
1421        TerminalNavAction::Ignored
1422    }
1423
1424    /// Collects all visible focusable or clickable node handles in pre-order traversal.
1425    ///
1426    /// # Arguments
1427    ///
1428    /// - `&SceneTree` - Retained UI scene tree.
1429    ///
1430    /// # Returns
1431    ///
1432    /// - `Vec<NodeId>` - Ordered focus ring candidates.
1433    #[must_use]
1434    fn collect_focusables(tree: &SceneTree) -> Vec<NodeId> {
1435        let mut out: Vec<NodeId> = Vec::new();
1436        let mut stack: Vec<NodeId> = vec![tree.get_root()];
1437        while let Some(id) = stack.pop() {
1438            let Some(node) = tree.get_node(id) else {
1439                continue;
1440            };
1441            if node.style_ref().get_layout().get_display() == Display::None
1442                || node.style_ref().get_paint().get_opacity() <= 0.0
1443            {
1444                continue;
1445            }
1446            if Self::is_focusable_or_interactive(node) {
1447                out.push(id);
1448            }
1449            for child in node.get_children().iter().rev().copied() {
1450                stack.push(child);
1451            }
1452        }
1453        out
1454    }
1455
1456    /// Finds the first visible `NodeKind::ScrollView` node in pre-order traversal.
1457    ///
1458    /// # Arguments
1459    ///
1460    /// - `&SceneTree` - Retained UI scene tree.
1461    ///
1462    /// # Returns
1463    ///
1464    /// - `Option<NodeId>` - First visible scroll container handle.
1465    #[must_use]
1466    fn find_first_scroll_view(tree: &SceneTree) -> Option<NodeId> {
1467        let mut stack: Vec<NodeId> = vec![tree.get_root()];
1468        while let Some(id) = stack.pop() {
1469            let Some(node) = tree.get_node(id) else {
1470                continue;
1471            };
1472            if node.style_ref().get_layout().get_display() == Display::None {
1473                continue;
1474            }
1475            if matches!(node.get_kind(), NodeKind::ScrollView) {
1476                return Some(id);
1477            }
1478            for child in node.get_children().iter().rev().copied() {
1479                stack.push(child);
1480            }
1481        }
1482        None
1483    }
1484
1485    /// Returns `true` when `node` should participate in terminal focus and clickable affordances.
1486    ///
1487    /// # Arguments
1488    ///
1489    /// - `&SceneNode` - Candidate scene node.
1490    ///
1491    /// # Returns
1492    ///
1493    /// - `bool` - Whether the node is focusable or interactive.
1494    #[must_use]
1495    fn is_focusable_or_interactive(node: &SceneNode) -> bool {
1496        node.get_interaction().get_focusable()
1497            || matches!(node.get_kind(), NodeKind::Input(_))
1498            || Self::is_clickable_node(node)
1499    }
1500
1501    /// Returns `true` when `node` acts as a clickable button or interactive trigger.
1502    ///
1503    /// # Arguments
1504    ///
1505    /// - `&SceneNode` - Candidate scene node.
1506    ///
1507    /// # Returns
1508    ///
1509    /// - `bool` - Whether the node has click semantics.
1510    #[must_use]
1511    fn is_clickable_node(node: &SceneNode) -> bool {
1512        node.get_handlers()
1513            .handler_for(&UiEventKind::Click(Point::default()))
1514            .is_some()
1515            || node.style_ref().get_paint().get_cursor() == CursorIcon::Pointer
1516            || node
1517                .a11y_props()
1518                .is_some_and(|a: A11yProps| a.get_role() == A11yRole::Button)
1519    }
1520
1521    /// Returns `true` when a child node is visible for terminal projection.
1522    ///
1523    /// # Arguments
1524    ///
1525    /// - `&SceneTree` - Retained UI scene tree.
1526    /// - `NodeId` - Candidate node handle.
1527    ///
1528    /// # Returns
1529    ///
1530    /// - `bool` - `true` iff node exists, `display != None`, and `opacity > 0.0`.
1531    #[must_use]
1532    fn is_node_visible(tree: &SceneTree, node_id: NodeId) -> bool {
1533        tree.get_node(node_id).is_some_and(|c: &SceneNode| {
1534            c.style_ref().get_layout().get_display() != Display::None
1535                && c.style_ref().get_paint().get_opacity() > 0.0
1536        })
1537    }
1538
1539    /// Collects direct/descendant display label text for a clickable container button.
1540    ///
1541    /// # Arguments
1542    ///
1543    /// - `&SceneTree` - Retained UI scene tree.
1544    /// - `NodeId` - Button container node identifier.
1545    ///
1546    /// # Returns
1547    ///
1548    /// - `String` - Resolved button caption text.
1549    #[must_use]
1550    fn collect_button_label(tree: &SceneTree, node_id: NodeId) -> String {
1551        let Some(node) = tree.get_node(node_id) else {
1552            return String::new();
1553        };
1554        let mut parts: Vec<String> = Vec::new();
1555        let mut stack: Vec<NodeId> = node.get_children().iter().rev().copied().collect();
1556        while let Some(cid) = stack.pop() {
1557            let Some(child) = tree.get_node(cid) else {
1558                continue;
1559            };
1560            if child.style_ref().get_layout().get_display() == Display::None {
1561                continue;
1562            }
1563            if let NodeKind::Text(text) = child.get_kind() {
1564                let trimmed: &str = text.trim();
1565                if !trimmed.is_empty() {
1566                    parts.push(trimmed.to_string());
1567                }
1568            }
1569            for grand in child.get_children().iter().rev().copied() {
1570                stack.push(grand);
1571            }
1572        }
1573        if !parts.is_empty() {
1574            return parts.join(" ");
1575        }
1576        node.a11y_props()
1577            .map(|a: A11yProps| a.get_label().clone())
1578            .unwrap_or_default()
1579    }
1580
1581    /// Projects a single scene node subtree into the current `TerminalCellGrid` using terminal character coordinates directly.
1582    ///
1583    /// # Arguments
1584    ///
1585    /// - `&Self` - Mutable terminal renderer.
1586    /// - `&SceneTree` - Retained scene tree.
1587    /// - `NodeId` - Target node handle to project.
1588    /// - `TerminalRegion` - Active character-grid region and focus context.
1589    /// - `&mut u16` - Mutable current row cursor advanced as content is laid out.
1590    fn project_node(
1591        &mut self,
1592        tree: &SceneTree,
1593        node_id: NodeId,
1594        region: TerminalRegion,
1595        y: &mut u16,
1596    ) {
1597        let x: u16 = region.get_x();
1598        let avail_w: u16 = region.get_width();
1599        let max_y: u16 = region.get_max_y();
1600        let focused: Option<NodeId> = region.get_focused();
1601        if *y >= max_y || avail_w == 0 {
1602            return;
1603        }
1604        let Some(node) = tree.get_node(node_id) else {
1605            return;
1606        };
1607        let style: &Style = node.style_ref();
1608        let layout: LayoutStyle = style.get_layout();
1609        let paint: PaintStyle = style.get_paint();
1610        let text_style: TextStyle = style.get_text();
1611        if layout.get_display() == Display::None || paint.get_opacity() <= 0.0 {
1612            return;
1613        }
1614        let is_focused: bool = focused == Some(node_id) || node.get_interaction().get_focused();
1615        let is_bold: bool = matches!(
1616            text_style.get_weight(),
1617            FontWeight::SemiBold | FontWeight::Bold
1618        );
1619        let fg: Option<Color> = Some(text_style.get_color());
1620        let bg: Option<Color> = paint.background_color();
1621        let template: TerminalCell = TerminalCell::styled(
1622            ' ',
1623            1,
1624            fg,
1625            bg,
1626            is_bold,
1627            is_focused,
1628            text_style.get_underline(),
1629        );
1630        match node.get_kind() {
1631            NodeKind::Text(content) => {
1632                if Self::is_clickable_node(node) {
1633                    let display_str: String = if is_focused {
1634                        format!("> [ {content} ]")
1635                    } else {
1636                        format!("[ {content} ]")
1637                    };
1638                    self.write_wrapped_text(region, y, &display_str, template);
1639                } else {
1640                    self.write_wrapped_text(region, y, content.as_str(), template);
1641                }
1642            }
1643            NodeKind::Input(inp) => {
1644                let inner: String = if inp.get_value().is_empty() {
1645                    inp.get_placeholder().clone()
1646                } else if inp.get_password() {
1647                    let count: usize = inp.get_value().chars().count();
1648                    "*".repeat(count)
1649                } else {
1650                    inp.get_value().clone()
1651                };
1652                let formatted: String = if is_focused {
1653                    if tree.get_caret_visible() {
1654                        format!("> [ {inner}| ]")
1655                    } else {
1656                        format!("> [ {inner}  ]")
1657                    }
1658                } else {
1659                    format!("[ {inner} ]")
1660                };
1661                let _: u16 = self
1662                    .get_mut_current()
1663                    .write_styled_text(x, *y, avail_w, &formatted, template);
1664                *y = y.saturating_add(1);
1665            }
1666            NodeKind::Image(img) => {
1667                let alt: String = node
1668                    .a11y_props()
1669                    .map(|a: A11yProps| a.get_label().clone())
1670                    .filter(|s: &String| !s.is_empty())
1671                    .map(|lbl: String| format!("{TERMINAL_IMAGE_FALLBACK_PREFIX}{lbl}]"))
1672                    .unwrap_or_else(|| {
1673                        format!(
1674                            "{TERMINAL_IMAGE_DIM_PREFIX}{}x{}]",
1675                            img.get_width(),
1676                            img.get_height()
1677                        )
1678                    });
1679                let _: u16 = self
1680                    .get_mut_current()
1681                    .write_styled_text(x, *y, avail_w, &alt, template);
1682                *y = y.saturating_add(1);
1683            }
1684            NodeKind::Canvas => {
1685                let alt: String = node
1686                    .a11y_props()
1687                    .map(|a: A11yProps| a.get_label().clone())
1688                    .filter(|s: &String| !s.is_empty())
1689                    .map(|lbl: String| format!("{TERMINAL_CANVAS_FALLBACK_PREFIX}{lbl}]"))
1690                    .unwrap_or_else(|| TERMINAL_CANVAS_FALLBACK.to_string());
1691                let _: u16 = self
1692                    .get_mut_current()
1693                    .write_styled_text(x, *y, avail_w, &alt, template);
1694                *y = y.saturating_add(1);
1695            }
1696            NodeKind::Fragment => {
1697                for child_id in node.get_children().iter().copied() {
1698                    if *y >= max_y {
1699                        break;
1700                    }
1701                    self.project_node(tree, child_id, region, y);
1702                }
1703            }
1704            NodeKind::ScrollView => {
1705                self.project_scroll_view(tree, node_id, region, y);
1706            }
1707            NodeKind::View | NodeKind::Portal => {
1708                let is_root: bool = node_id == tree.get_root();
1709                if !is_root && Self::is_clickable_node(node) {
1710                    let caption: String = Self::collect_button_label(tree, node_id);
1711                    if !caption.is_empty() {
1712                        let formatted: String = if is_focused {
1713                            format!("> [ {caption} ]")
1714                        } else {
1715                            format!("[ {caption} ]")
1716                        };
1717                        let _: u16 = self
1718                            .get_mut_current()
1719                            .write_styled_text(x, *y, avail_w, &formatted, template);
1720                        *y = y.saturating_add(1);
1721                        return;
1722                    }
1723                }
1724                let has_border: bool = !is_root
1725                    && (paint.get_border().get_width() > 0.0
1726                        || matches!(node.get_kind(), NodeKind::Portal))
1727                    && avail_w >= 4
1728                    && max_y.saturating_sub(*y) >= 3;
1729                if has_border {
1730                    let top_y: u16 = *y;
1731                    let inner_region: TerminalRegion = TerminalRegion::new(
1732                        x.saturating_add(1),
1733                        avail_w.saturating_sub(2),
1734                        max_y.saturating_sub(1),
1735                        focused,
1736                    );
1737                    let mut child_y: u16 = top_y.saturating_add(1);
1738                    self.project_children_flow(tree, node, inner_region, &mut child_y);
1739                    let box_h: u16 = child_y
1740                        .saturating_sub(top_y)
1741                        .saturating_add(1)
1742                        .max(3)
1743                        .min(max_y.saturating_sub(top_y));
1744                    let border_cell: TerminalCell = TerminalCell::styled(
1745                        ' ',
1746                        1,
1747                        Some(paint.get_border().get_color()),
1748                        bg,
1749                        false,
1750                        is_focused,
1751                        false,
1752                    );
1753                    self.get_mut_current()
1754                        .draw_box(x, top_y, avail_w, box_h, border_cell);
1755                    *y = top_y.saturating_add(box_h);
1756                } else {
1757                    self.project_children_flow(tree, node, region, y);
1758                }
1759            }
1760        }
1761    }
1762
1763    /// Projects children of a container respecting row, column, and grid directions directly in character columns.
1764    ///
1765    /// # Arguments
1766    ///
1767    /// - `&Self` - Mutable terminal renderer.
1768    /// - `&SceneTree` - Retained scene tree.
1769    /// - `&SceneNode` - Container scene node.
1770    /// - `TerminalRegion` - Active character-grid region and focus context.
1771    /// - `&mut u16` - Mutable current row cursor.
1772    fn project_children_flow(
1773        &mut self,
1774        tree: &SceneTree,
1775        node: &SceneNode,
1776        region: TerminalRegion,
1777        y: &mut u16,
1778    ) {
1779        let x: u16 = region.get_x();
1780        let avail_w: u16 = region.get_width();
1781        let max_y: u16 = region.get_max_y();
1782        let focused: Option<NodeId> = region.get_focused();
1783        let children: &[NodeId] = node.get_children().as_slice();
1784        let layout: LayoutStyle = node.style_ref().get_layout();
1785        let is_row: bool = matches!(
1786            layout.get_flex_direction(),
1787            FlexDirection::Row | FlexDirection::RowReverse
1788        ) && layout.get_display() == Display::Flex;
1789        if is_row {
1790            let visible_count: usize = children
1791                .iter()
1792                .copied()
1793                .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
1794                .count();
1795            if visible_count > 1 && avail_w >= (visible_count as u16).saturating_mul(2) {
1796                let count: u16 = visible_count as u16;
1797                let total_gaps: u16 = count.saturating_sub(1).saturating_mul(TERMINAL_ROW_GAP);
1798                let slot_w: u16 = avail_w.saturating_sub(total_gaps) / count;
1799                if slot_w >= 2 {
1800                    let row_start_y: u16 = *y;
1801                    let mut max_child_end: u16 = row_start_y;
1802                    let mut visible_idx: usize = 0;
1803                    for child_id in children.iter().copied() {
1804                        if !Self::is_node_visible(tree, child_id) {
1805                            continue;
1806                        }
1807                        let cx: u16 =
1808                            x.saturating_add((visible_idx as u16).saturating_mul(slot_w + 1));
1809                        let rem_w: u16 = avail_w.saturating_sub(cx.saturating_sub(x));
1810                        let col_w: u16 = if visible_idx + 1 == visible_count {
1811                            rem_w
1812                        } else {
1813                            slot_w.min(rem_w)
1814                        };
1815                        let mut cy: u16 = row_start_y;
1816                        let child_region: TerminalRegion =
1817                            TerminalRegion::new(cx, col_w, max_y, focused);
1818                        self.project_node(tree, child_id, child_region, &mut cy);
1819                        if cy > max_child_end {
1820                            max_child_end = cy;
1821                        }
1822                        visible_idx += 1;
1823                    }
1824                    *y = max_child_end;
1825                    return;
1826                }
1827            }
1828        }
1829        for child_id in children.iter().copied() {
1830            if *y >= max_y {
1831                break;
1832            }
1833            if Self::is_node_visible(tree, child_id) {
1834                self.project_node(tree, child_id, region, y);
1835            }
1836        }
1837    }
1838
1839    /// Projects a `NodeKind::ScrollView` container with zero-allocation visible-range virtualization and a Unicode scrollbar rail.
1840    ///
1841    /// # Arguments
1842    ///
1843    /// - `&Self` - Mutable terminal renderer.
1844    /// - `&SceneTree` - Retained scene tree.
1845    /// - `NodeId` - Scroll container node handle.
1846    /// - `TerminalRegion` - Active character-grid region and focus context.
1847    /// - `&mut u16` - Mutable current row cursor.
1848    fn project_scroll_view(
1849        &mut self,
1850        tree: &SceneTree,
1851        node_id: NodeId,
1852        region: TerminalRegion,
1853        y: &mut u16,
1854    ) {
1855        self.get_mut_tracked_scroll_nodes().push(node_id);
1856        let x: u16 = region.get_x();
1857        let avail_w: u16 = region.get_width();
1858        let max_y: u16 = region.get_max_y();
1859        let focused: Option<NodeId> = region.get_focused();
1860        let Some(node) = tree.get_node(node_id) else {
1861            return;
1862        };
1863        let children: &[NodeId] = node.get_children().as_slice();
1864        let total_visible: usize = children
1865            .iter()
1866            .copied()
1867            .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
1868            .count();
1869        let avail_h: u16 = max_y.saturating_sub(*y);
1870        if avail_h == 0 || total_visible == 0 {
1871            return;
1872        }
1873        let scroll_y: f32 = node.get_layout_box().get_scroll_offset().get_y().max(0.0);
1874        let skip_items: usize = ((scroll_y / TERMINAL_SCROLL_STEP_PX).floor() as usize)
1875            .min(total_visible.saturating_sub(1));
1876        let needs_rail: bool = total_visible > (avail_h as usize) && avail_w >= 3;
1877        let inner_w: u16 = if needs_rail {
1878            avail_w.saturating_sub(1)
1879        } else {
1880            avail_w
1881        };
1882        let child_region: TerminalRegion = TerminalRegion::new(x, inner_w, max_y, focused);
1883        let start_y: u16 = *y;
1884        let mut seen_visible: usize = 0;
1885        for child_id in children.iter().copied() {
1886            if !Self::is_node_visible(tree, child_id) {
1887                continue;
1888            }
1889            if seen_visible < skip_items {
1890                seen_visible += 1;
1891                continue;
1892            }
1893            if *y >= max_y {
1894                break;
1895            }
1896            self.project_node(tree, child_id, child_region, y);
1897            seen_visible += 1;
1898        }
1899        if needs_rail {
1900            let rail_x: u16 = x.saturating_add(inner_w);
1901            let total_items: usize = total_visible.max(1);
1902            let thumb_offset: u16 = ((skip_items * (avail_h as usize)) / total_items)
1903                .min((avail_h - 1) as usize) as u16;
1904            for offset in 0..avail_h {
1905                let glyph: char = if offset == thumb_offset {
1906                    TERMINAL_SCROLL_THUMB
1907                } else {
1908                    TERMINAL_SCROLL_TRACK
1909                };
1910                let _: u16 = self.get_mut_current().put_cell(
1911                    rail_x,
1912                    start_y.saturating_add(offset),
1913                    TerminalCell::styled(glyph, 1, None, None, false, false, false),
1914                );
1915            }
1916        }
1917    }
1918
1919    /// Writes `text` wrapped across consecutive terminal rows within `region` by Extended Grapheme Clusters without breaking CJK wide glyphs or ZWJ emoji sequences.
1920    ///
1921    /// # Arguments
1922    ///
1923    /// - `&Self` - Mutable terminal renderer.
1924    /// - `TerminalRegion` - Active character-grid region.
1925    /// - `&mut u16` - Mutable current row cursor.
1926    /// - `&str` - UTF-8 text to wrap.
1927    /// - `TerminalCell` - Style template cell.
1928    fn write_wrapped_text(
1929        &mut self,
1930        region: TerminalRegion,
1931        y: &mut u16,
1932        text: &str,
1933        template: TerminalCell,
1934    ) {
1935        let x: u16 = region.get_x();
1936        let avail_w: u16 = region.get_width();
1937        let max_y: u16 = region.get_max_y();
1938        if *y >= max_y || avail_w == 0 {
1939            return;
1940        }
1941        let mut wrote_any_line: bool = false;
1942        for raw_line in text.split('\n') {
1943            if *y >= max_y {
1944                break;
1945            }
1946            if raw_line.is_empty() {
1947                *y = y.saturating_add(1);
1948                wrote_any_line = true;
1949                continue;
1950            }
1951            let raw_bytes: &[u8] = raw_line.as_bytes();
1952            if raw_line.is_ascii() && raw_bytes.iter().all(|b: &u8| (0x20..=0x7E).contains(b)) {
1953                let chunk_len: usize = avail_w as usize;
1954                let mut offset: usize = 0;
1955                while offset < raw_bytes.len() {
1956                    if *y >= max_y {
1957                        return;
1958                    }
1959                    let end: usize = (offset + chunk_len).min(raw_bytes.len());
1960                    let _: u16 = self.get_mut_current().write_printable_ascii_run(
1961                        x,
1962                        *y,
1963                        &raw_bytes[offset..end],
1964                        template,
1965                    );
1966                    offset = end;
1967                    if offset < raw_bytes.len() {
1968                        *y = y.saturating_add(1);
1969                    }
1970                }
1971                *y = y.saturating_add(1);
1972                wrote_any_line = true;
1973                continue;
1974            }
1975            let mut cur_col: u16 = 0;
1976            let mut rest: &str = raw_line;
1977            while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
1978                rest = next_rest;
1979                if cluster.starts_with('\r') {
1980                    continue;
1981                }
1982                let width: u8 = grapheme_display_width(cluster);
1983                if width == 0 {
1984                    continue;
1985                }
1986                let w_u16: u16 = width as u16;
1987                if w_u16 > avail_w {
1988                    continue;
1989                }
1990                if cur_col.saturating_add(w_u16) > avail_w {
1991                    *y = y.saturating_add(1);
1992                    if *y >= max_y {
1993                        return;
1994                    }
1995                    cur_col = 0;
1996                }
1997                let cell: TerminalCell = TerminalCell::from_grapheme(cluster, width, template);
1998                let consumed: u16 = self.get_mut_current().put_cell(x + cur_col, *y, cell);
1999                cur_col = cur_col.saturating_add(consumed);
2000            }
2001            *y = y.saturating_add(1);
2002            wrote_any_line = true;
2003        }
2004        if !wrote_any_line {
2005            *y = y.saturating_add(1);
2006        }
2007    }
2008
2009    /// Encodes the full current grid into `ansi_scratch` using zero-allocation cursor and SGR delta sequences.
2010    ///
2011    /// # Arguments
2012    ///
2013    /// - `&Self` - Mutable terminal renderer.
2014    fn encode_full_frame_into_scratch(&mut self) {
2015        let sync_mode: bool = self.get_sync_output_mode();
2016        let Self {
2017            current,
2018            ansi_scratch,
2019            ..
2020        } = self;
2021        let cols: u16 = current.get_cols();
2022        let rows: u16 = current.get_rows();
2023        let needed: usize = current.total_cells().saturating_mul(2);
2024        if ansi_scratch.capacity() < needed {
2025            ansi_scratch.reserve(needed - ansi_scratch.capacity());
2026        }
2027        if sync_mode {
2028            ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
2029        }
2030        ansi_scratch.push_str(ANSI_CLEAR_AND_HOME);
2031        let mut active_style: Option<TerminalCell> = None;
2032        let mut cursor_pos: Option<(u16, u16)> = Some((0, 0));
2033        for row in 0..rows {
2034            append_cursor_move_smart(ansi_scratch, cursor_pos, 0, row);
2035            cursor_pos = Some((0, row));
2036            let mut col: u16 = 0;
2037            while col < cols {
2038                let Some(cell) = current.cell(col, row) else {
2039                    col += 1;
2040                    continue;
2041                };
2042                if cell.is_continuation() {
2043                    col += 1;
2044                    continue;
2045                }
2046                append_sgr_delta(ansi_scratch, active_style, &cell);
2047                active_style = Some(cell);
2048                cell.push_grapheme_to(ansi_scratch);
2049                let step: u16 = cell.get_width().max(1) as u16;
2050                cursor_pos = Some((col.saturating_add(step), row));
2051                col = col.saturating_add(step);
2052            }
2053        }
2054        ansi_scratch.push_str(ANSI_RESET_STYLE);
2055        if sync_mode {
2056            ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
2057        }
2058    }
2059
2060    /// Encodes only cells changed relative to `previous` into `ansi_scratch`, skipping unchanged rows via row hashes and coalescing short runs and SGR deltas.
2061    ///
2062    /// # Arguments
2063    ///
2064    /// - `&Self` - Mutable terminal renderer.
2065    ///
2066    /// # Returns
2067    ///
2068    /// - `TerminalDiffStats` - Incremental diff telemetry (`is_idle == true` and `0` bytes when identical).
2069    fn encode_diff_frame_into_scratch(&mut self) -> TerminalDiffStats {
2070        let sync_mode: bool = self.get_sync_output_mode();
2071        let Self {
2072            previous,
2073            current,
2074            ansi_scratch,
2075            ..
2076        } = self;
2077        let total_cells: usize = current.total_cells();
2078        let cols: u16 = current.get_cols();
2079        let rows: u16 = current.get_rows();
2080        let mut changed_cells: usize = 0;
2081        let mut active_style: Option<TerminalCell> = None;
2082        let mut cursor_pos: Option<(u16, u16)> = None;
2083        let mut emitted_any: bool = false;
2084        for row in 0..rows {
2085            let row_idx: usize = row as usize;
2086            let cur_hash: Option<u64> = current.get_row_hashes().get(row_idx).copied();
2087            let prev_hash: Option<u64> = previous.get_row_hashes().get(row_idx).copied();
2088            if cur_hash.is_some() && cur_hash == prev_hash {
2089                continue;
2090            }
2091            let mut col: u16 = 0;
2092            while col < cols {
2093                let Some(cur_cell) = current.cell(col, row) else {
2094                    col += 1;
2095                    continue;
2096                };
2097                let Some(prev_cell) = previous.cell(col, row) else {
2098                    col += 1;
2099                    continue;
2100                };
2101                if cur_cell.is_continuation() {
2102                    col += 1;
2103                    continue;
2104                }
2105                let mut cell_dirty: bool =
2106                    Self::is_cell_dirty(current, previous, col, row, cur_cell, prev_cell);
2107                if !cell_dirty
2108                    && let Some((cur_cx, cur_cy)) = cursor_pos
2109                    && cur_cy == row
2110                    && cur_cx == col
2111                    && let Some(active) = active_style
2112                    && active.same_style(&cur_cell)
2113                    && Self::has_dirty_within_gap(current, previous, col, row, cols)
2114                {
2115                    cell_dirty = true;
2116                }
2117                if !cell_dirty {
2118                    col = col.saturating_add(cur_cell.get_width().max(1) as u16);
2119                    continue;
2120                }
2121                if !emitted_any && sync_mode {
2122                    ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
2123                }
2124                emitted_any = true;
2125                let step: u16 = cur_cell.get_width().max(1) as u16;
2126                if cur_cell != prev_cell {
2127                    changed_cells = changed_cells.saturating_add(step as usize);
2128                }
2129                append_cursor_move_smart(ansi_scratch, cursor_pos, col, row);
2130                append_sgr_delta(ansi_scratch, active_style, &cur_cell);
2131                active_style = Some(cur_cell);
2132                cur_cell.push_grapheme_to(ansi_scratch);
2133                cursor_pos = Some((col.saturating_add(step), row));
2134                col = col.saturating_add(step);
2135            }
2136        }
2137        if !emitted_any {
2138            return TerminalDiffStats::new(total_cells, 0, 0, true, false);
2139        }
2140        ansi_scratch.push_str(ANSI_RESET_STYLE);
2141        if sync_mode {
2142            ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
2143        }
2144        let output_bytes: usize = ansi_scratch.len();
2145        TerminalDiffStats::new(
2146            total_cells,
2147            changed_cells.max(1),
2148            output_bytes,
2149            false,
2150            false,
2151        )
2152    }
2153
2154    /// Determines whether cell `(col, row)` must be emitted, including wide-character partner invalidation on both lead and continuation columns.
2155    ///
2156    /// # Arguments
2157    ///
2158    /// - `&TerminalCellGrid` - Active grid.
2159    /// - `&TerminalCellGrid` - Committed previous grid.
2160    /// - `u16` - Zero-based column coordinate.
2161    /// - `u16` - Zero-based row coordinate.
2162    /// - `TerminalCell` - Current cell value.
2163    /// - `TerminalCell` - Previous cell value.
2164    ///
2165    /// # Returns
2166    ///
2167    /// - `bool` - `true` when `(col, row)` requires re-emission.
2168    #[must_use]
2169    fn is_cell_dirty(
2170        current: &TerminalCellGrid,
2171        previous: &TerminalCellGrid,
2172        col: u16,
2173        row: u16,
2174        cur_cell: TerminalCell,
2175        prev_cell: TerminalCell,
2176    ) -> bool {
2177        if cur_cell != prev_cell {
2178            return true;
2179        }
2180        if cur_cell.is_wide_lead()
2181            && col.saturating_add(1) < current.get_cols()
2182            && current.cell(col + 1, row) != previous.cell(col + 1, row)
2183        {
2184            return true;
2185        }
2186        if prev_cell.is_continuation() && !cur_cell.is_continuation() {
2187            return true;
2188        }
2189        if col > 0
2190            && let Some(prev_left) = previous.cell(col - 1, row)
2191            && prev_left.is_wide_lead()
2192            && current.cell(col - 1, row) != Some(prev_left)
2193        {
2194            return true;
2195        }
2196        false
2197    }
2198
2199    /// Checks whether another dirty cell appears within `TERMINAL_COALESCE_GAP_MAX` columns so short same-style gaps avoid expensive cursor-move escapes.
2200    ///
2201    /// # Arguments
2202    ///
2203    /// - `&TerminalCellGrid` - Active grid.
2204    /// - `&TerminalCellGrid` - Committed previous grid.
2205    /// - `u16` - Starting column coordinate.
2206    /// - `u16` - Zero-based row coordinate.
2207    /// - `u16` - Total columns in the grid.
2208    ///
2209    /// # Returns
2210    ///
2211    /// - `bool` - `true` if coalescing across the current cell saves cursor movement.
2212    #[must_use]
2213    fn has_dirty_within_gap(
2214        current: &TerminalCellGrid,
2215        previous: &TerminalCellGrid,
2216        start_col: u16,
2217        row: u16,
2218        cols: u16,
2219    ) -> bool {
2220        let mut probe: u16 = start_col.saturating_add(1);
2221        let max_probe: u16 = start_col
2222            .saturating_add(TERMINAL_COALESCE_GAP_MAX)
2223            .min(cols.saturating_sub(1));
2224        while probe <= max_probe {
2225            if let (Some(c), Some(p)) = (current.cell(probe, row), previous.cell(probe, row))
2226                && !c.is_continuation()
2227                && Self::is_cell_dirty(current, previous, probe, row, c, p)
2228            {
2229                return true;
2230            }
2231            probe = probe.saturating_add(1);
2232        }
2233        false
2234    }
2235}