| 1 |
use std::sync::atomic::{AtomicBool, Ordering}; |
| 2 |
|
| 3 |
use crossterm_winapi::{ConsoleMode, Handle}; |
| 4 |
use parking_lot::Once; |
| 5 |
use winapi::um::wincon::ENABLE_VIRTUAL_TERMINAL_PROCESSING; |
| 6 |
|
| 7 |
/// Enable virtual terminal processing. |
| 8 |
/// |
| 9 |
/// This method attempts to enable virtual terminal processing for this |
| 10 |
/// console. If there was a problem enabling it, then an error returned. |
| 11 |
/// On success, the caller may assume that enabling it was successful. |
| 12 |
/// |
| 13 |
/// When virtual terminal processing is enabled, characters emitted to the |
| 14 |
/// console are parsed for VT100 and similar control character sequences |
| 15 |
/// that control color and other similar operations. |
| 16 |
fn enable_vt_processing() -> std::io::Result<()> { |
| 17 |
let mask = ENABLE_VIRTUAL_TERMINAL_PROCESSING; |
| 18 |
|
| 19 |
let console_mode = ConsoleMode::from(Handle::current_out_handle()?); |
| 20 |
let old_mode = console_mode.mode()?; |
| 21 |
|
| 22 |
if old_mode & mask == 0 { |
| 23 |
console_mode.set_mode(old_mode | mask)?; |
| 24 |
} |
| 25 |
|
| 26 |
Ok(()) |
| 27 |
} |
| 28 |
|
| 29 |
static SUPPORTS_ANSI_ESCAPE_CODES: AtomicBool = AtomicBool::new(false); |
| 30 |
static INITIALIZER: Once = Once::new(); |
| 31 |
|
| 32 |
/// Checks if the current terminal supports ANSI escape sequences |
| 33 |
pub fn supports_ansi() -> bool { |
| 34 |
INITIALIZER.call_once(|| { |
| 35 |
// Some terminals on Windows like GitBash can't use WinAPI calls directly |
| 36 |
// so when we try to enable the ANSI-flag for Windows this won't work. |
| 37 |
// Because of that we should check first if the TERM-variable is set |
| 38 |
// and see if the current terminal is a terminal who does support ANSI. |
| 39 |
let supported = enable_vt_processing().is_ok() |
| 40 |
|| std::env::var("TERM").map_or(false, |term| term != "dumb"); |
| 41 |
|
| 42 |
SUPPORTS_ANSI_ESCAPE_CODES.store(supported, Ordering::SeqCst); |
| 43 |
}); |
| 44 |
|
| 45 |
SUPPORTS_ANSI_ESCAPE_CODES.load(Ordering::SeqCst) |
| 46 |
} |