1 //! Windows console handling
3 // FIXME (#13400): this is only a tiny fraction of the Windows console api
6 use std::io::prelude::*;
11 /// A Terminal implementation that uses the Win32 Console API.
12 pub(crate) struct WinConsole<T> {
14 def_foreground: color::Color,
15 def_background: color::Color,
16 foreground: color::Color,
17 background: color::Color,
24 type HANDLE = *mut u8;
26 #[allow(non_snake_case)]
35 #[allow(non_snake_case)]
42 #[allow(non_snake_case)]
44 struct CONSOLE_SCREEN_BUFFER_INFO {
46 dwCursorPosition: COORD,
49 dwMaximumWindowSize: COORD,
52 #[allow(non_snake_case)]
53 #[link(name = "kernel32")]
55 fn SetConsoleTextAttribute(handle: HANDLE, attr: WORD) -> BOOL;
56 fn GetStdHandle(which: DWORD) -> HANDLE;
57 fn GetConsoleScreenBufferInfo(handle: HANDLE, info: *mut CONSOLE_SCREEN_BUFFER_INFO) -> BOOL;
60 fn color_to_bits(color: color::Color) -> u16 {
61 // magic numbers from mingw-w64's wincon.h
63 let bits = match color % 8 {
68 color::YELLOW => 0x2 | 0x4,
69 color::MAGENTA => 0x1 | 0x4,
70 color::CYAN => 0x1 | 0x2,
71 color::WHITE => 0x1 | 0x2 | 0x4,
75 if color >= 8 { bits | 0x8 } else { bits }
78 fn bits_to_color(bits: u16) -> color::Color {
79 let color = match bits & 0x7 {
85 0x5 => color::MAGENTA,
91 color | (u32::from(bits) & 0x8) // copy the hi-intensity bit
94 impl<T: Write + Send + 'static> WinConsole<T> {
96 let _unused = self.buf.flush();
97 let mut accum: WORD = 0;
98 accum |= color_to_bits(self.foreground);
99 accum |= color_to_bits(self.background) << 4;
102 // Magic -11 means stdout, from
103 // https://docs.microsoft.com/en-us/windows/console/getstdhandle
105 // You may be wondering, "but what about stderr?", and the answer
106 // to that is that setting terminal attributes on the stdout
107 // handle also sets them for stderr, since they go to the same
108 // terminal! Admittedly, this is fragile, since stderr could be
109 // redirected to a different console. This is good enough for
110 // rustc though. See #13400.
111 let out = GetStdHandle(-11i32 as DWORD);
112 SetConsoleTextAttribute(out, accum);
116 pub(crate) fn new(out: T) -> WinConsole<T> {
117 use std::mem::MaybeUninit;
122 let mut buffer_info = MaybeUninit::<CONSOLE_SCREEN_BUFFER_INFO>::uninit();
123 if GetConsoleScreenBufferInfo(GetStdHandle(-11i32 as DWORD), buffer_info.as_mut_ptr())
126 let buffer_info = buffer_info.assume_init();
127 fg = bits_to_color(buffer_info.wAttributes);
128 bg = bits_to_color(buffer_info.wAttributes >> 4);
144 impl<T: Write> Write for WinConsole<T> {
145 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
149 fn flush(&mut self) -> io::Result<()> {
154 impl<T: Write + Send + 'static> Terminal for WinConsole<T> {
155 fn fg(&mut self, color: color::Color) -> io::Result<bool> {
156 self.foreground = color;
162 fn reset(&mut self) -> io::Result<bool> {
163 self.foreground = self.def_foreground;
164 self.background = self.def_background;