1#[cfg(windows)]
2mod windows_console {
3 use std::os::windows::io::AsRawHandle;
4 use std::os::windows::io::RawHandle;
5
6 use windows_sys::Win32::System::Console::CONSOLE_MODE;
7 use windows_sys::Win32::System::Console::ENABLE_VIRTUAL_TERMINAL_PROCESSING;
8
9 fn enable_vt(handle: RawHandle) -> std::io::Result<()> {
10 unsafe {
11 let handle = std::mem::transmute(handle);
12 if handle == 0 {
13 return Err(std::io::Error::new(
14 std::io::ErrorKind::BrokenPipe,
15 "console is detached",
16 ));
17 }
18
19 let mut dwmode: CONSOLE_MODE = 0;
20 if windows_sys::Win32::System::Console::GetConsoleMode(handle, &mut dwmode) == 0 {
21 return Err(std::io::Error::last_os_error());
22 }
23
24 dwmode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
25 if windows_sys::Win32::System::Console::SetConsoleMode(handle, dwmode) == 0 {
26 return Err(std::io::Error::last_os_error());
27 }
28
29 Ok(())
30 }
31 }
32
33 fn enable_ansi_colors_raw() -> std::io::Result<()> {
34 let stdout = std::io::stdout();
35 let stdout_handle = stdout.as_raw_handle();
36 let stderr = std::io::stderr();
37 let stderr_handle = stderr.as_raw_handle();
38
39 enable_vt(stdout_handle)?;
40 if stdout_handle != stderr_handle {
41 enable_vt(stderr_handle)?;
42 }
43
44 Ok(())
45 }
46
47 #[inline]
48 pub fn enable_ansi_colors() -> Option<bool> {
49 Some(enable_ansi_colors_raw().map(|_| true).unwrap_or(false))
50 }
51}
52
53#[cfg(not(windows))]
54mod windows_console {
55 #[inline]
56 pub fn enable_ansi_colors() -> Option<bool> {
57 None
58 }
59}
60
61pub use self::windows_console::enable_ansi_colors;
62