euv_core/render/terminal/
fn.rs1use super::*;
2
3#[must_use]
13pub const fn is_zero_width_combining(ch: char) -> bool {
14 let code: u32 = ch as u32;
15 matches!(
16 code,
17 0x0300..=0x036F
18 | 0x0483..=0x0489
19 | 0x0591..=0x05BD
20 | 0x05BF
21 | 0x05C1..=0x05C2
22 | 0x05C4..=0x05C5
23 | 0x05C7
24 | 0x0610..=0x061A
25 | 0x064B..=0x065F
26 | 0x0670
27 | 0x06D6..=0x06DC
28 | 0x06DF..=0x06E4
29 | 0x06E7..=0x06E8
30 | 0x06EA..=0x06ED
31 | 0x1AB0..=0x1AFF
32 | 0x1DC0..=0x1DFF
33 | 0x200B..=0x200F
34 | 0x202A..=0x202E
35 | 0x2060..=0x206F
36 | 0x20D0..=0x20FF
37 | 0xFE00..=0xFE0F
38 | 0xFE20..=0xFE2F
39 | 0xFEFF
40 | 0xE0100..=0xE01EF
41 )
42}
43
44#[must_use]
54pub const fn is_regional_indicator(ch: char) -> bool {
55 let code: u32 = ch as u32;
56 code >= 0x1F1E6 && code <= 0x1F1FF
57}
58
59#[must_use]
69pub const fn is_emoji_modifier(ch: char) -> bool {
70 let code: u32 = ch as u32;
71 code >= 0x1F3FB && code <= 0x1F3FF
72}
73
74#[must_use]
84pub const fn is_tag_extend(ch: char) -> bool {
85 let code: u32 = ch as u32;
86 code >= 0xE0020 && code <= 0xE007F
87}
88
89#[must_use]
99pub const fn is_wide_char(ch: char) -> bool {
100 let code: u32 = ch as u32;
101 matches!(
102 code,
103 0x1100..=0x115F
104 | 0x231A..=0x231B
105 | 0x2329..=0x232A
106 | 0x23E9..=0x23EC
107 | 0x23F0
108 | 0x23F3
109 | 0x25FD..=0x25FE
110 | 0x2614..=0x2615
111 | 0x2648..=0x2653
112 | 0x267F
113 | 0x2693
114 | 0x26A1
115 | 0x26AA..=0x26AB
116 | 0x26BD..=0x26BE
117 | 0x26C4..=0x26C5
118 | 0x26CE
119 | 0x26D4
120 | 0x26EA
121 | 0x26F2..=0x26F3
122 | 0x26F5
123 | 0x26FA
124 | 0x26FD
125 | 0x2705
126 | 0x270A..=0x270B
127 | 0x2728
128 | 0x274C
129 | 0x274E
130 | 0x2753..=0x2755
131 | 0x2757
132 | 0x2795..=0x2797
133 | 0x27B0
134 | 0x27BF
135 | 0x2B1B..=0x2B1C
136 | 0x2B50
137 | 0x2B55
138 | 0x2E80..=0x303E
139 | 0x3041..=0x33FF
140 | 0x3400..=0x4DBF
141 | 0x4E00..=0xA4CF
142 | 0xA960..=0xA97F
143 | 0xAC00..=0xD7A3
144 | 0xF900..=0xFAFF
145 | 0xFE10..=0xFE19
146 | 0xFE30..=0xFE6F
147 | 0xFF01..=0xFF60
148 | 0xFFE0..=0xFFE6
149 | 0x1F300..=0x1FAFF
150 | 0x20000..=0x3FFFD
151 )
152}
153
154#[must_use]
164pub const fn terminal_char_width(ch: char) -> u8 {
165 let code: u32 = ch as u32;
166 if code <= 0x1F || (code >= 0x7F && code <= 0x9F) || is_zero_width_combining(ch) {
167 0
168 } else if is_wide_char(ch) {
169 2
170 } else {
171 1
172 }
173}
174
175#[must_use]
185pub fn next_grapheme_cluster(input: &str) -> Option<(&str, &str)> {
186 let mut iter: Chars<'_> = input.chars();
187 let first: char = iter.next()?;
188 if first == '\r' {
189 let mut end: usize = first.len_utf8();
190 if input[end..].starts_with('\n') {
191 end += 1;
192 }
193 return Some((&input[..end], &input[end..]));
194 }
195 if first == '\n' {
196 return Some((&input[..1], &input[1..]));
197 }
198 let mut end: usize = first.len_utf8();
199 if is_regional_indicator(first)
200 && let Some(second) = input[end..].chars().next()
201 && is_regional_indicator(second)
202 {
203 end += second.len_utf8();
204 }
205 loop {
206 let rest: &str = &input[end..];
207 let Some(next_ch) = rest.chars().next() else {
208 break;
209 };
210 if next_ch == '\u{200D}' {
211 let after_zwj_offset: usize = end + next_ch.len_utf8();
212 if let Some(joined) = input[after_zwj_offset..].chars().next()
213 && joined != '\n'
214 && joined != '\r'
215 {
216 end = after_zwj_offset + joined.len_utf8();
217 continue;
218 }
219 end = after_zwj_offset;
220 continue;
221 }
222 if is_zero_width_combining(next_ch)
223 || is_emoji_modifier(next_ch)
224 || is_tag_extend(next_ch)
225 || next_ch == '\u{20E3}'
226 {
227 end += next_ch.len_utf8();
228 continue;
229 }
230 break;
231 }
232 Some((&input[..end], &input[end..]))
233}
234
235#[must_use]
245pub fn grapheme_display_width(cluster: &str) -> u8 {
246 let mut iter: Chars<'_> = cluster.chars();
247 let Some(first) = iter.next() else {
248 return 0;
249 };
250 let mut has_zwj: bool = false;
251 let mut has_emoji_vs: bool = false;
252 let mut has_text_vs: bool = false;
253 let mut has_keycap: bool = false;
254 let mut has_skin_mod: bool = false;
255 let mut regional_count: u8 = if is_regional_indicator(first) { 1 } else { 0 };
256 for ch in iter {
257 if ch == '\u{200D}' {
258 has_zwj = true;
259 } else if ch == '\u{FE0F}' {
260 has_emoji_vs = true;
261 } else if ch == '\u{FE0E}' {
262 has_text_vs = true;
263 } else if ch == '\u{20E3}' {
264 has_keycap = true;
265 } else if is_emoji_modifier(ch) {
266 has_skin_mod = true;
267 } else if is_regional_indicator(ch) {
268 regional_count = regional_count.saturating_add(1);
269 }
270 }
271 if regional_count >= 2 || has_zwj {
272 return 2;
273 }
274 if has_keycap || has_skin_mod {
275 return 2;
276 }
277 if has_emoji_vs && !has_text_vs {
278 return 2;
279 }
280 let base_w: u8 = terminal_char_width(first);
281 if has_text_vs && base_w == 2 && !is_cjk_ideograph(first) {
282 return 1;
283 }
284 base_w
285}
286
287#[must_use]
297const fn is_cjk_ideograph(ch: char) -> bool {
298 let code: u32 = ch as u32;
299 matches!(
300 code,
301 0x1100..=0x115F
302 | 0x2E80..=0xA4CF
303 | 0xAC00..=0xD7A3
304 | 0xF900..=0xFAFF
305 | 0xFE10..=0xFE6F
306 | 0xFF01..=0xFF60
307 | 0xFFE0..=0xFFE6
308 | 0x20000..=0x3FFFD
309 )
310}
311
312#[must_use]
322pub fn terminal_str_width(text: &str) -> usize {
323 let mut total: usize = 0;
324 let mut rest: &str = text;
325 while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
326 total = total.saturating_add(grapheme_display_width(cluster) as usize);
327 rest = next_rest;
328 }
329 total
330}
331
332#[must_use]
338pub fn detect_stdout_is_tty() -> bool {
339 #[cfg(not(target_arch = "wasm32"))]
340 {
341 io::stdout().is_terminal()
342 }
343 #[cfg(target_arch = "wasm32")]
344 {
345 false
346 }
347}
348
349#[must_use]
362pub const fn resolve_cli_render_mode(
363 is_tty: bool,
364 force_ansi: Option<bool>,
365 no_color: bool,
366 term_is_dumb: bool,
367) -> TerminalRenderMode {
368 match force_ansi {
369 Some(true) => TerminalRenderMode::InteractiveTui,
370 Some(false) => TerminalRenderMode::StaticPlainText,
371 None => {
372 if is_tty && !no_color && !term_is_dumb {
373 TerminalRenderMode::InteractiveTui
374 } else {
375 TerminalRenderMode::StaticPlainText
376 }
377 }
378 }
379}
380
381#[must_use]
393pub fn render_static_plain_text(tree: &SceneTree, cols: u16, rows: u16) -> String {
394 let mut renderer: TerminalRenderer = TerminalRenderer::new();
395 let (plain, _): (String, TerminalDiffStats) =
396 renderer.render_tree(tree, cols, rows, TerminalRenderMode::StaticPlainText);
397 plain
398}
399
400#[cfg(not(target_arch = "wasm32"))]
415pub fn write_cli_streams<WOut, WErr>(
416 tree: &SceneTree,
417 cols: u16,
418 rows: u16,
419 diagnostic: Option<&str>,
420 stdout: &mut WOut,
421 stderr: &mut WErr,
422) -> CliWriteStatus
423where
424 WOut: Write,
425 WErr: Write,
426{
427 let plain: String = render_static_plain_text(tree, cols, rows);
428 if let Err(err) = stdout.write_all(plain.as_bytes()) {
429 return classify_io_error(&err);
430 }
431 if !plain.is_empty()
432 && !plain.ends_with('\n')
433 && let Err(err) = stdout.write_all(TERMINAL_NEWLINE_BYTES)
434 {
435 return classify_io_error(&err);
436 }
437 if let Err(err) = stdout.flush() {
438 return classify_io_error(&err);
439 }
440 if let Some(diag) = diagnostic
441 && !diag.is_empty()
442 {
443 let _: io::Result<()> = stderr.write_all(diag.as_bytes());
444 if !diag.ends_with('\n') {
445 let _: io::Result<()> = stderr.write_all(TERMINAL_NEWLINE_BYTES);
446 }
447 let _: io::Result<()> = stderr.flush();
448 }
449 CliWriteStatus::Written
450}
451
452#[cfg(not(target_arch = "wasm32"))]
462#[must_use]
463pub(crate) fn classify_io_error(err: &io::Error) -> CliWriteStatus {
464 if err.kind() == io::ErrorKind::BrokenPipe {
465 CliWriteStatus::BrokenPipe
466 } else {
467 CliWriteStatus::IoError
468 }
469}
470
471pub(crate) fn append_u32_ascii(out: &mut String, mut val: u32) {
478 let mut digits: [u8; 10] = [0; 10];
479 let mut idx: usize = 10;
480 if val == 0 {
481 out.push('0');
482 return;
483 }
484 while val > 0 {
485 idx -= 1;
486 digits[idx] = TERMINAL_ASCII_ZERO + ((val % 10) as u8);
487 val /= 10;
488 }
489 if let Ok(text) = from_utf8(&digits[idx..10]) {
490 out.push_str(text);
491 }
492}
493
494pub(crate) fn append_u8_ascii(out: &mut String, val: u8) {
501 if val >= 100 {
502 out.push((TERMINAL_ASCII_ZERO + (val / 100)) as char);
503 out.push((TERMINAL_ASCII_ZERO + ((val / 10) % 10)) as char);
504 out.push((TERMINAL_ASCII_ZERO + (val % 10)) as char);
505 } else if val >= 10 {
506 out.push((TERMINAL_ASCII_ZERO + (val / 10)) as char);
507 out.push((TERMINAL_ASCII_ZERO + (val % 10)) as char);
508 } else {
509 out.push((TERMINAL_ASCII_ZERO + val) as char);
510 }
511}
512
513pub(crate) fn append_cursor_move(out: &mut String, col: u16, row: u16) {
521 if col == 0 && row == 0 {
522 out.push_str(ANSI_CURSOR_HOME);
523 return;
524 }
525 out.push_str(ANSI_CSI_PREFIX);
526 append_u32_ascii(out, (row as u32) + 1);
527 out.push(';');
528 append_u32_ascii(out, (col as u32) + 1);
529 out.push('H');
530}
531
532pub(crate) fn append_cursor_move_smart(
541 out: &mut String,
542 cursor_pos: Option<(u16, u16)>,
543 col: u16,
544 row: u16,
545) {
546 if cursor_pos == Some((col, row)) {
547 return;
548 }
549 if col == 0 && row == 0 {
550 out.push_str(ANSI_CURSOR_HOME);
551 return;
552 }
553 if let Some((cur_col, cur_row)) = cursor_pos
554 && cur_row == row
555 && col > cur_col
556 {
557 let delta: u16 = col - cur_col;
558 if delta == 1 {
559 out.push_str(ANSI_CURSOR_RIGHT_ONE);
560 return;
561 }
562 out.push_str(ANSI_CSI_PREFIX);
563 append_u32_ascii(out, delta as u32);
564 out.push('C');
565 return;
566 }
567 append_cursor_move(out, col, row);
568}
569
570pub(crate) fn append_sgr_style(
581 out: &mut String,
582 fg: Option<Color>,
583 bg: Option<Color>,
584 bold: bool,
585 reverse: bool,
586 underline: bool,
587) {
588 out.push_str(ANSI_CSI_PREFIX);
589 out.push('0');
590 if bold {
591 out.push_str(ANSI_BOLD_CODE);
592 }
593 if reverse {
594 out.push_str(ANSI_REVERSE_CODE);
595 }
596 if underline {
597 out.push_str(ANSI_UNDERLINE_CODE);
598 }
599 if let Some(color) = fg {
600 out.push_str(ANSI_FG_TRUECOLOR_PREFIX);
601 append_u8_ascii(out, color.get_r());
602 out.push(';');
603 append_u8_ascii(out, color.get_g());
604 out.push(';');
605 append_u8_ascii(out, color.get_b());
606 }
607 if let Some(color) = bg {
608 out.push_str(ANSI_BG_TRUECOLOR_PREFIX);
609 append_u8_ascii(out, color.get_r());
610 out.push(';');
611 append_u8_ascii(out, color.get_g());
612 out.push(';');
613 append_u8_ascii(out, color.get_b());
614 }
615 out.push('m');
616}
617
618pub(crate) fn append_sgr_delta(
626 out: &mut String,
627 prev_style: Option<TerminalCell>,
628 next: &TerminalCell,
629) {
630 let Some(prev) = prev_style else {
631 append_sgr_style(
632 out,
633 next.fg_color(),
634 next.bg_color(),
635 next.get_bold(),
636 next.get_reverse(),
637 next.get_underline(),
638 );
639 return;
640 };
641 if prev.same_style(next) {
642 return;
643 }
644 let needs_reset: bool = (prev.get_bold() && !next.get_bold())
645 || (prev.get_reverse() && !next.get_reverse())
646 || (prev.get_underline() && !next.get_underline())
647 || (prev.fg_color().is_some() && next.fg_color().is_none())
648 || (prev.bg_color().is_some() && next.bg_color().is_none());
649 if needs_reset {
650 append_sgr_style(
651 out,
652 next.fg_color(),
653 next.bg_color(),
654 next.get_bold(),
655 next.get_reverse(),
656 next.get_underline(),
657 );
658 return;
659 }
660 out.push_str(ANSI_CSI_PREFIX);
661 let mut emitted: bool = false;
662 if next.get_bold() && !prev.get_bold() {
663 out.push('1');
664 emitted = true;
665 }
666 if next.get_reverse() && !prev.get_reverse() {
667 if emitted {
668 out.push(';');
669 }
670 out.push('7');
671 emitted = true;
672 }
673 if next.get_underline() && !prev.get_underline() {
674 if emitted {
675 out.push(';');
676 }
677 out.push('4');
678 emitted = true;
679 }
680 if let Some(fg) = next.fg_color()
681 && prev.fg_color() != Some(fg)
682 {
683 if emitted {
684 out.push(';');
685 }
686 out.push_str(ANSI_FG_TRUECOLOR_HEAD);
687 append_u8_ascii(out, fg.get_r());
688 out.push(';');
689 append_u8_ascii(out, fg.get_g());
690 out.push(';');
691 append_u8_ascii(out, fg.get_b());
692 emitted = true;
693 }
694 if let Some(bg) = next.bg_color()
695 && prev.bg_color() != Some(bg)
696 {
697 if emitted {
698 out.push(';');
699 }
700 out.push_str(ANSI_BG_TRUECOLOR_HEAD);
701 append_u8_ascii(out, bg.get_r());
702 out.push(';');
703 append_u8_ascii(out, bg.get_g());
704 out.push(';');
705 append_u8_ascii(out, bg.get_b());
706 }
707 out.push('m');
708}
709
710#[must_use]
721pub(crate) const fn fnv1a_mix_u64(mut hash: u64, value: u64) -> u64 {
722 let bytes: [u8; 8] = value.to_le_bytes();
723 let mut idx: usize = 0;
724 while idx < 8 {
725 hash ^= bytes[idx] as u64;
726 hash = hash.wrapping_mul(TERMINAL_FNV_PRIME);
727 idx += 1;
728 }
729 hash
730}
731
732#[must_use]
742pub(crate) fn hash_terminal_row(cells: &[TerminalCell]) -> u64 {
743 let mut hash: u64 = TERMINAL_FNV_OFFSET_BASIS;
744 for cell in cells.iter() {
745 let fg_bits: u64 = match cell.fg_color() {
746 Some(c) => {
747 0x0100_0000_u64
748 | ((c.get_r() as u64) << 16)
749 | ((c.get_g() as u64) << 8)
750 | (c.get_b() as u64)
751 }
752 None => 0,
753 };
754 let bg_bits: u64 = match cell.bg_color() {
755 Some(c) => {
756 0x0100_0000_u64
757 | ((c.get_r() as u64) << 16)
758 | ((c.get_g() as u64) << 8)
759 | (c.get_b() as u64)
760 }
761 None => 0,
762 };
763 let color_bits: u64 = fg_bits | (bg_bits << 32);
764 let style_bits: u64 = ((cell.get_ch() as u64) << 16)
765 | ((cell.get_width() as u64) << 8)
766 | ((cell.get_tail_len() as u64) << 3)
767 | (if cell.get_bold() { 1 } else { 0 })
768 | (if cell.get_reverse() { 2 } else { 0 })
769 | (if cell.get_underline() { 4 } else { 0 });
770 hash = (hash ^ style_bits).wrapping_mul(TERMINAL_FNV_PRIME);
771 hash = (hash ^ color_bits).wrapping_mul(TERMINAL_FNV_PRIME);
772 let tail_len: usize = cell.get_tail_len() as usize;
773 if tail_len > 0 {
774 let tail: &[u8] = cell.tail_bytes();
775 for byte in tail.iter().copied() {
776 hash ^= byte as u64;
777 hash = hash.wrapping_mul(TERMINAL_FNV_PRIME);
778 }
779 }
780 }
781 hash
782}