1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
//! Low-level wincon-styling

use std::os::windows::io::AsHandle;
use std::os::windows::io::AsRawHandle;

type StdioColorResult = std::io::Result<(anstyle::AnsiColor, anstyle::AnsiColor)>;
type StdioColorInnerResult = Result<(anstyle::AnsiColor, anstyle::AnsiColor), inner::IoError>;

/// Cached [`get_colors`] call for [`std::io::stdout`]
pub fn stdout_initial_colors() -> StdioColorResult {
    static INITIAL: std::sync::OnceLock<StdioColorInnerResult> = std::sync::OnceLock::new();
    INITIAL
        .get_or_init(|| get_colors_(&std::io::stdout()))
        .clone()
        .map_err(Into::into)
}

/// Cached [`get_colors`] call for [`std::io::stderr`]
pub fn stderr_initial_colors() -> StdioColorResult {
    static INITIAL: std::sync::OnceLock<StdioColorInnerResult> = std::sync::OnceLock::new();
    INITIAL
        .get_or_init(|| get_colors_(&std::io::stderr()))
        .clone()
        .map_err(Into::into)
}

/// Apply colors to future writes
///
/// **Note:** Make sure any buffers are first flushed or else these colors will apply
pub fn set_colors<S: AsHandle>(
    stream: &mut S,
    fg: anstyle::AnsiColor,
    bg: anstyle::AnsiColor,
) -> std::io::Result<()> {
    set_colors_(stream, fg, bg).map_err(Into::into)
}

fn set_colors_<S: AsHandle>(
    stream: &mut S,
    fg: anstyle::AnsiColor,
    bg: anstyle::AnsiColor,
) -> Result<(), inner::IoError> {
    let handle = stream.as_handle();
    let handle = handle.as_raw_handle();
    let attributes = inner::set_colors(fg, bg);
    inner::set_console_text_attributes(handle, attributes)
}

/// Get the colors currently active on the console
pub fn get_colors<S: AsHandle>(stream: &S) -> StdioColorResult {
    get_colors_(stream).map_err(Into::into)
}

fn get_colors_<S: AsHandle>(stream: &S) -> StdioColorInnerResult {
    let handle = stream.as_handle();
    let handle = handle.as_raw_handle();
    let info = inner::get_screen_buffer_info(handle)?;
    let (fg, bg) = inner::get_colors(&info);
    Ok((fg, bg))
}

pub(crate) fn write_colored<S: AsHandle + std::io::Write>(
    stream: &mut S,
    fg: Option<anstyle::AnsiColor>,
    bg: Option<anstyle::AnsiColor>,
    data: &[u8],
    initial: StdioColorResult,
) -> std::io::Result<usize> {
    let (initial_fg, initial_bg) = initial?;
    let non_default = fg.is_some() || bg.is_some();

    if non_default {
        let fg = fg.unwrap_or(initial_fg);
        let bg = bg.unwrap_or(initial_bg);
        // Ensure everything is written with the last set of colors before applying the next set
        stream.flush()?;
        set_colors(stream, fg, bg)?;
    }
    let written = stream.write(data)?;
    if non_default {
        // Ensure everything is written with the last set of colors before applying the next set
        stream.flush()?;
        set_colors(stream, initial_fg, initial_bg)?;
    }
    Ok(written)
}

mod inner {
    use windows_sys::Win32::System::Console::CONSOLE_CHARACTER_ATTRIBUTES;
    use windows_sys::Win32::System::Console::CONSOLE_SCREEN_BUFFER_INFO;
    use windows_sys::Win32::System::Console::FOREGROUND_BLUE;
    use windows_sys::Win32::System::Console::FOREGROUND_GREEN;
    use windows_sys::Win32::System::Console::FOREGROUND_INTENSITY;
    use windows_sys::Win32::System::Console::FOREGROUND_RED;

    use std::os::windows::io::RawHandle;

    const FOREGROUND_CYAN: CONSOLE_CHARACTER_ATTRIBUTES = FOREGROUND_BLUE | FOREGROUND_GREEN;
    const FOREGROUND_MAGENTA: CONSOLE_CHARACTER_ATTRIBUTES = FOREGROUND_BLUE | FOREGROUND_RED;
    const FOREGROUND_YELLOW: CONSOLE_CHARACTER_ATTRIBUTES = FOREGROUND_GREEN | FOREGROUND_RED;
    const FOREGROUND_WHITE: CONSOLE_CHARACTER_ATTRIBUTES =
        FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;

    #[derive(Copy, Clone, Debug)]
    pub(crate) enum IoError {
        BrokenPipe,
        RawOs(i32),
    }

    impl From<IoError> for std::io::Error {
        fn from(io: IoError) -> Self {
            match io {
                IoError::BrokenPipe => {
                    std::io::Error::new(std::io::ErrorKind::BrokenPipe, "console is detached")
                }
                IoError::RawOs(code) => std::io::Error::from_raw_os_error(code),
            }
        }
    }

    impl IoError {
        fn last_os_error() -> Self {
            Self::RawOs(std::io::Error::last_os_error().raw_os_error().unwrap())
        }
    }

    pub(crate) fn get_screen_buffer_info(
        handle: RawHandle,
    ) -> Result<CONSOLE_SCREEN_BUFFER_INFO, IoError> {
        unsafe {
            let handle = std::mem::transmute(handle);
            if handle == 0 {
                return Err(IoError::BrokenPipe);
            }

            let mut info: CONSOLE_SCREEN_BUFFER_INFO = std::mem::zeroed();
            if windows_sys::Win32::System::Console::GetConsoleScreenBufferInfo(handle, &mut info)
                != 0
            {
                Ok(info)
            } else {
                Err(IoError::last_os_error())
            }
        }
    }

    pub(crate) fn set_console_text_attributes(
        handle: RawHandle,
        attributes: CONSOLE_CHARACTER_ATTRIBUTES,
    ) -> Result<(), IoError> {
        unsafe {
            let handle = std::mem::transmute(handle);
            if handle == 0 {
                return Err(IoError::BrokenPipe);
            }

            if windows_sys::Win32::System::Console::SetConsoleTextAttribute(handle, attributes) != 0
            {
                Ok(())
            } else {
                Err(IoError::last_os_error())
            }
        }
    }

    pub(crate) fn get_colors(
        info: &CONSOLE_SCREEN_BUFFER_INFO,
    ) -> (anstyle::AnsiColor, anstyle::AnsiColor) {
        let attributes = info.wAttributes;
        let bg = from_nibble(attributes >> 4);
        let fg = from_nibble(attributes);
        (fg, bg)
    }

    pub(crate) fn set_colors(
        fg: anstyle::AnsiColor,
        bg: anstyle::AnsiColor,
    ) -> CONSOLE_CHARACTER_ATTRIBUTES {
        to_nibble(bg) << 4 | to_nibble(fg)
    }

    fn from_nibble(color: CONSOLE_CHARACTER_ATTRIBUTES) -> anstyle::AnsiColor {
        if color & FOREGROUND_WHITE == FOREGROUND_WHITE {
            // 3 bits high
            anstyle::AnsiColor::White
        } else if color & FOREGROUND_CYAN == FOREGROUND_CYAN {
            // 2 bits high
            anstyle::AnsiColor::Cyan
        } else if color & FOREGROUND_YELLOW == FOREGROUND_YELLOW {
            // 2 bits high
            anstyle::AnsiColor::Yellow
        } else if color & FOREGROUND_MAGENTA == FOREGROUND_MAGENTA {
            // 2 bits high
            anstyle::AnsiColor::Magenta
        } else if color & FOREGROUND_RED == FOREGROUND_RED {
            // 1 bit high
            anstyle::AnsiColor::Red
        } else if color & FOREGROUND_GREEN == FOREGROUND_GREEN {
            // 1 bit high
            anstyle::AnsiColor::Green
        } else if color & FOREGROUND_BLUE == FOREGROUND_BLUE {
            // 1 bit high
            anstyle::AnsiColor::Blue
        } else {
            // 0 bits high
            anstyle::AnsiColor::Black
        }
        .bright(color & FOREGROUND_INTENSITY == FOREGROUND_INTENSITY)
    }

    fn to_nibble(color: anstyle::AnsiColor) -> CONSOLE_CHARACTER_ATTRIBUTES {
        let mut attributes = 0;
        attributes |= match color.bright(false) {
            anstyle::AnsiColor::Black => 0,
            anstyle::AnsiColor::Red => FOREGROUND_RED,
            anstyle::AnsiColor::Green => FOREGROUND_GREEN,
            anstyle::AnsiColor::Yellow => FOREGROUND_YELLOW,
            anstyle::AnsiColor::Blue => FOREGROUND_BLUE,
            anstyle::AnsiColor::Magenta => FOREGROUND_MAGENTA,
            anstyle::AnsiColor::Cyan => FOREGROUND_CYAN,
            anstyle::AnsiColor::White => FOREGROUND_WHITE,
            anstyle::AnsiColor::BrightBlack
            | anstyle::AnsiColor::BrightRed
            | anstyle::AnsiColor::BrightGreen
            | anstyle::AnsiColor::BrightYellow
            | anstyle::AnsiColor::BrightBlue
            | anstyle::AnsiColor::BrightMagenta
            | anstyle::AnsiColor::BrightCyan
            | anstyle::AnsiColor::BrightWhite => unreachable!("brights were toggled off"),
        };
        if color.is_bright() {
            attributes |= FOREGROUND_INTENSITY;
        }
        attributes
    }

    #[test]
    fn to_from_nibble() {
        const COLORS: [anstyle::AnsiColor; 16] = [
            anstyle::AnsiColor::Black,
            anstyle::AnsiColor::Red,
            anstyle::AnsiColor::Green,
            anstyle::AnsiColor::Yellow,
            anstyle::AnsiColor::Blue,
            anstyle::AnsiColor::Magenta,
            anstyle::AnsiColor::Cyan,
            anstyle::AnsiColor::White,
            anstyle::AnsiColor::BrightBlack,
            anstyle::AnsiColor::BrightRed,
            anstyle::AnsiColor::BrightGreen,
            anstyle::AnsiColor::BrightYellow,
            anstyle::AnsiColor::BrightBlue,
            anstyle::AnsiColor::BrightMagenta,
            anstyle::AnsiColor::BrightCyan,
            anstyle::AnsiColor::BrightWhite,
        ];
        for expected in COLORS {
            let nibble = to_nibble(expected);
            let actual = from_nibble(nibble);
            assert_eq!(expected, actual, "Intermediate: {}", nibble);
        }
    }
}