use super::*;
#[must_use]
pub const fn is_zero_width_combining(ch: char) -> bool {
let code: u32 = ch as u32;
matches!(
code,
0x0300..=0x036F
| 0x0483..=0x0489
| 0x0591..=0x05BD
| 0x05BF
| 0x05C1..=0x05C2
| 0x05C4..=0x05C5
| 0x05C7
| 0x0610..=0x061A
| 0x064B..=0x065F
| 0x0670
| 0x06D6..=0x06DC
| 0x06DF..=0x06E4
| 0x06E7..=0x06E8
| 0x06EA..=0x06ED
| 0x1AB0..=0x1AFF
| 0x1DC0..=0x1DFF
| 0x200B..=0x200F
| 0x202A..=0x202E
| 0x2060..=0x206F
| 0x20D0..=0x20FF
| 0xFE00..=0xFE0F
| 0xFE20..=0xFE2F
| 0xFEFF
| 0xE0100..=0xE01EF
)
}
#[must_use]
pub const fn is_regional_indicator(ch: char) -> bool {
let code: u32 = ch as u32;
code >= 0x1F1E6 && code <= 0x1F1FF
}
#[must_use]
pub const fn is_emoji_modifier(ch: char) -> bool {
let code: u32 = ch as u32;
code >= 0x1F3FB && code <= 0x1F3FF
}
#[must_use]
pub const fn is_tag_extend(ch: char) -> bool {
let code: u32 = ch as u32;
code >= 0xE0020 && code <= 0xE007F
}
#[must_use]
pub const fn is_wide_char(ch: char) -> bool {
let code: u32 = ch as u32;
matches!(
code,
0x1100..=0x115F
| 0x231A..=0x231B
| 0x2329..=0x232A
| 0x23E9..=0x23EC
| 0x23F0
| 0x23F3
| 0x25FD..=0x25FE
| 0x2614..=0x2615
| 0x2648..=0x2653
| 0x267F
| 0x2693
| 0x26A1
| 0x26AA..=0x26AB
| 0x26BD..=0x26BE
| 0x26C4..=0x26C5
| 0x26CE
| 0x26D4
| 0x26EA
| 0x26F2..=0x26F3
| 0x26F5
| 0x26FA
| 0x26FD
| 0x2705
| 0x270A..=0x270B
| 0x2728
| 0x274C
| 0x274E
| 0x2753..=0x2755
| 0x2757
| 0x2795..=0x2797
| 0x27B0
| 0x27BF
| 0x2B1B..=0x2B1C
| 0x2B50
| 0x2B55
| 0x2E80..=0x303E
| 0x3041..=0x33FF
| 0x3400..=0x4DBF
| 0x4E00..=0xA4CF
| 0xA960..=0xA97F
| 0xAC00..=0xD7A3
| 0xF900..=0xFAFF
| 0xFE10..=0xFE19
| 0xFE30..=0xFE6F
| 0xFF01..=0xFF60
| 0xFFE0..=0xFFE6
| 0x1F300..=0x1FAFF
| 0x20000..=0x3FFFD
)
}
#[must_use]
pub const fn terminal_char_width(ch: char) -> u8 {
let code: u32 = ch as u32;
if code <= 0x1F || (code >= 0x7F && code <= 0x9F) || is_zero_width_combining(ch) {
0
} else if is_wide_char(ch) {
2
} else {
1
}
}
#[must_use]
pub fn next_grapheme_cluster(input: &str) -> Option<(&str, &str)> {
let mut iter: Chars<'_> = input.chars();
let first: char = iter.next()?;
if first == '\r' {
let mut end: usize = first.len_utf8();
if input[end..].starts_with('\n') {
end += 1;
}
return Some((&input[..end], &input[end..]));
}
if first == '\n' {
return Some((&input[..1], &input[1..]));
}
let mut end: usize = first.len_utf8();
if is_regional_indicator(first)
&& let Some(second) = input[end..].chars().next()
&& is_regional_indicator(second)
{
end += second.len_utf8();
}
loop {
let rest: &str = &input[end..];
let Some(next_ch) = rest.chars().next() else {
break;
};
if next_ch == '\u{200D}' {
let after_zwj_offset: usize = end + next_ch.len_utf8();
if let Some(joined) = input[after_zwj_offset..].chars().next()
&& joined != '\n'
&& joined != '\r'
{
end = after_zwj_offset + joined.len_utf8();
continue;
}
end = after_zwj_offset;
continue;
}
if is_zero_width_combining(next_ch)
|| is_emoji_modifier(next_ch)
|| is_tag_extend(next_ch)
|| next_ch == '\u{20E3}'
{
end += next_ch.len_utf8();
continue;
}
break;
}
Some((&input[..end], &input[end..]))
}
#[must_use]
pub fn grapheme_display_width(cluster: &str) -> u8 {
let mut iter: Chars<'_> = cluster.chars();
let Some(first) = iter.next() else {
return 0;
};
let mut has_zwj: bool = false;
let mut has_emoji_vs: bool = false;
let mut has_text_vs: bool = false;
let mut has_keycap: bool = false;
let mut has_skin_mod: bool = false;
let mut regional_count: u8 = if is_regional_indicator(first) { 1 } else { 0 };
for ch in iter {
if ch == '\u{200D}' {
has_zwj = true;
} else if ch == '\u{FE0F}' {
has_emoji_vs = true;
} else if ch == '\u{FE0E}' {
has_text_vs = true;
} else if ch == '\u{20E3}' {
has_keycap = true;
} else if is_emoji_modifier(ch) {
has_skin_mod = true;
} else if is_regional_indicator(ch) {
regional_count = regional_count.saturating_add(1);
}
}
if regional_count >= 2 || has_zwj {
return 2;
}
if has_keycap || has_skin_mod {
return 2;
}
if has_emoji_vs && !has_text_vs {
return 2;
}
let base_w: u8 = terminal_char_width(first);
if has_text_vs && base_w == 2 && !is_cjk_ideograph(first) {
return 1;
}
base_w
}
#[must_use]
const fn is_cjk_ideograph(ch: char) -> bool {
let code: u32 = ch as u32;
matches!(
code,
0x1100..=0x115F
| 0x2E80..=0xA4CF
| 0xAC00..=0xD7A3
| 0xF900..=0xFAFF
| 0xFE10..=0xFE6F
| 0xFF01..=0xFF60
| 0xFFE0..=0xFFE6
| 0x20000..=0x3FFFD
)
}
#[must_use]
pub fn terminal_str_width(text: &str) -> usize {
let mut total: usize = 0;
let mut rest: &str = text;
while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
total = total.saturating_add(grapheme_display_width(cluster) as usize);
rest = next_rest;
}
total
}
#[must_use]
pub fn detect_stdout_is_tty() -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
io::stdout().is_terminal()
}
#[cfg(target_arch = "wasm32")]
{
false
}
}
#[must_use]
pub const fn resolve_cli_render_mode(
is_tty: bool,
force_ansi: Option<bool>,
no_color: bool,
term_is_dumb: bool,
) -> TerminalRenderMode {
match force_ansi {
Some(true) => TerminalRenderMode::InteractiveTui,
Some(false) => TerminalRenderMode::StaticPlainText,
None => {
if is_tty && !no_color && !term_is_dumb {
TerminalRenderMode::InteractiveTui
} else {
TerminalRenderMode::StaticPlainText
}
}
}
}
#[must_use]
pub fn render_static_plain_text(tree: &SceneTree, cols: u16, rows: u16) -> String {
let mut renderer: TerminalRenderer = TerminalRenderer::new();
let (plain, _): (String, TerminalDiffStats) =
renderer.render_tree(tree, cols, rows, TerminalRenderMode::StaticPlainText);
plain
}
#[cfg(not(target_arch = "wasm32"))]
pub fn write_cli_streams<WOut, WErr>(
tree: &SceneTree,
cols: u16,
rows: u16,
diagnostic: Option<&str>,
stdout: &mut WOut,
stderr: &mut WErr,
) -> CliWriteStatus
where
WOut: Write,
WErr: Write,
{
let plain: String = render_static_plain_text(tree, cols, rows);
if let Err(err) = stdout.write_all(plain.as_bytes()) {
return classify_io_error(&err);
}
if !plain.is_empty()
&& !plain.ends_with('\n')
&& let Err(err) = stdout.write_all(TERMINAL_NEWLINE_BYTES)
{
return classify_io_error(&err);
}
if let Err(err) = stdout.flush() {
return classify_io_error(&err);
}
if let Some(diag) = diagnostic
&& !diag.is_empty()
{
let _: io::Result<()> = stderr.write_all(diag.as_bytes());
if !diag.ends_with('\n') {
let _: io::Result<()> = stderr.write_all(TERMINAL_NEWLINE_BYTES);
}
let _: io::Result<()> = stderr.flush();
}
CliWriteStatus::Written
}
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
pub(crate) fn classify_io_error(err: &io::Error) -> CliWriteStatus {
if err.kind() == io::ErrorKind::BrokenPipe {
CliWriteStatus::BrokenPipe
} else {
CliWriteStatus::IoError
}
}
pub(crate) fn append_u32_ascii(out: &mut String, mut val: u32) {
let mut digits: [u8; 10] = [0; 10];
let mut idx: usize = 10;
if val == 0 {
out.push('0');
return;
}
while val > 0 {
idx -= 1;
digits[idx] = TERMINAL_ASCII_ZERO + ((val % 10) as u8);
val /= 10;
}
if let Ok(text) = from_utf8(&digits[idx..10]) {
out.push_str(text);
}
}
pub(crate) fn append_u8_ascii(out: &mut String, val: u8) {
if val >= 100 {
out.push((TERMINAL_ASCII_ZERO + (val / 100)) as char);
out.push((TERMINAL_ASCII_ZERO + ((val / 10) % 10)) as char);
out.push((TERMINAL_ASCII_ZERO + (val % 10)) as char);
} else if val >= 10 {
out.push((TERMINAL_ASCII_ZERO + (val / 10)) as char);
out.push((TERMINAL_ASCII_ZERO + (val % 10)) as char);
} else {
out.push((TERMINAL_ASCII_ZERO + val) as char);
}
}
pub(crate) fn append_cursor_move(out: &mut String, col: u16, row: u16) {
if col == 0 && row == 0 {
out.push_str(ANSI_CURSOR_HOME);
return;
}
out.push_str(ANSI_CSI_PREFIX);
append_u32_ascii(out, (row as u32) + 1);
out.push(';');
append_u32_ascii(out, (col as u32) + 1);
out.push('H');
}
pub(crate) fn append_cursor_move_smart(
out: &mut String,
cursor_pos: Option<(u16, u16)>,
col: u16,
row: u16,
) {
if cursor_pos == Some((col, row)) {
return;
}
if col == 0 && row == 0 {
out.push_str(ANSI_CURSOR_HOME);
return;
}
if let Some((cur_col, cur_row)) = cursor_pos
&& cur_row == row
&& col > cur_col
{
let delta: u16 = col - cur_col;
if delta == 1 {
out.push_str(ANSI_CURSOR_RIGHT_ONE);
return;
}
out.push_str(ANSI_CSI_PREFIX);
append_u32_ascii(out, delta as u32);
out.push('C');
return;
}
append_cursor_move(out, col, row);
}
pub(crate) fn append_sgr_style(
out: &mut String,
fg: Option<Color>,
bg: Option<Color>,
bold: bool,
reverse: bool,
underline: bool,
) {
out.push_str(ANSI_CSI_PREFIX);
out.push('0');
if bold {
out.push_str(ANSI_BOLD_CODE);
}
if reverse {
out.push_str(ANSI_REVERSE_CODE);
}
if underline {
out.push_str(ANSI_UNDERLINE_CODE);
}
if let Some(color) = fg {
out.push_str(ANSI_FG_TRUECOLOR_PREFIX);
append_u8_ascii(out, color.get_r());
out.push(';');
append_u8_ascii(out, color.get_g());
out.push(';');
append_u8_ascii(out, color.get_b());
}
if let Some(color) = bg {
out.push_str(ANSI_BG_TRUECOLOR_PREFIX);
append_u8_ascii(out, color.get_r());
out.push(';');
append_u8_ascii(out, color.get_g());
out.push(';');
append_u8_ascii(out, color.get_b());
}
out.push('m');
}
pub(crate) fn append_sgr_delta(
out: &mut String,
prev_style: Option<TerminalCell>,
next: &TerminalCell,
) {
let Some(prev) = prev_style else {
append_sgr_style(
out,
next.fg_color(),
next.bg_color(),
next.get_bold(),
next.get_reverse(),
next.get_underline(),
);
return;
};
if prev.same_style(next) {
return;
}
let needs_reset: bool = (prev.get_bold() && !next.get_bold())
|| (prev.get_reverse() && !next.get_reverse())
|| (prev.get_underline() && !next.get_underline())
|| (prev.fg_color().is_some() && next.fg_color().is_none())
|| (prev.bg_color().is_some() && next.bg_color().is_none());
if needs_reset {
append_sgr_style(
out,
next.fg_color(),
next.bg_color(),
next.get_bold(),
next.get_reverse(),
next.get_underline(),
);
return;
}
out.push_str(ANSI_CSI_PREFIX);
let mut emitted: bool = false;
if next.get_bold() && !prev.get_bold() {
out.push('1');
emitted = true;
}
if next.get_reverse() && !prev.get_reverse() {
if emitted {
out.push(';');
}
out.push('7');
emitted = true;
}
if next.get_underline() && !prev.get_underline() {
if emitted {
out.push(';');
}
out.push('4');
emitted = true;
}
if let Some(fg) = next.fg_color()
&& prev.fg_color() != Some(fg)
{
if emitted {
out.push(';');
}
out.push_str(ANSI_FG_TRUECOLOR_HEAD);
append_u8_ascii(out, fg.get_r());
out.push(';');
append_u8_ascii(out, fg.get_g());
out.push(';');
append_u8_ascii(out, fg.get_b());
emitted = true;
}
if let Some(bg) = next.bg_color()
&& prev.bg_color() != Some(bg)
{
if emitted {
out.push(';');
}
out.push_str(ANSI_BG_TRUECOLOR_HEAD);
append_u8_ascii(out, bg.get_r());
out.push(';');
append_u8_ascii(out, bg.get_g());
out.push(';');
append_u8_ascii(out, bg.get_b());
}
out.push('m');
}
#[must_use]
pub(crate) const fn fnv1a_mix_u64(mut hash: u64, value: u64) -> u64 {
let bytes: [u8; 8] = value.to_le_bytes();
let mut idx: usize = 0;
while idx < 8 {
hash ^= bytes[idx] as u64;
hash = hash.wrapping_mul(TERMINAL_FNV_PRIME);
idx += 1;
}
hash
}
#[must_use]
pub(crate) fn hash_terminal_row(cells: &[TerminalCell]) -> u64 {
let mut hash: u64 = TERMINAL_FNV_OFFSET_BASIS;
for cell in cells.iter() {
let fg_bits: u64 = match cell.fg_color() {
Some(c) => {
0x0100_0000_u64
| ((c.get_r() as u64) << 16)
| ((c.get_g() as u64) << 8)
| (c.get_b() as u64)
}
None => 0,
};
let bg_bits: u64 = match cell.bg_color() {
Some(c) => {
0x0100_0000_u64
| ((c.get_r() as u64) << 16)
| ((c.get_g() as u64) << 8)
| (c.get_b() as u64)
}
None => 0,
};
let color_bits: u64 = fg_bits | (bg_bits << 32);
let style_bits: u64 = ((cell.get_ch() as u64) << 16)
| ((cell.get_width() as u64) << 8)
| ((cell.get_tail_len() as u64) << 3)
| (if cell.get_bold() { 1 } else { 0 })
| (if cell.get_reverse() { 2 } else { 0 })
| (if cell.get_underline() { 4 } else { 0 });
hash = (hash ^ style_bits).wrapping_mul(TERMINAL_FNV_PRIME);
hash = (hash ^ color_bits).wrapping_mul(TERMINAL_FNV_PRIME);
let tail_len: usize = cell.get_tail_len() as usize;
if tail_len > 0 {
let tail: &[u8] = cell.tail_bytes();
for byte in tail.iter().copied() {
hash ^= byte as u64;
hash = hash.wrapping_mul(TERMINAL_FNV_PRIME);
}
}
}
hash
}