1use super::*;
2
3impl Default for TerminalCell {
5 fn default() -> Self {
11 Self::blank()
12 }
13}
14
15impl TerminalCell {
17 #[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 #[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 #[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 #[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 #[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 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 #[must_use]
202 pub const fn fg_color(&self) -> Option<Color> {
203 let Self { fg, .. } = *self;
204 fg
205 }
206
207 #[must_use]
217 pub const fn bg_color(&self) -> Option<Color> {
218 let Self { bg, .. } = *self;
219 bg
220 }
221
222 #[must_use]
232 pub const fn is_continuation(&self) -> bool {
233 let Self { width, .. } = *self;
234 width == 0
235 }
236
237 #[must_use]
247 pub const fn is_wide_lead(&self) -> bool {
248 let Self { width, .. } = *self;
249 width == 2
250 }
251
252 #[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
272impl TerminalFrameFingerprint {
274 #[must_use]
284 pub const fn focused_node(&self) -> Option<NodeId> {
285 let Self { focused, .. } = *self;
286 focused
287 }
288}
289
290impl TerminalWriteResult {
292 #[must_use]
302 pub fn error_message(&self) -> Option<&str> {
303 let Self { error_message, .. } = self;
304 error_message.as_deref()
305 }
306}
307
308impl TerminalCellGrid {
310 #[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 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 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 #[must_use]
442 pub fn total_cells(&self) -> usize {
443 self.get_cells().len()
444 }
445
446 #[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 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 #[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 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 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 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 pub fn write_styled_text(
668 &mut self,
669 col: u16,
670 row: u16,
671 max_cols: u16,
672 text: &str,
673 style_cell: TerminalCell,
674 ) -> u16 {
675 let cols: u16 = self.get_cols();
676 let rows: u16 = self.get_rows();
677 if col >= cols || row >= rows || max_cols == 0 {
678 return 0;
679 }
680 let limit: u16 = max_cols.min(cols.saturating_sub(col));
681 let raw_bytes: &[u8] = text.as_bytes();
682 let check_len: usize = raw_bytes.len().min(limit as usize);
683 if text.is_ascii()
684 && raw_bytes[..check_len]
685 .iter()
686 .all(|b: &u8| (0x20..=0x7E).contains(b))
687 {
688 return self.write_printable_ascii_run(col, row, &raw_bytes[..check_len], style_cell);
689 }
690 let mut used: u16 = 0;
691 let mut rest: &str = text;
692 while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
693 rest = next_rest;
694 if cluster.starts_with('\n') || cluster.starts_with('\r') {
695 break;
696 }
697 let width: u8 = grapheme_display_width(cluster);
698 if width == 0 {
699 continue;
700 }
701 let w_u16: u16 = width as u16;
702 if used.saturating_add(w_u16) > limit {
703 break;
704 }
705 let cell: TerminalCell = TerminalCell::from_grapheme(cluster, width, style_cell);
706 let consumed: u16 = self.put_cell(col + used, row, cell);
707 if consumed == 0 {
708 break;
709 }
710 used = used.saturating_add(consumed);
711 }
712 used
713 }
714
715 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 pub fn draw_box(&mut self, x: u16, y: u16, w: u16, h: u16, style_cell: TerminalCell) {
743 if w < 2 || h < 2 {
744 return;
745 }
746 let right: u16 = x.saturating_add(w - 1);
747 let bottom: u16 = y.saturating_add(h - 1);
748 let fg: Option<Color> = style_cell.fg_color();
749 let bg: Option<Color> = style_cell.bg_color();
750 let bold: bool = style_cell.get_bold();
751 let rev: bool = style_cell.get_reverse();
752 let ul: bool = style_cell.get_underline();
753 let _: u16 = self.put_cell(
754 x,
755 y,
756 TerminalCell::styled(TERMINAL_BOX_TOP_LEFT, 1, fg, bg, bold, rev, ul),
757 );
758 let _: u16 = self.put_cell(
759 right,
760 y,
761 TerminalCell::styled(TERMINAL_BOX_TOP_RIGHT, 1, fg, bg, bold, rev, ul),
762 );
763 let _: u16 = self.put_cell(
764 x,
765 bottom,
766 TerminalCell::styled(TERMINAL_BOX_BOTTOM_LEFT, 1, fg, bg, bold, rev, ul),
767 );
768 let _: u16 = self.put_cell(
769 right,
770 bottom,
771 TerminalCell::styled(TERMINAL_BOX_BOTTOM_RIGHT, 1, fg, bg, bold, rev, ul),
772 );
773 let horiz: TerminalCell =
774 TerminalCell::styled(TERMINAL_BOX_HORIZONTAL, 1, fg, bg, bold, rev, ul);
775 let mut cx: u16 = x + 1;
776 while cx < right {
777 let _: u16 = self.put_cell(cx, y, horiz);
778 let _: u16 = self.put_cell(cx, bottom, horiz);
779 cx += 1;
780 }
781 let vert: TerminalCell =
782 TerminalCell::styled(TERMINAL_BOX_VERTICAL, 1, fg, bg, bold, rev, ul);
783 let mut cy: u16 = y + 1;
784 while cy < bottom {
785 let _: u16 = self.put_cell(x, cy, vert);
786 let _: u16 = self.put_cell(right, cy, vert);
787 cy += 1;
788 }
789 }
790
791 #[must_use]
801 pub fn to_plain_text(&self) -> String {
802 let cols: usize = self.get_cols() as usize;
803 let rows: usize = self.get_rows() as usize;
804 let cells: &[TerminalCell] = self.get_cells().as_slice();
805 let mut lines: Vec<String> = Vec::with_capacity(rows);
806 for row in 0..rows {
807 let start: usize = row * cols;
808 let end: usize = (start + cols).min(cells.len());
809 let mut line: String = String::with_capacity(cols);
810 for cell in &cells[start..end] {
811 if cell.is_continuation() {
812 continue;
813 }
814 cell.push_grapheme_to(&mut line);
815 }
816 let trimmed_len: usize = line.trim_end().len();
817 line.truncate(trimmed_len);
818 lines.push(line);
819 }
820 while let Some(last) = lines.last() {
821 if last.is_empty() {
822 let _: Option<String> = lines.pop();
823 } else {
824 break;
825 }
826 }
827 lines.join("\n")
828 }
829}
830
831impl TerminalSessionGuard {
833 #[must_use]
845 pub fn build_enter_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
846 let mut out: String = String::new();
847 if alt_screen {
848 out.push_str(ANSI_ENTER_ALT_SCREEN);
849 }
850 if cursor_hidden {
851 out.push_str(ANSI_HIDE_CURSOR);
852 }
853 if raw_mode {
854 out.push_str(ANSI_ENTER_RAW_MODES);
855 }
856 out
857 }
858
859 #[must_use]
871 pub fn build_restore_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
872 let mut out: String = String::from(ANSI_RESET_STYLE);
873 if raw_mode {
874 out.push_str(ANSI_LEAVE_RAW_MODES);
875 }
876 if cursor_hidden {
877 out.push_str(ANSI_SHOW_CURSOR);
878 }
879 if alt_screen {
880 out.push_str(ANSI_LEAVE_ALT_SCREEN);
881 }
882 out
883 }
884
885 #[must_use]
898 pub fn enter_captured(
899 alt_screen: bool,
900 cursor_hidden: bool,
901 raw_mode: bool,
902 sink: Option<Rc<RefCell<String>>>,
903 ) -> Self {
904 let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
905 if let Some(buf) = sink.as_ref()
906 && let Ok(mut guard) = buf.try_borrow_mut()
907 {
908 guard.push_str(&enter_seq);
909 }
910 Self {
911 alt_screen,
912 cursor_hidden,
913 raw_mode,
914 restored: false,
915 write_to_stdout: false,
916 sink,
917 }
918 }
919
920 #[must_use]
932 pub fn enter_stdout(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> Self {
933 let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
934 #[cfg(not(target_arch = "wasm32"))]
935 {
936 let mut stdout: io::Stdout = io::stdout();
937 let _: io::Result<()> = stdout.write_all(enter_seq.as_bytes());
938 let _: io::Result<()> = stdout.flush();
939 }
940 #[cfg(target_arch = "wasm32")]
941 let _: &String = &enter_seq;
942 Self {
943 alt_screen,
944 cursor_hidden,
945 raw_mode,
946 restored: false,
947 write_to_stdout: true,
948 sink: None,
949 }
950 }
951
952 pub fn restore_now(&mut self) -> String {
962 if self.get_restored() {
963 return String::new();
964 }
965 self.set_restored(true);
966 let seq: String = Self::build_restore_sequence(
967 self.get_alt_screen(),
968 self.get_cursor_hidden(),
969 self.get_raw_mode(),
970 );
971 let write_stdout: bool = self.get_write_to_stdout();
972 let Self { sink, .. } = self;
973 if let Some(buf) = sink.as_ref()
974 && let Ok(mut guard) = buf.try_borrow_mut()
975 {
976 guard.push_str(&seq);
977 }
978 #[cfg(not(target_arch = "wasm32"))]
979 if write_stdout {
980 let mut stdout: io::Stdout = io::stdout();
981 let _: io::Result<()> = stdout.write_all(seq.as_bytes());
982 let _: io::Result<()> = stdout.flush();
983 }
984 #[cfg(target_arch = "wasm32")]
985 let _: bool = write_stdout;
986 seq
987 }
988}
989
990impl Drop for TerminalSessionGuard {
992 fn drop(&mut self) {
998 let _: String = self.restore_now();
999 }
1000}
1001
1002impl TerminalRenderer {
1004 #[must_use]
1010 pub fn new() -> Self {
1011 Self::default()
1012 }
1013
1014 #[must_use]
1024 pub fn has_previous_frame(&self) -> bool {
1025 self.get_previous_valid() && !self.get_previous().get_cells().is_empty()
1026 }
1027
1028 #[must_use]
1038 pub const fn last_fingerprint(&self) -> Option<TerminalFrameFingerprint> {
1039 let Self {
1040 last_fingerprint, ..
1041 } = *self;
1042 last_fingerprint
1043 }
1044
1045 pub fn invalidate(&mut self) {
1051 self.set_previous_valid(false);
1052 let Self {
1053 last_fingerprint, ..
1054 } = self;
1055 *last_fingerprint = None;
1056 }
1057
1058 #[must_use]
1072 fn compute_fingerprint(
1073 &self,
1074 tree: &SceneTree,
1075 cols: u16,
1076 rows: u16,
1077 mode: TerminalRenderMode,
1078 ) -> TerminalFrameFingerprint {
1079 let focused: Option<NodeId> = tree.get_focus().focused_node();
1080 let focused_caret_offset: usize = focused
1081 .and_then(|id: NodeId| tree.get_node(id))
1082 .map(|node: &SceneNode| match node.get_kind() {
1083 NodeKind::Input(inp) => inp.get_caret(),
1084 _ => 0,
1085 })
1086 .unwrap_or(0);
1087 let mut scroll_hash: u64 = TERMINAL_FNV_OFFSET_BASIS;
1088 for scroll_id in self.get_tracked_scroll_nodes().iter().copied() {
1089 if let Some(node) = tree.get_node(scroll_id) {
1090 let off: Point = node.get_layout_box().get_scroll_offset();
1091 scroll_hash = fnv1a_mix_u64(scroll_hash, off.get_x().to_bits() as u64);
1092 scroll_hash = fnv1a_mix_u64(scroll_hash, off.get_y().to_bits() as u64);
1093 }
1094 }
1095 TerminalFrameFingerprint {
1096 scene_revision: tree.get_revision(),
1097 focused,
1098 caret_visible: tree.get_caret_visible(),
1099 focused_caret_offset,
1100 scroll_hash,
1101 cols,
1102 rows,
1103 mode,
1104 }
1105 }
1106
1107 pub fn render_tree(
1121 &mut self,
1122 tree: &SceneTree,
1123 cols: u16,
1124 rows: u16,
1125 mode: TerminalRenderMode,
1126 ) -> (String, TerminalDiffStats) {
1127 let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1128 let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1129 let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1130 if mode == TerminalRenderMode::InteractiveTui {
1131 let fp: TerminalFrameFingerprint =
1132 self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1133 if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1134 self.set_last_projected_rows(0);
1135 let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1136 self.set_skipped_idle_frames(next_skipped);
1137 let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1138 self.set_frames_rendered(next_frames);
1139 return (
1140 String::new(),
1141 TerminalDiffStats::new(total_cells, 0, 0, true, false),
1142 );
1143 }
1144 }
1145 let stats: TerminalDiffStats =
1146 self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1147 let output: String = self.get_ansi_scratch().clone();
1148 self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1149 (output, stats)
1150 }
1151
1152 pub fn render_tree_borrowed(
1166 &mut self,
1167 tree: &SceneTree,
1168 cols: u16,
1169 rows: u16,
1170 mode: TerminalRenderMode,
1171 ) -> (&str, TerminalDiffStats) {
1172 let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1173 let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1174 let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1175 if mode == TerminalRenderMode::InteractiveTui {
1176 let fp: TerminalFrameFingerprint =
1177 self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1178 if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1179 self.set_last_projected_rows(0);
1180 let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1181 self.set_skipped_idle_frames(next_skipped);
1182 let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1183 self.set_frames_rendered(next_frames);
1184 self.get_mut_ansi_scratch().clear();
1185 return (
1186 self.get_ansi_scratch().as_str(),
1187 TerminalDiffStats::new(total_cells, 0, 0, true, false),
1188 );
1189 }
1190 }
1191 let stats: TerminalDiffStats =
1192 self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1193 self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1194 (self.get_ansi_scratch().as_str(), stats)
1195 }
1196
1197 #[cfg(not(target_arch = "wasm32"))]
1212 pub fn render_tree_to_writer<W>(
1213 &mut self,
1214 tree: &SceneTree,
1215 cols: u16,
1216 rows: u16,
1217 mode: TerminalRenderMode,
1218 writer: &mut W,
1219 ) -> TerminalWriteResult
1220 where
1221 W: Write,
1222 {
1223 let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
1224 let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
1225 let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1226 if mode == TerminalRenderMode::InteractiveTui {
1227 let fp: TerminalFrameFingerprint =
1228 self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1229 if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
1230 self.set_last_projected_rows(0);
1231 let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
1232 self.set_skipped_idle_frames(next_skipped);
1233 let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1234 self.set_frames_rendered(next_frames);
1235 return TerminalWriteResult {
1236 status: CliWriteStatus::Written,
1237 stats: TerminalDiffStats::new(total_cells, 0, 0, true, false),
1238 swapped: false,
1239 error_message: None,
1240 };
1241 }
1242 }
1243 let stats: TerminalDiffStats =
1244 self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
1245 let payload_bytes: &[u8] = self.get_ansi_scratch().as_bytes();
1246 if !payload_bytes.is_empty() {
1247 if let Err(err) = writer.write_all(payload_bytes) {
1248 let status: CliWriteStatus = classify_io_error(&err);
1249 self.invalidate();
1250 return TerminalWriteResult {
1251 status,
1252 stats,
1253 swapped: false,
1254 error_message: Some(err.to_string()),
1255 };
1256 }
1257 if let Err(err) = writer.flush() {
1258 let status: CliWriteStatus = classify_io_error(&err);
1259 self.invalidate();
1260 return TerminalWriteResult {
1261 status,
1262 stats,
1263 swapped: false,
1264 error_message: Some(err.to_string()),
1265 };
1266 }
1267 }
1268 let swapped: bool = self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
1269 TerminalWriteResult {
1270 status: CliWriteStatus::Written,
1271 stats,
1272 swapped,
1273 error_message: None,
1274 }
1275 }
1276
1277 fn project_and_encode_into_scratch(
1291 &mut self,
1292 tree: &SceneTree,
1293 clamped_cols: u16,
1294 clamped_rows: u16,
1295 mode: TerminalRenderMode,
1296 ) -> TerminalDiffStats {
1297 self.get_mut_current().reset(clamped_cols, clamped_rows);
1298 self.get_mut_tracked_scroll_nodes().clear();
1299 let focused: Option<NodeId> = tree.get_focus().focused_node();
1300 let mut cursor_y: u16 = 0;
1301 let root_region: TerminalRegion =
1302 TerminalRegion::new(0, clamped_cols, clamped_rows, focused);
1303 self.project_node(tree, tree.get_root(), root_region, &mut cursor_y);
1304 self.set_last_projected_rows(cursor_y as usize);
1305 self.get_mut_current().finalize_row_hashes();
1306 let total_cells: usize = self.get_current().total_cells();
1307 self.get_mut_ansi_scratch().clear();
1308 match mode {
1309 TerminalRenderMode::StaticPlainText => {
1310 let plain: String = self.get_current().to_plain_text();
1311 let bytes: usize = plain.len();
1312 self.get_mut_ansi_scratch().push_str(&plain);
1313 TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
1314 }
1315 TerminalRenderMode::InteractiveTui => {
1316 let resized_or_first: bool = !self.get_previous_valid()
1317 || self.get_last_cols() != clamped_cols
1318 || self.get_last_rows() != clamped_rows
1319 || self.get_previous().total_cells() != total_cells;
1320 if resized_or_first {
1321 self.encode_full_frame_into_scratch();
1322 let bytes: usize = self.get_ansi_scratch().len();
1323 TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
1324 } else {
1325 self.encode_diff_frame_into_scratch()
1326 }
1327 }
1328 }
1329 }
1330
1331 fn commit_after_write(
1345 &mut self,
1346 tree: &SceneTree,
1347 clamped_cols: u16,
1348 clamped_rows: u16,
1349 mode: TerminalRenderMode,
1350 ) -> bool {
1351 self.set_last_cols(clamped_cols);
1352 self.set_last_rows(clamped_rows);
1353 let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
1354 self.set_frames_rendered(next_frames);
1355 if mode == TerminalRenderMode::StaticPlainText {
1356 self.set_previous_valid(false);
1357 let Self {
1358 last_fingerprint, ..
1359 } = self;
1360 *last_fingerprint = None;
1361 return false;
1362 }
1363 let fp: TerminalFrameFingerprint =
1364 self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
1365 let Self {
1366 previous,
1367 current,
1368 previous_valid,
1369 last_fingerprint,
1370 ..
1371 } = self;
1372 swap(current, previous);
1373 let target_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
1374 if current.total_cells() != target_cells {
1375 current.reset(clamped_cols, clamped_rows);
1376 }
1377 *previous_valid = true;
1378 *last_fingerprint = Some(fp);
1379 true
1380 }
1381
1382 pub fn handle_key(&mut self, tree: &mut SceneTree, key: KeyEvent) -> TerminalNavAction {
1394 let code: KeyCode = key.get_code();
1395 let mods: Modifiers = key.get_modifiers();
1396 if code == KeyCode::Escape
1397 || (mods.get_ctrl()
1398 && matches!(code, KeyCode::Character('c') | KeyCode::Character('C')))
1399 {
1400 self.set_exit_requested(true);
1401 return TerminalNavAction::ExitRequested;
1402 }
1403 if code == KeyCode::Tab {
1404 let focusables: Vec<NodeId> = Self::collect_focusables(tree);
1405 if focusables.is_empty() {
1406 return TerminalNavAction::Ignored;
1407 }
1408 let current: Option<NodeId> = tree.get_focus().focused_node();
1409 let next_target: NodeId = match current
1410 .and_then(|cur: NodeId| focusables.iter().position(|id: &NodeId| *id == cur))
1411 {
1412 Some(idx) => {
1413 let next_idx: usize = if mods.get_shift() {
1414 if idx == 0 {
1415 focusables.len() - 1
1416 } else {
1417 idx - 1
1418 }
1419 } else {
1420 (idx + 1) % focusables.len()
1421 };
1422 focusables[next_idx]
1423 }
1424 None => {
1425 if mods.get_shift() {
1426 focusables[focusables.len() - 1]
1427 } else {
1428 focusables[0]
1429 }
1430 }
1431 };
1432 let callbacks: Vec<(UiEventHandler, UiEvent)> = tree.update_focus(Some(next_target));
1433 for (handler, ev) in callbacks.into_iter() {
1434 if let Ok(mut cb) = handler.try_borrow_mut() {
1435 cb(&ev);
1436 }
1437 }
1438 return TerminalNavAction::FocusMoved(next_target);
1439 }
1440 if code == KeyCode::ArrowDown || code == KeyCode::ArrowUp {
1441 let delta_rows: i16 = if code == KeyCode::ArrowDown { 1 } else { -1 };
1442 if let Some(scroll_id) = Self::find_first_scroll_view(tree) {
1443 let current_y: f32 = tree
1444 .get_node(scroll_id)
1445 .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
1446 .unwrap_or(0.0);
1447 let next_y: f32 =
1448 (current_y + (delta_rows as f32) * TERMINAL_SCROLL_STEP_PX).max(0.0);
1449 tree.set_scroll_offset(scroll_id, Point::new(0.0, next_y));
1450 return TerminalNavAction::Scrolled(delta_rows);
1451 }
1452 return TerminalNavAction::Ignored;
1453 }
1454 if code == KeyCode::Enter {
1455 if let Some(target) = tree.get_focus().focused_node() {
1456 let click_kind: UiEventKind = UiEventKind::Click(Point::default());
1457 let handler_opt: Option<UiEventHandler> = tree
1458 .get_node(target)
1459 .and_then(|node: &SceneNode| node.get_handlers().handler_for(&click_kind));
1460 if let Some(handler) = handler_opt
1461 && let Ok(mut cb) = handler.try_borrow_mut()
1462 {
1463 let click_ev: UiEvent = UiEvent::new(target, click_kind);
1464 cb(&click_ev);
1465 }
1466 return TerminalNavAction::Activated(target);
1467 }
1468 return TerminalNavAction::Ignored;
1469 }
1470 TerminalNavAction::Ignored
1471 }
1472
1473 #[must_use]
1483 fn collect_focusables(tree: &SceneTree) -> Vec<NodeId> {
1484 let mut out: Vec<NodeId> = Vec::new();
1485 let mut stack: Vec<NodeId> = vec![tree.get_root()];
1486 while let Some(id) = stack.pop() {
1487 let Some(node) = tree.get_node(id) else {
1488 continue;
1489 };
1490 if node.style_ref().get_layout().get_display() == Display::None
1491 || node.style_ref().get_paint().get_opacity() <= 0.0
1492 {
1493 continue;
1494 }
1495 if Self::is_focusable_or_interactive(node) {
1496 out.push(id);
1497 }
1498 for child in tree.children_iter(id).rev() {
1499 stack.push(child);
1500 }
1501 }
1502 out
1503 }
1504
1505 #[must_use]
1515 fn find_first_scroll_view(tree: &SceneTree) -> Option<NodeId> {
1516 let mut stack: Vec<NodeId> = vec![tree.get_root()];
1517 while let Some(id) = stack.pop() {
1518 let Some(node) = tree.get_node(id) else {
1519 continue;
1520 };
1521 if node.style_ref().get_layout().get_display() == Display::None {
1522 continue;
1523 }
1524 if matches!(node.get_kind(), NodeKind::ScrollView) {
1525 return Some(id);
1526 }
1527 for child in tree.children_iter(id).rev() {
1528 stack.push(child);
1529 }
1530 }
1531 None
1532 }
1533
1534 #[must_use]
1544 fn is_focusable_or_interactive(node: &SceneNode) -> bool {
1545 node.get_interaction().get_focusable()
1546 || matches!(node.get_kind(), NodeKind::Input(_))
1547 || Self::is_clickable_node(node)
1548 }
1549
1550 #[must_use]
1560 fn is_clickable_node(node: &SceneNode) -> bool {
1561 node.get_handlers()
1562 .handler_for(&UiEventKind::Click(Point::default()))
1563 .is_some()
1564 || node.style_ref().get_paint().get_cursor() == CursorIcon::Pointer
1565 || node
1566 .a11y_props()
1567 .is_some_and(|a: A11yProps| a.get_role() == A11yRole::Button)
1568 }
1569
1570 #[must_use]
1581 fn is_node_visible(tree: &SceneTree, node_id: NodeId) -> bool {
1582 tree.get_node(node_id).is_some_and(|c: &SceneNode| {
1583 c.style_ref().get_layout().get_display() != Display::None
1584 && c.style_ref().get_paint().get_opacity() > 0.0
1585 })
1586 }
1587
1588 #[must_use]
1599 fn collect_button_label(tree: &SceneTree, node_id: NodeId) -> String {
1600 let Some(node) = tree.get_node(node_id) else {
1601 return String::new();
1602 };
1603 let mut parts: Vec<String> = Vec::new();
1604 let mut stack: Vec<NodeId> = tree.children_iter(node_id).rev().collect();
1605 while let Some(cid) = stack.pop() {
1606 let Some(child) = tree.get_node(cid) else {
1607 continue;
1608 };
1609 if child.style_ref().get_layout().get_display() == Display::None {
1610 continue;
1611 }
1612 if let NodeKind::Text(text) = child.get_kind() {
1613 let trimmed: &str = text.trim();
1614 if !trimmed.is_empty() {
1615 parts.push(trimmed.to_string());
1616 }
1617 }
1618 for grand in tree.children_iter(cid).rev() {
1619 stack.push(grand);
1620 }
1621 }
1622 if !parts.is_empty() {
1623 return parts.join(" ");
1624 }
1625 node.a11y_props()
1626 .map(|a: A11yProps| a.get_label().clone())
1627 .unwrap_or_default()
1628 }
1629
1630 fn project_node(
1640 &mut self,
1641 tree: &SceneTree,
1642 node_id: NodeId,
1643 region: TerminalRegion,
1644 y: &mut u16,
1645 ) {
1646 let x: u16 = region.get_x();
1647 let avail_w: u16 = region.get_width();
1648 let max_y: u16 = region.get_max_y();
1649 let focused: Option<NodeId> = region.get_focused();
1650 if *y >= max_y || avail_w == 0 {
1651 return;
1652 }
1653 let Some(node) = tree.get_node(node_id) else {
1654 return;
1655 };
1656 let style: &Style = node.style_ref();
1657 let layout: LayoutStyle = style.get_layout();
1658 let paint: PaintStyle = style.get_paint();
1659 let text_style: TextStyle = style.get_text();
1660 if layout.get_display() == Display::None || paint.get_opacity() <= 0.0 {
1661 return;
1662 }
1663 let is_focused: bool = focused == Some(node_id) || node.get_interaction().get_focused();
1664 let is_bold: bool = matches!(
1665 text_style.get_weight(),
1666 FontWeight::SemiBold | FontWeight::Bold
1667 );
1668 let fg: Option<Color> = Some(text_style.get_color());
1669 let bg: Option<Color> = paint.background_color();
1670 let template: TerminalCell = TerminalCell::styled(
1671 ' ',
1672 1,
1673 fg,
1674 bg,
1675 is_bold,
1676 is_focused,
1677 text_style.get_underline(),
1678 );
1679 match node.get_kind() {
1680 NodeKind::Text(content) => {
1681 if Self::is_clickable_node(node) {
1682 let display_str: String = if is_focused {
1683 format!("> [ {content} ]")
1684 } else {
1685 format!("[ {content} ]")
1686 };
1687 self.write_wrapped_text(region, y, &display_str, template);
1688 } else {
1689 self.write_wrapped_text(region, y, content.as_str(), template);
1690 }
1691 }
1692 NodeKind::Input(inp) => {
1693 let inner: String = if inp.get_value().is_empty() {
1694 inp.get_placeholder().clone()
1695 } else if inp.get_password() {
1696 let count: usize = inp.get_value().chars().count();
1697 "*".repeat(count)
1698 } else {
1699 inp.get_value().clone()
1700 };
1701 let formatted: String = if is_focused {
1702 if tree.get_caret_visible() {
1703 format!("> [ {inner}| ]")
1704 } else {
1705 format!("> [ {inner} ]")
1706 }
1707 } else {
1708 format!("[ {inner} ]")
1709 };
1710 let _: u16 = self
1711 .get_mut_current()
1712 .write_styled_text(x, *y, avail_w, &formatted, template);
1713 *y = y.saturating_add(1);
1714 }
1715 NodeKind::Image(img) => {
1716 let alt: String = node
1717 .a11y_props()
1718 .map(|a: A11yProps| a.get_label().clone())
1719 .filter(|s: &String| !s.is_empty())
1720 .map(|lbl: String| format!("{TERMINAL_IMAGE_FALLBACK_PREFIX}{lbl}]"))
1721 .unwrap_or_else(|| {
1722 format!(
1723 "{TERMINAL_IMAGE_DIM_PREFIX}{}x{}]",
1724 img.get_width(),
1725 img.get_height()
1726 )
1727 });
1728 let _: u16 = self
1729 .get_mut_current()
1730 .write_styled_text(x, *y, avail_w, &alt, template);
1731 *y = y.saturating_add(1);
1732 }
1733 NodeKind::Canvas(_) => {
1734 let alt: String = node
1735 .a11y_props()
1736 .map(|a: A11yProps| a.get_label().clone())
1737 .filter(|s: &String| !s.is_empty())
1738 .map(|lbl: String| format!("{TERMINAL_CANVAS_FALLBACK_PREFIX}{lbl}]"))
1739 .unwrap_or_else(|| TERMINAL_CANVAS_FALLBACK.to_string());
1740 let _: u16 = self
1741 .get_mut_current()
1742 .write_styled_text(x, *y, avail_w, &alt, template);
1743 *y = y.saturating_add(1);
1744 }
1745 NodeKind::Fragment => {
1746 for child_id in tree.children_iter(node_id) {
1747 if *y >= max_y {
1748 break;
1749 }
1750 self.project_node(tree, child_id, region, y);
1751 }
1752 }
1753 NodeKind::ScrollView => {
1754 self.project_scroll_view(tree, node_id, region, y);
1755 }
1756 NodeKind::View | NodeKind::Portal => {
1757 let is_root: bool = node_id == tree.get_root();
1758 if !is_root && Self::is_clickable_node(node) {
1759 let caption: String = Self::collect_button_label(tree, node_id);
1760 if !caption.is_empty() {
1761 let formatted: String = if is_focused {
1762 format!("> [ {caption} ]")
1763 } else {
1764 format!("[ {caption} ]")
1765 };
1766 let _: u16 = self
1767 .get_mut_current()
1768 .write_styled_text(x, *y, avail_w, &formatted, template);
1769 *y = y.saturating_add(1);
1770 return;
1771 }
1772 }
1773 let has_border: bool = !is_root
1774 && (paint.get_border().get_width() > 0.0
1775 || matches!(node.get_kind(), NodeKind::Portal))
1776 && avail_w >= 4
1777 && max_y.saturating_sub(*y) >= 3;
1778 if has_border {
1779 let top_y: u16 = *y;
1780 let inner_region: TerminalRegion = TerminalRegion::new(
1781 x.saturating_add(1),
1782 avail_w.saturating_sub(2),
1783 max_y.saturating_sub(1),
1784 focused,
1785 );
1786 let mut child_y: u16 = top_y.saturating_add(1);
1787 self.project_children_flow(tree, node_id, node, inner_region, &mut child_y);
1788 let box_h: u16 = child_y
1789 .saturating_sub(top_y)
1790 .saturating_add(1)
1791 .max(3)
1792 .min(max_y.saturating_sub(top_y));
1793 let border_cell: TerminalCell = TerminalCell::styled(
1794 ' ',
1795 1,
1796 Some(paint.get_border().get_color()),
1797 bg,
1798 false,
1799 is_focused,
1800 false,
1801 );
1802 self.get_mut_current()
1803 .draw_box(x, top_y, avail_w, box_h, border_cell);
1804 *y = top_y.saturating_add(box_h);
1805 } else {
1806 self.project_children_flow(tree, node_id, node, region, y);
1807 }
1808 }
1809 }
1810 }
1811
1812 fn project_children_flow(
1823 &mut self,
1824 tree: &SceneTree,
1825 node_id: NodeId,
1826 node: &SceneNode,
1827 region: TerminalRegion,
1828 y: &mut u16,
1829 ) {
1830 let x: u16 = region.get_x();
1831 let avail_w: u16 = region.get_width();
1832 let max_y: u16 = region.get_max_y();
1833 let focused: Option<NodeId> = region.get_focused();
1834 let layout: LayoutStyle = node.style_ref().get_layout();
1835 let is_row: bool = matches!(
1836 layout.get_flex_direction(),
1837 FlexDirection::Row | FlexDirection::RowReverse
1838 ) && layout.get_display() == Display::Flex;
1839 if is_row {
1840 let visible_count: usize = tree
1841 .children_iter(node_id)
1842 .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
1843 .count();
1844 if visible_count > 1 && avail_w >= (visible_count as u16).saturating_mul(2) {
1845 let count: u16 = visible_count as u16;
1846 let total_gaps: u16 = count.saturating_sub(1).saturating_mul(TERMINAL_ROW_GAP);
1847 let slot_w: u16 = avail_w.saturating_sub(total_gaps) / count;
1848 if slot_w >= 2 {
1849 let row_start_y: u16 = *y;
1850 let mut max_child_end: u16 = row_start_y;
1851 let mut visible_idx: usize = 0;
1852 for child_id in tree.children_iter(node_id) {
1853 if !Self::is_node_visible(tree, child_id) {
1854 continue;
1855 }
1856 let cx: u16 =
1857 x.saturating_add((visible_idx as u16).saturating_mul(slot_w + 1));
1858 let rem_w: u16 = avail_w.saturating_sub(cx.saturating_sub(x));
1859 let col_w: u16 = if visible_idx + 1 == visible_count {
1860 rem_w
1861 } else {
1862 slot_w.min(rem_w)
1863 };
1864 let mut cy: u16 = row_start_y;
1865 let child_region: TerminalRegion =
1866 TerminalRegion::new(cx, col_w, max_y, focused);
1867 self.project_node(tree, child_id, child_region, &mut cy);
1868 if cy > max_child_end {
1869 max_child_end = cy;
1870 }
1871 visible_idx += 1;
1872 }
1873 *y = max_child_end;
1874 return;
1875 }
1876 }
1877 }
1878 for child_id in tree.children_iter(node_id) {
1879 if *y >= max_y {
1880 break;
1881 }
1882 if Self::is_node_visible(tree, child_id) {
1883 self.project_node(tree, child_id, region, y);
1884 }
1885 }
1886 }
1887
1888 fn project_scroll_view(
1898 &mut self,
1899 tree: &SceneTree,
1900 node_id: NodeId,
1901 region: TerminalRegion,
1902 y: &mut u16,
1903 ) {
1904 self.get_mut_tracked_scroll_nodes().push(node_id);
1905 let x: u16 = region.get_x();
1906 let avail_w: u16 = region.get_width();
1907 let max_y: u16 = region.get_max_y();
1908 let focused: Option<NodeId> = region.get_focused();
1909 let Some(node) = tree.get_node(node_id) else {
1910 return;
1911 };
1912 let total_visible: usize = tree
1913 .children_iter(node_id)
1914 .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
1915 .count();
1916 let avail_h: u16 = max_y.saturating_sub(*y);
1917 if avail_h == 0 || total_visible == 0 {
1918 return;
1919 }
1920 let scroll_y: f32 = node.get_layout_box().get_scroll_offset().get_y().max(0.0);
1921 let skip_items: usize = ((scroll_y / TERMINAL_SCROLL_STEP_PX).floor() as usize)
1922 .min(total_visible.saturating_sub(1));
1923 let needs_rail: bool = total_visible > (avail_h as usize) && avail_w >= 3;
1924 let inner_w: u16 = if needs_rail {
1925 avail_w.saturating_sub(1)
1926 } else {
1927 avail_w
1928 };
1929 let child_region: TerminalRegion = TerminalRegion::new(x, inner_w, max_y, focused);
1930 let start_y: u16 = *y;
1931 let mut seen_visible: usize = 0;
1932 for child_id in tree.children_iter(node_id) {
1933 if !Self::is_node_visible(tree, child_id) {
1934 continue;
1935 }
1936 if seen_visible < skip_items {
1937 seen_visible += 1;
1938 continue;
1939 }
1940 if *y >= max_y {
1941 break;
1942 }
1943 self.project_node(tree, child_id, child_region, y);
1944 seen_visible += 1;
1945 }
1946 if needs_rail {
1947 let rail_x: u16 = x.saturating_add(inner_w);
1948 let total_items: usize = total_visible.max(1);
1949 let thumb_offset: u16 = ((skip_items * (avail_h as usize)) / total_items)
1950 .min((avail_h - 1) as usize) as u16;
1951 for offset in 0..avail_h {
1952 let glyph: char = if offset == thumb_offset {
1953 TERMINAL_SCROLL_THUMB
1954 } else {
1955 TERMINAL_SCROLL_TRACK
1956 };
1957 let _: u16 = self.get_mut_current().put_cell(
1958 rail_x,
1959 start_y.saturating_add(offset),
1960 TerminalCell::styled(glyph, 1, None, None, false, false, false),
1961 );
1962 }
1963 }
1964 }
1965
1966 fn write_wrapped_text(
1976 &mut self,
1977 region: TerminalRegion,
1978 y: &mut u16,
1979 text: &str,
1980 template: TerminalCell,
1981 ) {
1982 let x: u16 = region.get_x();
1983 let avail_w: u16 = region.get_width();
1984 let max_y: u16 = region.get_max_y();
1985 if *y >= max_y || avail_w == 0 {
1986 return;
1987 }
1988 let mut wrote_any_line: bool = false;
1989 for raw_line in text.split('\n') {
1990 if *y >= max_y {
1991 break;
1992 }
1993 if raw_line.is_empty() {
1994 *y = y.saturating_add(1);
1995 wrote_any_line = true;
1996 continue;
1997 }
1998 let raw_bytes: &[u8] = raw_line.as_bytes();
1999 if raw_line.is_ascii() && raw_bytes.iter().all(|b: &u8| (0x20..=0x7E).contains(b)) {
2000 let chunk_len: usize = avail_w as usize;
2001 let mut offset: usize = 0;
2002 while offset < raw_bytes.len() {
2003 if *y >= max_y {
2004 return;
2005 }
2006 let end: usize = (offset + chunk_len).min(raw_bytes.len());
2007 let _: u16 = self.get_mut_current().write_printable_ascii_run(
2008 x,
2009 *y,
2010 &raw_bytes[offset..end],
2011 template,
2012 );
2013 offset = end;
2014 if offset < raw_bytes.len() {
2015 *y = y.saturating_add(1);
2016 }
2017 }
2018 *y = y.saturating_add(1);
2019 wrote_any_line = true;
2020 continue;
2021 }
2022 let mut cur_col: u16 = 0;
2023 let mut rest: &str = raw_line;
2024 while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
2025 rest = next_rest;
2026 if cluster.starts_with('\r') {
2027 continue;
2028 }
2029 let width: u8 = grapheme_display_width(cluster);
2030 if width == 0 {
2031 continue;
2032 }
2033 let w_u16: u16 = width as u16;
2034 if w_u16 > avail_w {
2035 continue;
2036 }
2037 if cur_col.saturating_add(w_u16) > avail_w {
2038 *y = y.saturating_add(1);
2039 if *y >= max_y {
2040 return;
2041 }
2042 cur_col = 0;
2043 }
2044 let cell: TerminalCell = TerminalCell::from_grapheme(cluster, width, template);
2045 let consumed: u16 = self.get_mut_current().put_cell(x + cur_col, *y, cell);
2046 cur_col = cur_col.saturating_add(consumed);
2047 }
2048 *y = y.saturating_add(1);
2049 wrote_any_line = true;
2050 }
2051 if !wrote_any_line {
2052 *y = y.saturating_add(1);
2053 }
2054 }
2055
2056 fn encode_full_frame_into_scratch(&mut self) {
2062 let sync_mode: bool = self.get_sync_output_mode();
2063 let Self {
2064 current,
2065 ansi_scratch,
2066 ..
2067 } = self;
2068 let cols: u16 = current.get_cols();
2069 let rows: u16 = current.get_rows();
2070 let needed: usize = current.total_cells().saturating_mul(2);
2071 if ansi_scratch.capacity() < needed {
2072 ansi_scratch.reserve(needed - ansi_scratch.capacity());
2073 }
2074 if sync_mode {
2075 ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
2076 }
2077 ansi_scratch.push_str(ANSI_CLEAR_AND_HOME);
2078 let mut active_style: Option<TerminalCell> = None;
2079 let mut cursor_pos: Option<(u16, u16)> = Some((0, 0));
2080 for row in 0..rows {
2081 append_cursor_move_smart(ansi_scratch, cursor_pos, 0, row);
2082 cursor_pos = Some((0, row));
2083 let mut col: u16 = 0;
2084 while col < cols {
2085 let Some(cell) = current.cell(col, row) else {
2086 col += 1;
2087 continue;
2088 };
2089 if cell.is_continuation() {
2090 col += 1;
2091 continue;
2092 }
2093 append_sgr_delta(ansi_scratch, active_style, &cell);
2094 active_style = Some(cell);
2095 cell.push_grapheme_to(ansi_scratch);
2096 let step: u16 = cell.get_width().max(1) as u16;
2097 cursor_pos = Some((col.saturating_add(step), row));
2098 col = col.saturating_add(step);
2099 }
2100 }
2101 ansi_scratch.push_str(ANSI_RESET_STYLE);
2102 if sync_mode {
2103 ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
2104 }
2105 }
2106
2107 fn encode_diff_frame_into_scratch(&mut self) -> TerminalDiffStats {
2117 let sync_mode: bool = self.get_sync_output_mode();
2118 let Self {
2119 previous,
2120 current,
2121 ansi_scratch,
2122 ..
2123 } = self;
2124 let total_cells: usize = current.total_cells();
2125 let cols: u16 = current.get_cols();
2126 let rows: u16 = current.get_rows();
2127 let mut changed_cells: usize = 0;
2128 let mut active_style: Option<TerminalCell> = None;
2129 let mut cursor_pos: Option<(u16, u16)> = None;
2130 let mut emitted_any: bool = false;
2131 for row in 0..rows {
2132 let row_idx: usize = row as usize;
2133 let cur_hash: Option<u64> = current.get_row_hashes().get(row_idx).copied();
2134 let prev_hash: Option<u64> = previous.get_row_hashes().get(row_idx).copied();
2135 if cur_hash.is_some() && cur_hash == prev_hash {
2136 continue;
2137 }
2138 let mut col: u16 = 0;
2139 while col < cols {
2140 let Some(cur_cell) = current.cell(col, row) else {
2141 col += 1;
2142 continue;
2143 };
2144 let Some(prev_cell) = previous.cell(col, row) else {
2145 col += 1;
2146 continue;
2147 };
2148 if cur_cell.is_continuation() {
2149 col += 1;
2150 continue;
2151 }
2152 let mut cell_dirty: bool =
2153 Self::is_cell_dirty(current, previous, col, row, cur_cell, prev_cell);
2154 if !cell_dirty
2155 && let Some((cur_cx, cur_cy)) = cursor_pos
2156 && cur_cy == row
2157 && cur_cx == col
2158 && let Some(active) = active_style
2159 && active.same_style(&cur_cell)
2160 && Self::has_dirty_within_gap(current, previous, col, row, cols)
2161 {
2162 cell_dirty = true;
2163 }
2164 if !cell_dirty {
2165 col = col.saturating_add(cur_cell.get_width().max(1) as u16);
2166 continue;
2167 }
2168 if !emitted_any && sync_mode {
2169 ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
2170 }
2171 emitted_any = true;
2172 let step: u16 = cur_cell.get_width().max(1) as u16;
2173 if cur_cell != prev_cell {
2174 changed_cells = changed_cells.saturating_add(step as usize);
2175 }
2176 append_cursor_move_smart(ansi_scratch, cursor_pos, col, row);
2177 append_sgr_delta(ansi_scratch, active_style, &cur_cell);
2178 active_style = Some(cur_cell);
2179 cur_cell.push_grapheme_to(ansi_scratch);
2180 cursor_pos = Some((col.saturating_add(step), row));
2181 col = col.saturating_add(step);
2182 }
2183 }
2184 if !emitted_any {
2185 return TerminalDiffStats::new(total_cells, 0, 0, true, false);
2186 }
2187 ansi_scratch.push_str(ANSI_RESET_STYLE);
2188 if sync_mode {
2189 ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
2190 }
2191 let output_bytes: usize = ansi_scratch.len();
2192 TerminalDiffStats::new(
2193 total_cells,
2194 changed_cells.max(1),
2195 output_bytes,
2196 false,
2197 false,
2198 )
2199 }
2200
2201 #[must_use]
2216 fn is_cell_dirty(
2217 current: &TerminalCellGrid,
2218 previous: &TerminalCellGrid,
2219 col: u16,
2220 row: u16,
2221 cur_cell: TerminalCell,
2222 prev_cell: TerminalCell,
2223 ) -> bool {
2224 if cur_cell != prev_cell {
2225 return true;
2226 }
2227 if cur_cell.is_wide_lead()
2228 && col.saturating_add(1) < current.get_cols()
2229 && current.cell(col + 1, row) != previous.cell(col + 1, row)
2230 {
2231 return true;
2232 }
2233 if prev_cell.is_continuation() && !cur_cell.is_continuation() {
2234 return true;
2235 }
2236 if col > 0
2237 && let Some(prev_left) = previous.cell(col - 1, row)
2238 && prev_left.is_wide_lead()
2239 && current.cell(col - 1, row) != Some(prev_left)
2240 {
2241 return true;
2242 }
2243 false
2244 }
2245
2246 #[must_use]
2260 fn has_dirty_within_gap(
2261 current: &TerminalCellGrid,
2262 previous: &TerminalCellGrid,
2263 start_col: u16,
2264 row: u16,
2265 cols: u16,
2266 ) -> bool {
2267 let mut probe: u16 = start_col.saturating_add(1);
2268 let max_probe: u16 = start_col
2269 .saturating_add(TERMINAL_COALESCE_GAP_MAX)
2270 .min(cols.saturating_sub(1));
2271 while probe <= max_probe {
2272 if let (Some(c), Some(p)) = (current.cell(probe, row), previous.cell(probe, row))
2273 && !c.is_continuation()
2274 && Self::is_cell_dirty(current, previous, probe, row, c, p)
2275 {
2276 return true;
2277 }
2278 probe = probe.saturating_add(1);
2279 }
2280 false
2281 }
2282}