1 //! # Output-VT100
2 //!
3 //! When you write terminal-based crates, sometimes you might want to use the
4 //! standard ANSI escaped characters, to display some colors, to display text
5 //! as bold, italic or whatever. However, you’ve just discovered all your
6 //! pretty displays that worked like a charm on Linux and Mac look terrible
7 //! on Windows, because the escaped characters do not work. Rather, they are
8 //! not activated by default. Then you discover you have to do system calls to
9 //! Windows directly to activate them in order to get your beautiful text back.
10 //! What a pain!
11 //! And this is where this crate comes in action! Simply add it as a dependency
12 //! for your own crate, and use it like this:
13 //! ```rust
14 //! extern crate output_vt100;
15 //!
16 //! fn main() {
17 //!     output_vt100::init();
18 //!     println!("\x1b[31mThis text is red!\x1b[0m");
19 //! }
20 //! ```
21 //! And that’s it! By calling it once, you have now activated PowerShell’s and
22 //! CMD’s support for ANSI’s escaped characters on your Windows builds! And
23 //! you can leave this line in your Unix builds too, it will simply do nothing.
24 
25 #[cfg(windows)]
try_init() -> Result<(), ()>26 pub fn try_init() -> Result<(), ()> {
27     use winapi::shared::minwindef::DWORD;
28     use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode};
29     use winapi::um::processenv::GetStdHandle;
30     use winapi::um::winbase::STD_OUTPUT_HANDLE;
31     use winapi::um::wincon::{DISABLE_NEWLINE_AUTO_RETURN, ENABLE_VIRTUAL_TERMINAL_PROCESSING};
32 
33     let console_out = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) };
34 
35     let mut state: DWORD = 0;
36     let mut ret: Result<(), _> = Ok(());
37     unsafe {
38         let mut e: DWORD = 0;
39         if GetConsoleMode(console_out, &mut state) == 0 {
40             ret = Err(());
41         }
42         if ret.is_ok() {
43             state |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
44             state &= !DISABLE_NEWLINE_AUTO_RETURN;
45             if SetConsoleMode(console_out, state) == 0 {
46                 ret = Err(());
47             }
48         }
49     }
50     return ret;
51 }
52 
53 #[cfg(windows)]
init()54 pub fn init() {
55     assert_eq!(try_init().is_ok(), true);
56 }
57 
58 #[cfg(not(windows))]
try_init() -> Result<(), ()>59 pub fn try_init() -> Result<(), ()> {
60     Ok(())
61 }
62 
63 #[cfg(not(windows))]
init()64 pub fn init() {
65     ;
66 }
67 
68 #[cfg(test)]
69 mod tests {
70     #[test]
activate_vt100()71     fn activate_vt100() {
72         crate::init();
73     }
74 }
75