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(|blue_val: &u8| (0x20..=0x7E).contains(blue_val))
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(
743        &mut self,
744        pos_x: u16,
745        pos_y: u16,
746        width_val: u16,
747        height_val: u16,
748        style_cell: TerminalCell,
749    ) {
750        if width_val < 2 || height_val < 2 {
751            return;
752        }
753        let right: u16 = pos_x.saturating_add(width_val - 1);
754        let bottom: u16 = pos_y.saturating_add(height_val - 1);
755        let fg: Option<Color> = style_cell.fg_color();
756        let bg: Option<Color> = style_cell.bg_color();
757        let bold: bool = style_cell.get_bold();
758        let rev: bool = style_cell.get_reverse();
759        let ul: bool = style_cell.get_underline();
760        let _: u16 = self.put_cell(
761            pos_x,
762            pos_y,
763            TerminalCell::styled(TERMINAL_BOX_TOP_LEFT, 1, fg, bg, bold, rev, ul),
764        );
765        let _: u16 = self.put_cell(
766            right,
767            pos_y,
768            TerminalCell::styled(TERMINAL_BOX_TOP_RIGHT, 1, fg, bg, bold, rev, ul),
769        );
770        let _: u16 = self.put_cell(
771            pos_x,
772            bottom,
773            TerminalCell::styled(TERMINAL_BOX_BOTTOM_LEFT, 1, fg, bg, bold, rev, ul),
774        );
775        let _: u16 = self.put_cell(
776            right,
777            bottom,
778            TerminalCell::styled(TERMINAL_BOX_BOTTOM_RIGHT, 1, fg, bg, bold, rev, ul),
779        );
780        let horiz: TerminalCell =
781            TerminalCell::styled(TERMINAL_BOX_HORIZONTAL, 1, fg, bg, bold, rev, ul);
782        let mut cx: u16 = pos_x + 1;
783        while cx < right {
784            let _: u16 = self.put_cell(cx, pos_y, horiz);
785            let _: u16 = self.put_cell(cx, bottom, horiz);
786            cx += 1;
787        }
788        let vert: TerminalCell =
789            TerminalCell::styled(TERMINAL_BOX_VERTICAL, 1, fg, bg, bold, rev, ul);
790        let mut cy: u16 = pos_y + 1;
791        while cy < bottom {
792            let _: u16 = self.put_cell(pos_x, cy, vert);
793            let _: u16 = self.put_cell(right, cy, vert);
794            cy += 1;
795        }
796    }
797
798    /// Serializes the grid into clean UTF-8 lines with full Extended Grapheme Clusters and zero ANSI escape sequences for piped CLI stdout.
799    ///
800    /// # Arguments
801    ///
802    /// - `&Self` - Grid reference.
803    ///
804    /// # Returns
805    ///
806    /// - `String` - Plain-text UTF-8 representation trimmed of trailing whitespace per line and trailing blank lines.
807    #[must_use]
808    pub fn to_plain_text(&self) -> String {
809        let cols: usize = self.get_cols() as usize;
810        let rows: usize = self.get_rows() as usize;
811        let cells: &[TerminalCell] = self.get_cells().as_slice();
812        let mut lines: Vec<String> = Vec::with_capacity(rows);
813        for row in 0..rows {
814            let start: usize = row * cols;
815            let end: usize = (start + cols).min(cells.len());
816            let mut line: String = String::with_capacity(cols);
817            for cell in &cells[start..end] {
818                if cell.is_continuation() {
819                    continue;
820                }
821                cell.push_grapheme_to(&mut line);
822            }
823            let trimmed_len: usize = line.trim_end().len();
824            line.truncate(trimmed_len);
825            lines.push(line);
826        }
827        while let Some(last) = lines.last() {
828            if last.is_empty() {
829                let _: Option<String> = lines.pop();
830            } else {
831                break;
832            }
833        }
834        lines.join("\n")
835    }
836}
837
838/// Session lifecycle entry and idempotent ANSI state restoration for `TerminalSessionGuard`.
839impl TerminalSessionGuard {
840    /// Builds the escape sequence required to enter the configured interactive terminal modes.
841    ///
842    /// # Arguments
843    ///
844    /// - `bool` - Whether to enter the alternate screen buffer.
845    /// - `bool` - Whether to hide the terminal cursor.
846    /// - `bool` - Whether to enable raw bracketed input mode.
847    ///
848    /// # Returns
849    ///
850    /// - `String` - Concatenated ANSI enter sequence.
851    #[must_use]
852    pub fn build_enter_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
853        let mut out: String = String::new();
854        if alt_screen {
855            out.push_str(ANSI_ENTER_ALT_SCREEN);
856        }
857        if cursor_hidden {
858            out.push_str(ANSI_HIDE_CURSOR);
859        }
860        if raw_mode {
861            out.push_str(ANSI_ENTER_RAW_MODES);
862        }
863        out
864    }
865
866    /// Builds the escape sequence required to cleanly restore terminal state upon exit or unwind.
867    ///
868    /// # Arguments
869    ///
870    /// - `bool` - Whether alternate screen mode was entered.
871    /// - `bool` - Whether cursor visibility was hidden.
872    /// - `bool` - Whether raw input modes were enabled.
873    ///
874    /// # Returns
875    ///
876    /// - `String` - Concatenated ANSI restoration sequence.
877    #[must_use]
878    pub fn build_restore_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
879        let mut out: String = String::from(ANSI_RESET_STYLE);
880        if raw_mode {
881            out.push_str(ANSI_LEAVE_RAW_MODES);
882        }
883        if cursor_hidden {
884            out.push_str(ANSI_SHOW_CURSOR);
885        }
886        if alt_screen {
887            out.push_str(ANSI_LEAVE_ALT_SCREEN);
888        }
889        out
890    }
891
892    /// Enters an interactive terminal session writing enter/restore sequences to an optional capture buffer.
893    ///
894    /// # Arguments
895    ///
896    /// - `bool` - Enter alternate screen buffer.
897    /// - `bool` - Hide terminal cursor.
898    /// - `bool` - Enable raw input tracking modes.
899    /// - `Option<Rc<RefCell<String>>>` - Optional capture buffer for deterministic testing or virtual PTYs.
900    ///
901    /// # Returns
902    ///
903    /// - `Self` - Active RAII session guard.
904    #[must_use]
905    pub fn enter_captured(
906        alt_screen: bool,
907        cursor_hidden: bool,
908        raw_mode: bool,
909        sink: Option<Rc<RefCell<String>>>,
910    ) -> Self {
911        let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
912        if let Some(buf) = sink.as_ref()
913            && let Ok(mut guard) = buf.try_borrow_mut()
914        {
915            guard.push_str(&enter_seq);
916        }
917        Self {
918            alt_screen,
919            cursor_hidden,
920            raw_mode,
921            restored: false,
922            write_to_stdout: false,
923            sink,
924        }
925    }
926
927    /// Enters an interactive terminal session flushing enter and restore sequences directly to stdout on native targets.
928    ///
929    /// # Arguments
930    ///
931    /// - `bool` - Enter alternate screen buffer.
932    /// - `bool` - Hide terminal cursor.
933    /// - `bool` - Enable raw input tracking modes.
934    ///
935    /// # Returns
936    ///
937    /// - `Self` - Active RAII session guard bound to stdout.
938    #[must_use]
939    pub fn enter_stdout(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> Self {
940        let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
941        #[cfg(not(target_arch = "wasm32"))]
942        {
943            let mut stdout: io::Stdout = io::stdout();
944            let _: io::Result<()> = stdout.write_all(enter_seq.as_bytes());
945            let _: io::Result<()> = stdout.flush();
946        }
947        #[cfg(target_arch = "wasm32")]
948        let _: &String = &enter_seq;
949        Self {
950            alt_screen,
951            cursor_hidden,
952            raw_mode,
953            restored: false,
954            write_to_stdout: true,
955            sink: None,
956        }
957    }
958
959    /// Restores terminal state immediately if not already restored and returns the emitted ANSI sequence.
960    ///
961    /// # Arguments
962    ///
963    /// - `&Self` - Mutable session guard.
964    ///
965    /// # Returns
966    ///
967    /// - `String` - Restoration escape sequence emitted (empty if already restored).
968    pub fn restore_now(&mut self) -> String {
969        if self.get_restored() {
970            return String::new();
971        }
972        self.set_restored(true);
973        let seq: String = Self::build_restore_sequence(
974            self.get_alt_screen(),
975            self.get_cursor_hidden(),
976            self.get_raw_mode(),
977        );
978        let write_stdout: bool = self.get_write_to_stdout();
979        let Self { sink, .. } = self;
980        if let Some(buf) = sink.as_ref()
981            && let Ok(mut guard) = buf.try_borrow_mut()
982        {
983            guard.push_str(&seq);
984        }
985        #[cfg(not(target_arch = "wasm32"))]
986        if write_stdout {
987            let mut stdout: io::Stdout = io::stdout();
988            let _: io::Result<()> = stdout.write_all(seq.as_bytes());
989            let _: io::Result<()> = stdout.flush();
990        }
991        #[cfg(target_arch = "wasm32")]
992        let _: bool = write_stdout;
993        seq
994    }
995}
996
997/// Guaranteed RAII restoration of cursor, raw mode, and alternate screen on normal exit or panic unwind.
998impl Drop for TerminalSessionGuard {
999    /// Restores terminal modes automatically when the guard leaves scope.
1000    ///
1001    /// # Arguments
1002    ///
1003    /// - `&Self` - Mutable session guard being dropped.
1004    fn drop(&mut self) {
1005        let _: String = self.restore_now();
1006    }
1007}
1008
1009/// Double-buffered semantic scene projection, zero-work idle short-circuit, virtualized scroll projection, and coalesced ANSI diff encoding for `TerminalRenderer`.
1010impl TerminalRenderer {
1011    /// Creates a fresh `TerminalRenderer` with empty diff history.
1012    ///
1013    /// # Returns
1014    ///
1015    /// - `Self` - Initialized terminal renderer.
1016    #[must_use]
1017    pub fn new() -> Self {
1018        Self::default()
1019    }
1020
1021    /// Returns `true` when the persistent previous-frame back buffer has been allocated and holds a committed interactive frame.
1022    ///
1023    /// # Arguments
1024    ///
1025    /// - `&Self` - Terminal renderer reference.
1026    ///
1027    /// # Returns
1028    ///
1029    /// - `bool` - `true` iff a committed previous grid exists (always `false` in `StaticPlainText`-only runs).
1030    #[must_use]
1031    pub fn has_previous_frame(&self) -> bool {
1032        self.get_previous_valid() && !self.get_previous().get_cells().is_empty()
1033    }
1034
1035    /// Returns the last committed frame fingerprint used for O(1) idle short-circuiting.
1036    ///
1037    /// # Arguments
1038    ///
1039    /// - `&Self` - Terminal renderer reference.
1040    ///
1041    /// # Returns
1042    ///
1043    /// - `Option<TerminalFrameFingerprint>` - Cached frame fingerprint if valid.
1044    #[must_use]
1045    pub const fn last_fingerprint(&self) -> Option<TerminalFrameFingerprint> {
1046        let Self {
1047            last_fingerprint, ..
1048        } = *self;
1049        last_fingerprint
1050    }
1051
1052    /// Marks the previous-frame back buffer invalid without deallocating its storage, forcing a clean full synchronization on the next interactive render.
1053    ///
1054    /// # Arguments
1055    ///
1056    /// - `&Self` - Mutable terminal renderer.
1057    pub fn invalidate(&mut self) {
1058        self.set_previous_valid(false);
1059        let Self {
1060            last_fingerprint, ..
1061        } = self;
1062        *last_fingerprint = None;
1063    }
1064
1065    /// 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.
1066    ///
1067    /// # Arguments
1068    ///
1069    /// - `&Self` - Terminal renderer reference.
1070    /// - `&SceneTree` - Retained UI scene tree.
1071    /// - `u16` - Clamped terminal column count.
1072    /// - `u16` - Clamped terminal row count.
1073    /// - `TerminalRenderMode` - Active render mode.
1074    ///
1075    /// # Returns
1076    ///
1077    /// - `TerminalFrameFingerprint` - Frame fingerprint for idle detection.
1078    #[must_use]
1079    fn compute_fingerprint(
1080        &self,
1081        tree: &SceneTree,
1082        cols: u16,
1083        rows: u16,
1084        mode: TerminalRenderMode,
1085    ) -> TerminalFrameFingerprint {
1086        let focused: Option<NodeId> = tree.get_focus().focused_node();
1087        let focused_caret_offset: usize = focused
1088            .and_then(|id: NodeId| tree.get_node(id))
1089            .map(|node: &SceneNode| match node.get_kind() {
1090                NodeKind::Input(input_state) => input_state.get_caret(),
1091                _ => 0,
1092            })
1093            .unwrap_or(0);
1094        let mut scroll_hash: u64 = TERMINAL_FNV_OFFSET_BASIS;
1095        for scroll_id in self.get_tracked_scroll_nodes().iter().copied() {
1096            if let Some(node) = tree.get_node(scroll_id) {
1097                let off: Point = node.get_layout_box().get_scroll_offset();
1098                scroll_hash = fnv1a_mix_u64(scroll_hash, off.get_x().to_bits() as u64);
1099                scroll_hash = fnv1a_mix_u64(scroll_hash, off.get_y().to_bits() as u64);
1100            }
1101        }
1102        TerminalFrameFingerprint {
1103            scene_revision: tree.get_revision(),
1104            focused,
1105            caret_visible: tree.get_caret_visible(),
1106            focused_caret_offset,
1107            scroll_hash,
1108            cols,
1109            rows,
1110            mode,
1111        }
1112    }
1113
1114    /// 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.
1115    ///
1116    /// # Arguments
1117    ///
1118    /// - `&Self` - Mutable terminal renderer.
1119    /// - `&SceneTree` - Retained UI scene tree to project.
1120    /// - `u16` - Terminal viewport width in columns.
1121    /// - `u16` - Terminal viewport height in rows.
1122    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
1123    ///
1124    /// # Returns
1125    ///
1126    /// - `(String, TerminalDiffStats)` - Rendered UTF-8 terminal payload and cell-diff telemetry.
1127    pub fn render_tree(
1128        &mut self,
1129        tree: &SceneTree,
1130        cols: u16,
1131        rows: u16,
1132        mode: TerminalRenderMode,
1133    ) -> (String, TerminalDiffStats) {
1134        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1135        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1136        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1137        if mode == TerminalRenderMode::InteractiveTui {
1138            let fp: TerminalFrameFingerprint =
1139                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1140            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1141                self.set_last_projected_rows(0);
1142                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1143                self.set_skipped_idle_frames(next_skipped);
1144                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1145                self.set_frames_rendered(next_frames);
1146                return (
1147                    String::new(),
1148                    TerminalDiffStats::new(total_cells, 0, 0, true, false),
1149                );
1150            }
1151        }
1152        let stats: TerminalDiffStats =
1153            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1154        let output: String = self.get_ansi_scratch().clone();
1155        self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1156        (output, stats)
1157    }
1158
1159    /// Projects `tree` into a `cols x rows` character grid and returns a zero-allocation borrowed view of the encoded ANSI or plain-text payload.
1160    ///
1161    /// # Arguments
1162    ///
1163    /// - `&Self` - Mutable terminal renderer.
1164    /// - `&SceneTree` - Retained UI scene tree to project.
1165    /// - `u16` - Terminal viewport width in columns.
1166    /// - `u16` - Terminal viewport height in rows.
1167    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
1168    ///
1169    /// # Returns
1170    ///
1171    /// - `(&str, TerminalDiffStats)` - Borrowed UTF-8 terminal payload and cell-diff telemetry.
1172    pub fn render_tree_borrowed(
1173        &mut self,
1174        tree: &SceneTree,
1175        cols: u16,
1176        rows: u16,
1177        mode: TerminalRenderMode,
1178    ) -> (&str, TerminalDiffStats) {
1179        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1180        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1181        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1182        if mode == TerminalRenderMode::InteractiveTui {
1183            let fp: TerminalFrameFingerprint =
1184                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1185            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1186                self.set_last_projected_rows(0);
1187                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1188                self.set_skipped_idle_frames(next_skipped);
1189                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1190                self.set_frames_rendered(next_frames);
1191                self.get_mut_ansi_scratch().clear();
1192                return (
1193                    self.get_ansi_scratch().as_str(),
1194                    TerminalDiffStats::new(total_cells, 0, 0, true, false),
1195                );
1196            }
1197        }
1198        let stats: TerminalDiffStats =
1199            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1200        self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1201        (self.get_ansi_scratch().as_str(), stats)
1202    }
1203
1204    /// 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.
1205    ///
1206    /// # Arguments
1207    ///
1208    /// - `&Self` - Mutable terminal renderer.
1209    /// - `&SceneTree` - Retained UI scene tree to project.
1210    /// - `u16` - Terminal viewport width in columns.
1211    /// - `u16` - Terminal viewport height in rows.
1212    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
1213    /// - `&mut WriterType` - Output writer receiving the single batched write.
1214    ///
1215    /// # Returns
1216    ///
1217    /// - `TerminalWriteResult` - Write status, diff stats, and whether double-buffer ownership was swapped.
1218    #[cfg(not(target_arch = "wasm32"))]
1219    pub fn render_tree_to_writer<WriterType>(
1220        &mut self,
1221        tree: &SceneTree,
1222        cols: u16,
1223        rows: u16,
1224        mode: TerminalRenderMode,
1225        writer: &mut WriterType,
1226    ) -> TerminalWriteResult
1227    where
1228        WriterType: Write,
1229    {
1230        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1231        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1232        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1233        if mode == TerminalRenderMode::InteractiveTui {
1234            let fp: TerminalFrameFingerprint =
1235                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1236            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1237                self.set_last_projected_rows(0);
1238                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1239                self.set_skipped_idle_frames(next_skipped);
1240                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1241                self.set_frames_rendered(next_frames);
1242                let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
1243                    mode,
1244                    gpu_routing_opted_out: true,
1245                    uses_screen_hz: false,
1246                    input_to_output_ms: None,
1247                    flush_latency_ms: 0.0,
1248                    bytes_written: 0,
1249                    total_bytes_written: self.get_total_bytes_written(),
1250                    changed_cells: 0,
1251                    unchanged_frame_skipped: true,
1252                    backpressure_events: self.get_backpressure_events(),
1253                    batched_flush_count: self.get_batched_flush_count(),
1254                };
1255                self.set_last_telemetry(telemetry);
1256                return TerminalWriteResult {
1257                    status: CliWriteStatus::Written,
1258                    stats: TerminalDiffStats::new(total_cells, 0, 0, true, false),
1259                    swapped: false,
1260                    error_message: None,
1261                    telemetry,
1262                };
1263            }
1264        }
1265        let stats: TerminalDiffStats =
1266            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1267        let payload_bytes: &[u8] = self.get_ansi_scratch().as_bytes();
1268        let mut bytes_written: u64 = 0;
1269        let mut flush_latency_ms: f64 = 0.0;
1270        let mut bp_delta: u64 = 0;
1271        let mut flushed_batch: bool = false;
1272        if !payload_bytes.is_empty() {
1273            let flush_start: Instant = Instant::now();
1274            match write_all_with_backpressure(writer, payload_bytes) {
1275                Ok((written, bp_events)) => {
1276                    flush_latency_ms = flush_start.elapsed().as_secs_f64() * 1000.0;
1277                    bytes_written = written;
1278                    bp_delta = bp_events;
1279                    flushed_batch = true;
1280                }
1281                Err((err, written, bp_events)) => {
1282                    flush_latency_ms = flush_start.elapsed().as_secs_f64() * 1000.0;
1283                    let status: CliWriteStatus = classify_io_error(&err);
1284                    let next_total: u64 = self.get_total_bytes_written().saturating_add(written);
1285                    let next_bp: u64 = self
1286                        .get_backpressure_events()
1287                        .saturating_add(bp_events)
1288                        .saturating_add(1);
1289                    self.set_total_bytes_written(next_total);
1290                    self.set_backpressure_events(next_bp);
1291                    let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
1292                        mode,
1293                        gpu_routing_opted_out: true,
1294                        uses_screen_hz: false,
1295                        input_to_output_ms: self.take_input_to_output_ms(),
1296                        flush_latency_ms,
1297                        bytes_written: written,
1298                        total_bytes_written: next_total,
1299                        changed_cells: stats.get_changed_cells(),
1300                        unchanged_frame_skipped: false,
1301                        backpressure_events: next_bp,
1302                        batched_flush_count: self.get_batched_flush_count(),
1303                    };
1304                    self.set_last_telemetry(telemetry);
1305                    self.invalidate();
1306                    return TerminalWriteResult {
1307                        status,
1308                        stats,
1309                        swapped: false,
1310                        error_message: Some(err.to_string()),
1311                        telemetry,
1312                    };
1313                }
1314            }
1315        }
1316        let next_total: u64 = self.get_total_bytes_written().saturating_add(bytes_written);
1317        let next_bp: u64 = self.get_backpressure_events().saturating_add(bp_delta);
1318        let next_batches: u64 = self
1319            .get_batched_flush_count()
1320            .saturating_add(u64::from(flushed_batch));
1321        self.set_total_bytes_written(next_total);
1322        self.set_backpressure_events(next_bp);
1323        self.set_batched_flush_count(next_batches);
1324        let input_to_output_ms: Option<f64> = self.take_input_to_output_ms();
1325        let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
1326            mode,
1327            gpu_routing_opted_out: true,
1328            uses_screen_hz: false,
1329            input_to_output_ms,
1330            flush_latency_ms,
1331            bytes_written,
1332            total_bytes_written: next_total,
1333            changed_cells: stats.get_changed_cells(),
1334            unchanged_frame_skipped: stats.get_is_idle(),
1335            backpressure_events: next_bp,
1336            batched_flush_count: next_batches,
1337        };
1338        self.set_last_telemetry(telemetry);
1339        let swapped: bool = self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1340        TerminalWriteResult {
1341            status: CliWriteStatus::Written,
1342            stats,
1343            swapped,
1344            error_message: None,
1345            telemetry,
1346        }
1347    }
1348
1349    /// Projects `tree` into `current` and encodes the payload into `ansi_scratch` without mutating `previous`.
1350    ///
1351    /// # Arguments
1352    ///
1353    /// - `&Self` - Mutable terminal renderer.
1354    /// - `&SceneTree` - Retained UI scene tree.
1355    /// - `u16` - Clamped terminal columns.
1356    /// - `u16` - Clamped terminal rows.
1357    /// - `TerminalRenderMode` - Active render mode.
1358    ///
1359    /// # Returns
1360    ///
1361    /// - `TerminalDiffStats` - Per-frame cell diff telemetry.
1362    fn project_and_encode_into_scratch(
1363        &mut self,
1364        tree: &SceneTree,
1365        clamped_cols: u16,
1366        clamped_rows: u16,
1367        mode: TerminalRenderMode,
1368    ) -> TerminalDiffStats {
1369        self.get_mut_current().reset(clamped_cols, clamped_rows);
1370        self.get_mut_tracked_scroll_nodes().clear();
1371        let focused: Option<NodeId> = tree.get_focus().focused_node();
1372        let mut cursor_y: u16 = 0;
1373        let root_region: TerminalRegion =
1374            TerminalRegion::new(0, clamped_cols, clamped_rows, focused);
1375        self.project_node(tree, tree.get_root(), root_region, &mut cursor_y);
1376        self.set_last_projected_rows(cursor_y as usize);
1377        self.get_mut_current().finalize_row_hashes();
1378        let total_cells: usize = self.get_current().total_cells();
1379        self.get_mut_ansi_scratch().clear();
1380        match mode {
1381            TerminalRenderMode::StaticPlainText => {
1382                let plain: String = self.get_current().to_plain_text();
1383                let bytes: usize = plain.len();
1384                self.get_mut_ansi_scratch().push_str(&plain);
1385                TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
1386            }
1387            TerminalRenderMode::InteractiveTui => {
1388                let resized_or_first: bool = !self.get_previous_valid()
1389                    || self.get_last_cols() != clamped_cols
1390                    || self.get_last_rows() != clamped_rows
1391                    || self.get_previous().total_cells() != total_cells;
1392                if resized_or_first {
1393                    self.encode_full_frame_into_scratch();
1394                    let bytes: usize = self.get_ansi_scratch().len();
1395                    TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
1396                } else {
1397                    self.encode_diff_frame_into_scratch()
1398                }
1399            }
1400        }
1401    }
1402
1403    /// Commits double-buffer ownership via zero-clone `swap` after a confirmed interactive write (leaving `previous` untouched in `StaticPlainText` mode).
1404    ///
1405    /// # Arguments
1406    ///
1407    /// - `&Self` - Mutable terminal renderer.
1408    /// - `&SceneTree` - Rendered scene tree.
1409    /// - `u16` - Clamped terminal columns.
1410    /// - `u16` - Clamped terminal rows.
1411    /// - `TerminalRenderMode` - Active render mode.
1412    ///
1413    /// # Returns
1414    ///
1415    /// - `bool` - `true` when `current` and `previous` were swapped.
1416    fn commit_after_write(
1417        &mut self,
1418        tree: &SceneTree,
1419        clamped_cols: u16,
1420        clamped_rows: u16,
1421        mode: TerminalRenderMode,
1422    ) -> bool {
1423        self.set_last_cols(clamped_cols);
1424        self.set_last_rows(clamped_rows);
1425        let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1426        self.set_frames_rendered(next_frames);
1427        if mode == TerminalRenderMode::StaticPlainText {
1428            self.set_previous_valid(false);
1429            let Self {
1430                last_fingerprint, ..
1431            } = self;
1432            *last_fingerprint = None;
1433            return false;
1434        }
1435        let fp: TerminalFrameFingerprint =
1436            self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1437        let Self {
1438            previous,
1439            current,
1440            previous_valid,
1441            last_fingerprint,
1442            ..
1443        } = self;
1444        swap(current, previous);
1445        let target_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1446        if current.total_cells() != target_cells {
1447            current.reset(clamped_cols, clamped_rows);
1448        }
1449        *previous_valid = true;
1450        *last_fingerprint = Some(fp);
1451        true
1452    }
1453
1454    /// Processes a terminal keyboard event (`Tab`, `Shift+Tab`, arrows, `Enter`, `Escape`, `Ctrl+C`) against `tree`.
1455    ///
1456    /// # Arguments
1457    ///
1458    /// - `&Self` - Mutable terminal renderer.
1459    /// - `&mut SceneTree` - Retained UI scene tree to update focus, scroll, or activation on.
1460    /// - `KeyEvent` - Normalized keyboard event.
1461    ///
1462    /// # Returns
1463    ///
1464    /// - `TerminalNavAction` - Resulting focus, scroll, activation, or exit action.
1465    pub fn handle_key(&mut self, tree: &mut SceneTree, key: KeyEvent) -> TerminalNavAction {
1466        let code: KeyCode = key.get_code();
1467        let mods: Modifiers = key.get_modifiers();
1468        if code == KeyCode::Escape
1469            || (mods.get_ctrl()
1470                && matches!(code, KeyCode::Character('c') | KeyCode::Character('C')))
1471        {
1472            self.set_exit_requested(true);
1473            return TerminalNavAction::ExitRequested;
1474        }
1475        if code == KeyCode::Tab {
1476            let focusables: Vec<NodeId> = Self::collect_focusables(tree);
1477            if focusables.is_empty() {
1478                return TerminalNavAction::Ignored;
1479            }
1480            let current: Option<NodeId> = tree.get_focus().focused_node();
1481            let next_target: NodeId = match current
1482                .and_then(|cur: NodeId| focusables.iter().position(|id: &NodeId| *id == cur))
1483            {
1484                Some(idx) => {
1485                    let next_idx: usize = if mods.get_shift() {
1486                        if idx == 0 {
1487                            focusables.len() - 1
1488                        } else {
1489                            idx - 1
1490                        }
1491                    } else {
1492                        (idx + 1) % focusables.len()
1493                    };
1494                    focusables[next_idx]
1495                }
1496                None => {
1497                    if mods.get_shift() {
1498                        focusables[focusables.len() - 1]
1499                    } else {
1500                        focusables[0]
1501                    }
1502                }
1503            };
1504            let callbacks: Vec<(UiEventHandler, UiEvent)> = tree.update_focus(Some(next_target));
1505            for (handler, ui_event) in callbacks.into_iter() {
1506                if let Ok(mut callback_fn) = handler.try_borrow_mut() {
1507                    callback_fn(&ui_event);
1508                }
1509            }
1510            return TerminalNavAction::FocusMoved(next_target);
1511        }
1512        if code == KeyCode::ArrowDown || code == KeyCode::ArrowUp {
1513            let delta_rows: i16 = if code == KeyCode::ArrowDown { 1 } else { -1 };
1514            if let Some(scroll_id) = Self::find_first_scroll_view(tree) {
1515                let current_y: f32 = tree
1516                    .get_node(scroll_id)
1517                    .map(|scene_node: &SceneNode| {
1518                        scene_node.get_layout_box().get_scroll_offset().get_y()
1519                    })
1520                    .unwrap_or(0.0);
1521                let next_y: f32 =
1522                    (current_y + (delta_rows as f32) * TERMINAL_SCROLL_STEP_PX).max(0.0);
1523                tree.set_scroll_offset(scroll_id, Point::new(0.0, next_y));
1524                return TerminalNavAction::Scrolled(delta_rows);
1525            }
1526            return TerminalNavAction::Ignored;
1527        }
1528        if code == KeyCode::Enter {
1529            if let Some(target) = tree.get_focus().focused_node() {
1530                let click_kind: UiEventKind = UiEventKind::Click(Point::default());
1531                let handler_opt: Option<UiEventHandler> = tree
1532                    .get_node(target)
1533                    .and_then(|node: &SceneNode| node.get_handlers().handler_for(&click_kind));
1534                if let Some(handler) = handler_opt
1535                    && let Ok(mut handler_cb) = handler.try_borrow_mut()
1536                {
1537                    let click_ev: UiEvent = UiEvent::new(target, click_kind);
1538                    handler_cb(&click_ev);
1539                }
1540                return TerminalNavAction::Activated(target);
1541            }
1542            return TerminalNavAction::Ignored;
1543        }
1544        TerminalNavAction::Ignored
1545    }
1546
1547    /// Collects all visible focusable or clickable node handles in pre-order traversal.
1548    ///
1549    /// # Arguments
1550    ///
1551    /// - `&SceneTree` - Retained UI scene tree.
1552    ///
1553    /// # Returns
1554    ///
1555    /// - `Vec<NodeId>` - Ordered focus ring candidates.
1556    #[must_use]
1557    fn collect_focusables(tree: &SceneTree) -> Vec<NodeId> {
1558        let mut out: Vec<NodeId> = Vec::new();
1559        let mut stack: Vec<NodeId> = vec![tree.get_root()];
1560        while let Some(id) = stack.pop() {
1561            let Some(node) = tree.get_node(id) else {
1562                continue;
1563            };
1564            if node.style_ref().get_layout().get_display() == Display::None
1565                || node.style_ref().get_paint().get_opacity() <= 0.0
1566            {
1567                continue;
1568            }
1569            if Self::is_focusable_or_interactive(node) {
1570                out.push(id);
1571            }
1572            for child in tree.children_iter(id).rev() {
1573                stack.push(child);
1574            }
1575        }
1576        out
1577    }
1578
1579    /// Finds the first visible `NodeKind::ScrollView` node in pre-order traversal.
1580    ///
1581    /// # Arguments
1582    ///
1583    /// - `&SceneTree` - Retained UI scene tree.
1584    ///
1585    /// # Returns
1586    ///
1587    /// - `Option<NodeId>` - First visible scroll container handle.
1588    #[must_use]
1589    fn find_first_scroll_view(tree: &SceneTree) -> Option<NodeId> {
1590        let mut stack: Vec<NodeId> = vec![tree.get_root()];
1591        while let Some(id) = stack.pop() {
1592            let Some(node) = tree.get_node(id) else {
1593                continue;
1594            };
1595            if node.style_ref().get_layout().get_display() == Display::None {
1596                continue;
1597            }
1598            if matches!(node.get_kind(), NodeKind::ScrollView) {
1599                return Some(id);
1600            }
1601            for child in tree.children_iter(id).rev() {
1602                stack.push(child);
1603            }
1604        }
1605        None
1606    }
1607
1608    /// Returns `true` when `node` should participate in terminal focus and clickable affordances.
1609    ///
1610    /// # Arguments
1611    ///
1612    /// - `&SceneNode` - Candidate scene node.
1613    ///
1614    /// # Returns
1615    ///
1616    /// - `bool` - Whether the node is focusable or interactive.
1617    #[must_use]
1618    fn is_focusable_or_interactive(node: &SceneNode) -> bool {
1619        node.get_interaction().get_focusable()
1620            || matches!(node.get_kind(), NodeKind::Input(_))
1621            || Self::is_clickable_node(node)
1622    }
1623
1624    /// Returns `true` when `node` acts as a clickable button or interactive trigger.
1625    ///
1626    /// # Arguments
1627    ///
1628    /// - `&SceneNode` - Candidate scene node.
1629    ///
1630    /// # Returns
1631    ///
1632    /// - `bool` - Whether the node has click semantics.
1633    #[must_use]
1634    fn is_clickable_node(node: &SceneNode) -> bool {
1635        node.get_handlers()
1636            .handler_for(&UiEventKind::Click(Point::default()))
1637            .is_some()
1638            || node.style_ref().get_paint().get_cursor() == CursorIcon::Pointer
1639            || node
1640                .a11y_props()
1641                .is_some_and(|alpha_val: A11yProps| alpha_val.get_role() == A11yRole::Button)
1642    }
1643
1644    /// Returns `true` when a child node is visible for terminal projection.
1645    ///
1646    /// # Arguments
1647    ///
1648    /// - `&SceneTree` - Retained UI scene tree.
1649    /// - `NodeId` - Candidate node handle.
1650    ///
1651    /// # Returns
1652    ///
1653    /// - `bool` - `true` iff node exists, `display != None`, and `opacity > 0.0`.
1654    #[must_use]
1655    fn is_node_visible(tree: &SceneTree, node_id: NodeId) -> bool {
1656        tree.get_node(node_id)
1657            .is_some_and(|scene_node: &SceneNode| {
1658                scene_node.style_ref().get_layout().get_display() != Display::None
1659                    && scene_node.style_ref().get_paint().get_opacity() > 0.0
1660            })
1661    }
1662
1663    /// Collects direct/descendant display label text for a clickable container button.
1664    ///
1665    /// # Arguments
1666    ///
1667    /// - `&SceneTree` - Retained UI scene tree.
1668    /// - `NodeId` - Button container node identifier.
1669    ///
1670    /// # Returns
1671    ///
1672    /// - `String` - Resolved button caption text.
1673    #[must_use]
1674    fn collect_button_label(tree: &SceneTree, node_id: NodeId) -> String {
1675        let Some(node) = tree.get_node(node_id) else {
1676            return String::new();
1677        };
1678        let mut parts: Vec<String> = Vec::new();
1679        let mut stack: Vec<NodeId> = tree.children_iter(node_id).rev().collect();
1680        while let Some(cid) = stack.pop() {
1681            let Some(child) = tree.get_node(cid) else {
1682                continue;
1683            };
1684            if child.style_ref().get_layout().get_display() == Display::None {
1685                continue;
1686            }
1687            if let NodeKind::Text(text) = child.get_kind() {
1688                let trimmed: &str = text.trim();
1689                if !trimmed.is_empty() {
1690                    parts.push(trimmed.to_string());
1691                }
1692            }
1693            for grand in tree.children_iter(cid).rev() {
1694                stack.push(grand);
1695            }
1696        }
1697        if !parts.is_empty() {
1698            return parts.join(" ");
1699        }
1700        node.a11y_props()
1701            .map(|alpha_val: A11yProps| alpha_val.get_label().clone())
1702            .unwrap_or_default()
1703    }
1704
1705    /// Projects a single scene node subtree into the current `TerminalCellGrid` using terminal character coordinates directly.
1706    ///
1707    /// # Arguments
1708    ///
1709    /// - `&Self` - Mutable terminal renderer.
1710    /// - `&SceneTree` - Retained scene tree.
1711    /// - `NodeId` - Target node handle to project.
1712    /// - `TerminalRegion` - Active character-grid region and focus context.
1713    /// - `&mut u16` - Mutable current row cursor advanced as content is laid out.
1714    fn project_node(
1715        &mut self,
1716        tree: &SceneTree,
1717        node_id: NodeId,
1718        region: TerminalRegion,
1719        pos_y: &mut u16,
1720    ) {
1721        let pos_x: u16 = region.get_x();
1722        let avail_w: u16 = region.get_width();
1723        let max_y: u16 = region.get_max_y();
1724        let focused: Option<NodeId> = region.get_focused();
1725        if *pos_y >= max_y || avail_w == 0 {
1726            return;
1727        }
1728        let Some(node) = tree.get_node(node_id) else {
1729            return;
1730        };
1731        let style: &Style = node.style_ref();
1732        let layout: LayoutStyle = style.get_layout();
1733        let paint: PaintStyle = style.get_paint();
1734        let text_style: TextStyle = style.get_text();
1735        if layout.get_display() == Display::None || paint.get_opacity() <= 0.0 {
1736            return;
1737        }
1738        let is_focused: bool = focused == Some(node_id) || node.get_interaction().get_focused();
1739        let is_bold: bool = matches!(
1740            text_style.get_weight(),
1741            FontWeight::SemiBold | FontWeight::Bold
1742        );
1743        let fg: Option<Color> = Some(text_style.get_color());
1744        let bg: Option<Color> = paint.background_color();
1745        let template: TerminalCell = TerminalCell::styled(
1746            ' ',
1747            1,
1748            fg,
1749            bg,
1750            is_bold,
1751            is_focused,
1752            text_style.get_underline(),
1753        );
1754        match node.get_kind() {
1755            NodeKind::Text(content) => {
1756                if Self::is_clickable_node(node) {
1757                    let display_str: String = if is_focused {
1758                        format!("> [ {content} ]")
1759                    } else {
1760                        format!("[ {content} ]")
1761                    };
1762                    self.write_wrapped_text(region, pos_y, &display_str, template);
1763                } else {
1764                    self.write_wrapped_text(region, pos_y, content.as_str(), template);
1765                }
1766            }
1767            NodeKind::Input(input_state) => {
1768                let inner: String = if input_state.get_value().is_empty() {
1769                    input_state.get_placeholder().clone()
1770                } else if input_state.get_password() {
1771                    let count: usize = input_state.get_value().chars().count();
1772                    "*".repeat(count)
1773                } else {
1774                    input_state.get_value().clone()
1775                };
1776                let formatted: String = if is_focused {
1777                    if tree.get_caret_visible() {
1778                        format!("> [ {inner}| ]")
1779                    } else {
1780                        format!("> [ {inner}  ]")
1781                    }
1782                } else {
1783                    format!("[ {inner} ]")
1784                };
1785                let _: u16 = self
1786                    .get_mut_current()
1787                    .write_styled_text(pos_x, *pos_y, avail_w, &formatted, template);
1788                *pos_y = pos_y.saturating_add(1);
1789            }
1790            NodeKind::Image(img) => {
1791                let alt: String = node
1792                    .a11y_props()
1793                    .map(|alpha_val: A11yProps| alpha_val.get_label().clone())
1794                    .filter(|text_value: &String| !text_value.is_empty())
1795                    .map(|label_str: String| {
1796                        format!("{TERMINAL_IMAGE_FALLBACK_PREFIX}{label_str}]")
1797                    })
1798                    .unwrap_or_else(|| {
1799                        format!(
1800                            "{TERMINAL_IMAGE_DIM_PREFIX}{}x{}]",
1801                            img.get_width(),
1802                            img.get_height()
1803                        )
1804                    });
1805                let _: u16 = self
1806                    .get_mut_current()
1807                    .write_styled_text(pos_x, *pos_y, avail_w, &alt, template);
1808                *pos_y = pos_y.saturating_add(1);
1809            }
1810            NodeKind::Canvas(_) => {
1811                let alt: String = node
1812                    .a11y_props()
1813                    .map(|first_val: A11yProps| first_val.get_label().clone())
1814                    .filter(|content_text: &String| !content_text.is_empty())
1815                    .map(|label_text: String| {
1816                        format!("{TERMINAL_CANVAS_FALLBACK_PREFIX}{label_text}]")
1817                    })
1818                    .unwrap_or_else(|| TERMINAL_CANVAS_FALLBACK.to_string());
1819                let _: u16 = self
1820                    .get_mut_current()
1821                    .write_styled_text(pos_x, *pos_y, avail_w, &alt, template);
1822                *pos_y = pos_y.saturating_add(1);
1823            }
1824            NodeKind::Fragment => {
1825                for child_id in tree.children_iter(node_id) {
1826                    if *pos_y >= max_y {
1827                        break;
1828                    }
1829                    self.project_node(tree, child_id, region, pos_y);
1830                }
1831            }
1832            NodeKind::ScrollView => {
1833                self.project_scroll_view(tree, node_id, region, pos_y);
1834            }
1835            NodeKind::View | NodeKind::Portal => {
1836                let is_root: bool = node_id == tree.get_root();
1837                if !is_root && Self::is_clickable_node(node) {
1838                    let caption: String = Self::collect_button_label(tree, node_id);
1839                    if !caption.is_empty() {
1840                        let formatted: String = if is_focused {
1841                            format!("> [ {caption} ]")
1842                        } else {
1843                            format!("[ {caption} ]")
1844                        };
1845                        let _: u16 = self
1846                            .get_mut_current()
1847                            .write_styled_text(pos_x, *pos_y, avail_w, &formatted, template);
1848                        *pos_y = pos_y.saturating_add(1);
1849                        return;
1850                    }
1851                }
1852                let has_border: bool = !is_root
1853                    && (paint.get_border().get_width() > 0.0
1854                        || matches!(node.get_kind(), NodeKind::Portal))
1855                    && avail_w >= 4
1856                    && max_y.saturating_sub(*pos_y) >= 3;
1857                if has_border {
1858                    let top_y: u16 = *pos_y;
1859                    let inner_region: TerminalRegion = TerminalRegion::new(
1860                        pos_x.saturating_add(1),
1861                        avail_w.saturating_sub(2),
1862                        max_y.saturating_sub(1),
1863                        focused,
1864                    );
1865                    let mut child_y: u16 = top_y.saturating_add(1);
1866                    self.project_children_flow(tree, node_id, node, inner_region, &mut child_y);
1867                    let box_h: u16 = child_y
1868                        .saturating_sub(top_y)
1869                        .saturating_add(1)
1870                        .max(3)
1871                        .min(max_y.saturating_sub(top_y));
1872                    let border_cell: TerminalCell = TerminalCell::styled(
1873                        ' ',
1874                        1,
1875                        Some(paint.get_border().get_color()),
1876                        bg,
1877                        false,
1878                        is_focused,
1879                        false,
1880                    );
1881                    self.get_mut_current()
1882                        .draw_box(pos_x, top_y, avail_w, box_h, border_cell);
1883                    *pos_y = top_y.saturating_add(box_h);
1884                } else {
1885                    self.project_children_flow(tree, node_id, node, region, pos_y);
1886                }
1887            }
1888        }
1889    }
1890
1891    /// Projects children of a container respecting row, column, and grid directions directly in character columns.
1892    ///
1893    /// # Arguments
1894    ///
1895    /// - `&Self` - Mutable terminal renderer.
1896    /// - `&SceneTree` - Retained scene tree.
1897    /// - `NodeId` - Container scene node handle.
1898    /// - `&SceneNode` - Container scene node.
1899    /// - `TerminalRegion` - Active character-grid region and focus context.
1900    /// - `&mut u16` - Mutable current row cursor.
1901    fn project_children_flow(
1902        &mut self,
1903        tree: &SceneTree,
1904        node_id: NodeId,
1905        node: &SceneNode,
1906        region: TerminalRegion,
1907        pos_y: &mut u16,
1908    ) {
1909        let pos_x: u16 = region.get_x();
1910        let avail_w: u16 = region.get_width();
1911        let max_y: u16 = region.get_max_y();
1912        let focused: Option<NodeId> = region.get_focused();
1913        let layout: LayoutStyle = node.style_ref().get_layout();
1914        let is_row: bool = matches!(
1915            layout.get_flex_direction(),
1916            FlexDirection::Row | FlexDirection::RowReverse
1917        ) && layout.get_display() == Display::Flex;
1918        if is_row {
1919            let visible_count: usize = tree
1920                .children_iter(node_id)
1921                .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
1922                .count();
1923            if visible_count > 1 && avail_w >= (visible_count as u16).saturating_mul(2) {
1924                let count: u16 = visible_count as u16;
1925                let total_gaps: u16 = count.saturating_sub(1).saturating_mul(TERMINAL_ROW_GAP);
1926                let slot_w: u16 = avail_w.saturating_sub(total_gaps) / count;
1927                if slot_w >= 2 {
1928                    let row_start_y: u16 = *pos_y;
1929                    let mut max_child_end: u16 = row_start_y;
1930                    let mut visible_idx: usize = 0;
1931                    for child_id in tree.children_iter(node_id) {
1932                        if !Self::is_node_visible(tree, child_id) {
1933                            continue;
1934                        }
1935                        let cx: u16 =
1936                            pos_x.saturating_add((visible_idx as u16).saturating_mul(slot_w + 1));
1937                        let rem_w: u16 = avail_w.saturating_sub(cx.saturating_sub(pos_x));
1938                        let col_w: u16 = if visible_idx + 1 == visible_count {
1939                            rem_w
1940                        } else {
1941                            slot_w.min(rem_w)
1942                        };
1943                        let mut cy: u16 = row_start_y;
1944                        let child_region: TerminalRegion =
1945                            TerminalRegion::new(cx, col_w, max_y, focused);
1946                        self.project_node(tree, child_id, child_region, &mut cy);
1947                        if cy > max_child_end {
1948                            max_child_end = cy;
1949                        }
1950                        visible_idx += 1;
1951                    }
1952                    *pos_y = max_child_end;
1953                    return;
1954                }
1955            }
1956        }
1957        for child_id in tree.children_iter(node_id) {
1958            if *pos_y >= max_y {
1959                break;
1960            }
1961            if Self::is_node_visible(tree, child_id) {
1962                self.project_node(tree, child_id, region, pos_y);
1963            }
1964        }
1965    }
1966
1967    /// Projects a `NodeKind::ScrollView` container with zero-allocation visible-range virtualization and a Unicode scrollbar rail.
1968    ///
1969    /// # Arguments
1970    ///
1971    /// - `&Self` - Mutable terminal renderer.
1972    /// - `&SceneTree` - Retained scene tree.
1973    /// - `NodeId` - Scroll container node handle.
1974    /// - `TerminalRegion` - Active character-grid region and focus context.
1975    /// - `&mut u16` - Mutable current row cursor.
1976    fn project_scroll_view(
1977        &mut self,
1978        tree: &SceneTree,
1979        node_id: NodeId,
1980        region: TerminalRegion,
1981        pos_y: &mut u16,
1982    ) {
1983        self.get_mut_tracked_scroll_nodes().push(node_id);
1984        let pos_x: u16 = region.get_x();
1985        let avail_w: u16 = region.get_width();
1986        let max_y: u16 = region.get_max_y();
1987        let focused: Option<NodeId> = region.get_focused();
1988        let Some(node) = tree.get_node(node_id) else {
1989            return;
1990        };
1991        let total_visible: usize = tree
1992            .children_iter(node_id)
1993            .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
1994            .count();
1995        let avail_h: u16 = max_y.saturating_sub(*pos_y);
1996        if avail_h == 0 || total_visible == 0 {
1997            return;
1998        }
1999        let scroll_y: f32 = node.get_layout_box().get_scroll_offset().get_y().max(0.0);
2000        let skip_items: usize = ((scroll_y / TERMINAL_SCROLL_STEP_PX).floor() as usize)
2001            .min(total_visible.saturating_sub(1));
2002        let needs_rail: bool = total_visible > (avail_h as usize) && avail_w >= 3;
2003        let inner_w: u16 = if needs_rail {
2004            avail_w.saturating_sub(1)
2005        } else {
2006            avail_w
2007        };
2008        let child_region: TerminalRegion = TerminalRegion::new(pos_x, inner_w, max_y, focused);
2009        let start_y: u16 = *pos_y;
2010        let mut seen_visible: usize = 0;
2011        for child_id in tree.children_iter(node_id) {
2012            if !Self::is_node_visible(tree, child_id) {
2013                continue;
2014            }
2015            if seen_visible < skip_items {
2016                seen_visible += 1;
2017                continue;
2018            }
2019            if *pos_y >= max_y {
2020                break;
2021            }
2022            self.project_node(tree, child_id, child_region, pos_y);
2023            seen_visible += 1;
2024        }
2025        if needs_rail {
2026            let rail_x: u16 = pos_x.saturating_add(inner_w);
2027            let total_items: usize = total_visible.max(1);
2028            let thumb_offset: u16 = ((skip_items * (avail_h as usize)) / total_items)
2029                .min((avail_h - 1) as usize) as u16;
2030            for offset in 0..avail_h {
2031                let glyph: char = if offset == thumb_offset {
2032                    TERMINAL_SCROLL_THUMB
2033                } else {
2034                    TERMINAL_SCROLL_TRACK
2035                };
2036                let _: u16 = self.get_mut_current().put_cell(
2037                    rail_x,
2038                    start_y.saturating_add(offset),
2039                    TerminalCell::styled(glyph, 1, None, None, false, false, false),
2040                );
2041            }
2042        }
2043    }
2044
2045    /// Writes `text` wrapped across consecutive terminal rows within `region` by Extended Grapheme Clusters without breaking CJK wide glyphs or ZWJ emoji sequences.
2046    ///
2047    /// # Arguments
2048    ///
2049    /// - `&Self` - Mutable terminal renderer.
2050    /// - `TerminalRegion` - Active character-grid region.
2051    /// - `&mut u16` - Mutable current row cursor.
2052    /// - `&str` - UTF-8 text to wrap.
2053    /// - `TerminalCell` - Style template cell.
2054    fn write_wrapped_text(
2055        &mut self,
2056        region: TerminalRegion,
2057        pos_y: &mut u16,
2058        text: &str,
2059        template: TerminalCell,
2060    ) {
2061        let pos_x: u16 = region.get_x();
2062        let avail_w: u16 = region.get_width();
2063        let max_y: u16 = region.get_max_y();
2064        if *pos_y >= max_y || avail_w == 0 {
2065            return;
2066        }
2067        let mut wrote_any_line: bool = false;
2068        for raw_line in text.split('\n') {
2069            if *pos_y >= max_y {
2070                break;
2071            }
2072            if raw_line.is_empty() {
2073                *pos_y = pos_y.saturating_add(1);
2074                wrote_any_line = true;
2075                continue;
2076            }
2077            let raw_bytes: &[u8] = raw_line.as_bytes();
2078            if raw_line.is_ascii()
2079                && raw_bytes
2080                    .iter()
2081                    .all(|blue_val: &u8| (0x20..=0x7E).contains(blue_val))
2082            {
2083                let chunk_len: usize = avail_w as usize;
2084                let mut offset: usize = 0;
2085                while offset < raw_bytes.len() {
2086                    if *pos_y >= max_y {
2087                        return;
2088                    }
2089                    let end: usize = (offset + chunk_len).min(raw_bytes.len());
2090                    let _: u16 = self.get_mut_current().write_printable_ascii_run(
2091                        pos_x,
2092                        *pos_y,
2093                        &raw_bytes[offset..end],
2094                        template,
2095                    );
2096                    offset = end;
2097                    if offset < raw_bytes.len() {
2098                        *pos_y = pos_y.saturating_add(1);
2099                    }
2100                }
2101                *pos_y = pos_y.saturating_add(1);
2102                wrote_any_line = true;
2103                continue;
2104            }
2105            let mut cur_col: u16 = 0;
2106            let mut rest: &str = raw_line;
2107            while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
2108                rest = next_rest;
2109                if cluster.starts_with('\r') {
2110                    continue;
2111                }
2112                let width: u8 = grapheme_display_width(cluster);
2113                if width == 0 {
2114                    continue;
2115                }
2116                let w_u16: u16 = width as u16;
2117                if w_u16 > avail_w {
2118                    continue;
2119                }
2120                if cur_col.saturating_add(w_u16) > avail_w {
2121                    *pos_y = pos_y.saturating_add(1);
2122                    if *pos_y >= max_y {
2123                        return;
2124                    }
2125                    cur_col = 0;
2126                }
2127                let cell: TerminalCell = TerminalCell::from_grapheme(cluster, width, template);
2128                let consumed: u16 = self
2129                    .get_mut_current()
2130                    .put_cell(pos_x + cur_col, *pos_y, cell);
2131                cur_col = cur_col.saturating_add(consumed);
2132            }
2133            *pos_y = pos_y.saturating_add(1);
2134            wrote_any_line = true;
2135        }
2136        if !wrote_any_line {
2137            *pos_y = pos_y.saturating_add(1);
2138        }
2139    }
2140
2141    /// Encodes the full current grid into `ansi_scratch` using zero-allocation cursor and SGR delta sequences.
2142    ///
2143    /// # Arguments
2144    ///
2145    /// - `&Self` - Mutable terminal renderer.
2146    fn encode_full_frame_into_scratch(&mut self) {
2147        let sync_mode: bool = self.get_sync_output_mode();
2148        let Self {
2149            current,
2150            ansi_scratch,
2151            ..
2152        } = self;
2153        let cols: u16 = current.get_cols();
2154        let rows: u16 = current.get_rows();
2155        let needed: usize = current.total_cells().saturating_mul(2);
2156        if ansi_scratch.capacity() < needed {
2157            ansi_scratch.reserve(needed - ansi_scratch.capacity());
2158        }
2159        if sync_mode {
2160            ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
2161        }
2162        ansi_scratch.push_str(ANSI_CLEAR_AND_HOME);
2163        let mut active_style: Option<TerminalCell> = None;
2164        let mut cursor_pos: Option<(u16, u16)> = Some((0, 0));
2165        for row in 0..rows {
2166            append_cursor_move_smart(ansi_scratch, cursor_pos, 0, row);
2167            cursor_pos = Some((0, row));
2168            let mut col: u16 = 0;
2169            while col < cols {
2170                let Some(cell) = current.cell(col, row) else {
2171                    col += 1;
2172                    continue;
2173                };
2174                if cell.is_continuation() {
2175                    col += 1;
2176                    continue;
2177                }
2178                append_sgr_delta(ansi_scratch, active_style, &cell);
2179                active_style = Some(cell);
2180                cell.push_grapheme_to(ansi_scratch);
2181                let step: u16 = cell.get_width().max(1) as u16;
2182                cursor_pos = Some((col.saturating_add(step), row));
2183                col = col.saturating_add(step);
2184            }
2185        }
2186        ansi_scratch.push_str(ANSI_RESET_STYLE);
2187        if sync_mode {
2188            ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
2189        }
2190    }
2191
2192    /// Encodes only cells changed relative to `previous` into `ansi_scratch`, skipping unchanged rows via row hashes and coalescing short runs and SGR deltas.
2193    ///
2194    /// # Arguments
2195    ///
2196    /// - `&Self` - Mutable terminal renderer.
2197    ///
2198    /// # Returns
2199    ///
2200    /// - `TerminalDiffStats` - Incremental diff telemetry (`is_idle == true` and `0` bytes when identical).
2201    fn encode_diff_frame_into_scratch(&mut self) -> TerminalDiffStats {
2202        let sync_mode: bool = self.get_sync_output_mode();
2203        let Self {
2204            previous,
2205            current,
2206            ansi_scratch,
2207            ..
2208        } = self;
2209        let total_cells: usize = current.total_cells();
2210        let cols: u16 = current.get_cols();
2211        let rows: u16 = current.get_rows();
2212        let mut changed_cells: usize = 0;
2213        let mut active_style: Option<TerminalCell> = None;
2214        let mut cursor_pos: Option<(u16, u16)> = None;
2215        let mut emitted_any: bool = false;
2216        for row in 0..rows {
2217            let row_idx: usize = row as usize;
2218            let cur_hash: Option<u64> = current.get_row_hashes().get(row_idx).copied();
2219            let prev_hash: Option<u64> = previous.get_row_hashes().get(row_idx).copied();
2220            if cur_hash.is_some() && cur_hash == prev_hash {
2221                continue;
2222            }
2223            let mut col: u16 = 0;
2224            while col < cols {
2225                let Some(cur_cell) = current.cell(col, row) else {
2226                    col += 1;
2227                    continue;
2228                };
2229                let Some(prev_cell) = previous.cell(col, row) else {
2230                    col += 1;
2231                    continue;
2232                };
2233                if cur_cell.is_continuation() {
2234                    col += 1;
2235                    continue;
2236                }
2237                let mut cell_dirty: bool =
2238                    Self::is_cell_dirty(current, previous, col, row, cur_cell, prev_cell);
2239                if !cell_dirty
2240                    && let Some((cur_cx, cur_cy)) = cursor_pos
2241                    && cur_cy == row
2242                    && cur_cx == col
2243                    && let Some(active) = active_style
2244                    && active.same_style(&cur_cell)
2245                    && Self::has_dirty_within_gap(current, previous, col, row, cols)
2246                {
2247                    cell_dirty = true;
2248                }
2249                if !cell_dirty {
2250                    col = col.saturating_add(cur_cell.get_width().max(1) as u16);
2251                    continue;
2252                }
2253                if !emitted_any && sync_mode {
2254                    ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
2255                }
2256                emitted_any = true;
2257                let step: u16 = cur_cell.get_width().max(1) as u16;
2258                if cur_cell != prev_cell {
2259                    changed_cells = changed_cells.saturating_add(step as usize);
2260                }
2261                append_cursor_move_smart(ansi_scratch, cursor_pos, col, row);
2262                append_sgr_delta(ansi_scratch, active_style, &cur_cell);
2263                active_style = Some(cur_cell);
2264                cur_cell.push_grapheme_to(ansi_scratch);
2265                cursor_pos = Some((col.saturating_add(step), row));
2266                col = col.saturating_add(step);
2267            }
2268        }
2269        if !emitted_any {
2270            return TerminalDiffStats::new(total_cells, 0, 0, true, false);
2271        }
2272        ansi_scratch.push_str(ANSI_RESET_STYLE);
2273        if sync_mode {
2274            ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
2275        }
2276        let output_bytes: usize = ansi_scratch.len();
2277        TerminalDiffStats::new(
2278            total_cells,
2279            changed_cells.max(1),
2280            output_bytes,
2281            false,
2282            false,
2283        )
2284    }
2285
2286    /// Determines whether cell `(col, row)` must be emitted, including wide-character partner invalidation on both lead and continuation columns.
2287    ///
2288    /// # Arguments
2289    ///
2290    /// - `&TerminalCellGrid` - Active grid.
2291    /// - `&TerminalCellGrid` - Committed previous grid.
2292    /// - `u16` - Zero-based column coordinate.
2293    /// - `u16` - Zero-based row coordinate.
2294    /// - `TerminalCell` - Current cell value.
2295    /// - `TerminalCell` - Previous cell value.
2296    ///
2297    /// # Returns
2298    ///
2299    /// - `bool` - `true` when `(col, row)` requires re-emission.
2300    #[must_use]
2301    fn is_cell_dirty(
2302        current: &TerminalCellGrid,
2303        previous: &TerminalCellGrid,
2304        col: u16,
2305        row: u16,
2306        cur_cell: TerminalCell,
2307        prev_cell: TerminalCell,
2308    ) -> bool {
2309        if cur_cell != prev_cell {
2310            return true;
2311        }
2312        if cur_cell.is_wide_lead()
2313            && col.saturating_add(1) < current.get_cols()
2314            && current.cell(col + 1, row) != previous.cell(col + 1, row)
2315        {
2316            return true;
2317        }
2318        if prev_cell.is_continuation() && !cur_cell.is_continuation() {
2319            return true;
2320        }
2321        if col > 0
2322            && let Some(prev_left) = previous.cell(col - 1, row)
2323            && prev_left.is_wide_lead()
2324            && current.cell(col - 1, row) != Some(prev_left)
2325        {
2326            return true;
2327        }
2328        false
2329    }
2330
2331    /// Checks whether another dirty cell appears within `TERMINAL_COALESCE_GAP_MAX` columns so short same-style gaps avoid expensive cursor-move escapes.
2332    ///
2333    /// # Arguments
2334    ///
2335    /// - `&TerminalCellGrid` - Active grid.
2336    /// - `&TerminalCellGrid` - Committed previous grid.
2337    /// - `u16` - Starting column coordinate.
2338    /// - `u16` - Zero-based row coordinate.
2339    /// - `u16` - Total columns in the grid.
2340    ///
2341    /// # Returns
2342    ///
2343    /// - `bool` - `true` if coalescing across the current cell saves cursor movement.
2344    #[must_use]
2345    fn has_dirty_within_gap(
2346        current: &TerminalCellGrid,
2347        previous: &TerminalCellGrid,
2348        start_col: u16,
2349        row: u16,
2350        cols: u16,
2351    ) -> bool {
2352        let mut probe: u16 = start_col.saturating_add(1);
2353        let max_probe: u16 = start_col
2354            .saturating_add(TERMINAL_COALESCE_GAP_MAX)
2355            .min(cols.saturating_sub(1));
2356        while probe <= max_probe {
2357            if let (Some(char_item), Some(point_val)) =
2358                (current.cell(probe, row), previous.cell(probe, row))
2359                && !char_item.is_continuation()
2360                && Self::is_cell_dirty(current, previous, probe, row, char_item, point_val)
2361            {
2362                return true;
2363            }
2364            probe = probe.saturating_add(1);
2365        }
2366        false
2367    }
2368
2369    /// Explicitly signals that TUI/CLI rendering opts out of graphical GPU routing.
2370    ///
2371    /// # Returns
2372    ///
2373    /// - `bool` - Always `true`.
2374    #[must_use]
2375    pub fn opts_out_of_gpu_routing(&self) -> bool {
2376        true
2377    }
2378
2379    /// Records the arrival timestamp of a terminal input event for subsequent `input_to_output_ms` measurement.
2380    #[cfg(not(target_arch = "wasm32"))]
2381    pub fn record_input_received(&mut self) {
2382        let Self { last_input_at, .. } = self;
2383        *last_input_at = Some(Instant::now());
2384    }
2385
2386    /// Consumes the pending input timestamp and returns elapsed `input_to_output_ms` (`None` when unobservable).
2387    ///
2388    /// # Returns
2389    ///
2390    /// - `Option<f64>` - Elapsed milliseconds since the recorded input event.
2391    #[cfg(not(target_arch = "wasm32"))]
2392    fn take_input_to_output_ms(&mut self) -> Option<f64> {
2393        let Self { last_input_at, .. } = self;
2394        last_input_at
2395            .take()
2396            .map(|timestamp_val: Instant| timestamp_val.elapsed().as_secs_f64() * 1000.0)
2397    }
2398
2399    /// Returns the most recent non-GPU, non-Hz TUI/CLI telemetry snapshot.
2400    ///
2401    /// # Returns
2402    ///
2403    /// - `TerminalNonGpuTelemetry` - Latest telemetry (`input_to_output_ms`, `flush_latency_ms`, `bytes_written`, backpressure).
2404    #[must_use]
2405    pub fn last_telemetry_report(&self) -> TerminalNonGpuTelemetry {
2406        self.get_last_telemetry()
2407    }
2408}
2409
2410/// Accessors for `TerminalNonGpuTelemetry`.
2411impl TerminalNonGpuTelemetry {
2412    /// Returns the measured input-to-output latency in milliseconds (`None` when no input preceded the flush).
2413    ///
2414    /// # Returns
2415    ///
2416    /// - `Option<f64>` - Input-to-output latency in milliseconds.
2417    #[must_use]
2418    pub fn input_to_output_ms(&self) -> Option<f64> {
2419        let Self {
2420            input_to_output_ms, ..
2421        } = self;
2422        *input_to_output_ms
2423    }
2424}