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