use std::io::{self, Read, Write};
use std::time::Duration;
use crossterm::{ExecutableCommand, cursor, terminal};
pub fn probe_ambiguous_width() -> Option<u8> {
let was_raw = terminal::is_raw_mode_enabled().unwrap_or(false);
if !was_raw {
terminal::enable_raw_mode().ok()?;
}
let result = do_probe();
if !was_raw {
let _ = terminal::disable_raw_mode();
}
result
}
fn do_probe() -> Option<u8> {
let mut stdout = io::stdout();
let mut stdin = io::stdin();
stdout.execute(cursor::SavePosition).ok()?;
write!(stdout, "\x1b[999;1H").ok()?; write!(stdout, "\x1b[6n").ok()?; stdout.flush().ok()?;
let (base_row, _) = read_cursor_position(&mut stdin)?;
write!(stdout, "\x1b[{base_row};1H").ok()?; write!(stdout, "▒").ok()?; write!(stdout, "\x1b[6n").ok()?; stdout.flush().ok()?;
let (_, col_after) = read_cursor_position(&mut stdin)?;
write!(stdout, "\x1b[{base_row};1H").ok()?;
write!(stdout, " ").ok()?; stdout.execute(cursor::RestorePosition).ok()?;
stdout.flush().ok()?;
let width = (col_after - 1) as u8;
if width == 1 || width == 2 {
Some(width)
} else {
None
}
}
fn read_cursor_position(stdin: &mut impl Read) -> Option<(u16, u16)> {
let mut buf = [0u8; 32];
let mut idx = 0;
let deadline = std::time::Instant::now() + Duration::from_millis(500);
loop {
if std::time::Instant::now() > deadline {
return None;
}
if !crossterm::event::poll(Duration::from_millis(100)).ok()? {
continue;
}
let slot = buf.get_mut(idx..idx + 1)?;
let n = stdin.read(slot).ok()?;
if n == 0 {
continue;
}
if buf.get(idx).copied() == Some(b'R') {
break;
}
idx += 1;
if idx >= buf.len() {
return None;
}
}
let response = std::str::from_utf8(buf.get(..idx)?).ok()?;
let coords = response.strip_prefix("\x1b[")?;
let (row_str, col_str) = coords.split_once(';')?;
let row: u16 = row_str.parse().ok()?;
let col: u16 = col_str.parse().ok()?;
Some((row, col))
}
pub fn locale_ambiguous_width() -> u8 {
for var in &["LC_ALL", "LC_CTYPE", "LANG"] {
if let Ok(val) = std::env::var(var) {
let lower = val.to_ascii_lowercase();
if lower.starts_with("zh") || lower.starts_with("ja") || lower.starts_with("ko") {
return 2;
}
if !lower.is_empty() {
return 1;
}
}
}
1 }