fix: set terminal code page to UTF-8 on Windows

This commit is contained in:
sxyazi 2025-03-09 19:08:01 +08:00
parent 119cc9c2a1
commit 22980cf000
No known key found for this signature in database
2 changed files with 11 additions and 1 deletions

View file

@ -28,7 +28,7 @@ libc = { workspace = true }
uzers = { workspace = true }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.59.0", features = [ "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Threading", "Win32_UI_Shell" ] }
windows-sys = { version = "0.59.0", features = [ "Win32_Globalization", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_IO", "Win32_System_Threading", "Win32_UI_Shell" ] }
[target.'cfg(target_os = "macos")'.dependencies]
crossterm = { workspace = true, features = [ "use-dev-tty", "libc" ] }

View file

@ -11,6 +11,9 @@ pub struct Tty {
impl Default for Tty {
fn default() -> Self {
#[cfg(windows)]
Self::set_code_page().expect("failed to set terminal code page");
let stdin = Handle::new(false).expect("failed to open stdin");
let stdout = Handle::new(true).expect("failed to open stdout");
Self { stdin: Mutex::new(stdin), stdout: Mutex::new(BufWriter::new(stdout)) }
@ -55,6 +58,13 @@ impl Tty {
let result = read();
(buf, result)
}
#[cfg(windows)]
fn set_code_page() -> std::io::Result<()> {
use windows_sys::Win32::{Globalization::CP_UTF8, System::Console::SetConsoleOutputCP};
if unsafe { SetConsoleOutputCP(CP_UTF8) } == 0 { Err(Error::last_os_error()) } else { Ok(()) }
}
}
// --- Reader