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