Debian Codegraph @

src/style/sys/windows.rs

raw
1 use std::convert::TryFrom;
2 use std::sync::atomic::{AtomicU32, Ordering};
3
4 use crossterm_winapi::{Console, Handle, HandleType, ScreenBuffer};
5 use winapi::um::wincon;
6
7 use super::super::{Color, Colored};
8
9 const FG_GREEN: u16 = wincon::FOREGROUND_GREEN;
10 const FG_RED: u16 = wincon::FOREGROUND_RED;
11 const FG_BLUE: u16 = wincon::FOREGROUND_BLUE;
12 const FG_INTENSITY: u16 = wincon::FOREGROUND_INTENSITY;
13
14 const BG_GREEN: u16 = wincon::BACKGROUND_GREEN;
15 const BG_RED: u16 = wincon::BACKGROUND_RED;
16 const BG_BLUE: u16 = wincon::BACKGROUND_BLUE;
17 const BG_INTENSITY: u16 = wincon::BACKGROUND_INTENSITY;
18
19 pub(crate) fn set_foreground_color(fg_color: Color) -> std::io::Result<()> {
20 init_console_color()?;
21
22 let color_value: u16 = Colored::ForegroundColor(fg_color).into();
23
24 let screen_buffer = ScreenBuffer::current()?;
25 let csbi = screen_buffer.info()?;
26
27 // Notice that the color values are stored in wAttribute.
28 // So we need to use bitwise operators to check if the values exists or to get current console colors.
29 let attrs = csbi.attributes();
30 let bg_color = attrs & 0x0070;
31 let mut color = color_value | bg_color;
32
33 // background intensity is a separate value in attrs,
34 // we need to check if this was applied to the current bg color.
35 if (attrs & wincon::BACKGROUND_INTENSITY) != 0 {
36 color |= wincon::BACKGROUND_INTENSITY;
37 }
38
39 Console::from(screen_buffer.handle().clone()).set_text_attribute(color)?;
40 Ok(())
41 }
42
43 pub(crate) fn set_background_color(bg_color: Color) -> std::io::Result<()> {
44 init_console_color()?;
45
46 let color_value: u16 = Colored::BackgroundColor(bg_color).into();
47
48 let screen_buffer = ScreenBuffer::current()?;
49 let csbi = screen_buffer.info()?;
50
51 // Notice that the color values are stored in wAttribute.
52 // So we need to use bitwise operators to check if the values exists or to get current console colors.
53 let attrs = csbi.attributes();
54 let fg_color = attrs & 0x0007;
55 let mut color = fg_color | color_value;
56
57 // Foreground intensity is a separate value in attrs,
58 // So we need to check if this was applied to the current fg color.
59 if (attrs & wincon::FOREGROUND_INTENSITY) != 0 {
60 color |= wincon::FOREGROUND_INTENSITY;
61 }
62
63 Console::from(screen_buffer.handle().clone()).set_text_attribute(color)?;
64 Ok(())
65 }
66
67 pub(crate) fn reset() -> std::io::Result<()> {
68 if let Ok(original_color) = u16::try_from(ORIGINAL_CONSOLE_COLOR.load(Ordering::Relaxed)) {
69 Console::from(Handle::new(HandleType::CurrentOutputHandle)?)
70 .set_text_attribute(original_color)?;
71 }
72
73 Ok(())
74 }
75
76 /// Initializes the default console color. It will will be skipped if it has already been initialized.
77 pub(crate) fn init_console_color() -> std::io::Result<()> {
78 if ORIGINAL_CONSOLE_COLOR.load(Ordering::Relaxed) == u32::MAX {
79 let screen_buffer = ScreenBuffer::current()?;
80 let attr = screen_buffer.info()?.attributes();
81 ORIGINAL_CONSOLE_COLOR.store(u32::from(attr), Ordering::Relaxed);
82 }
83
84 Ok(())
85 }
86
87 /// Returns the original console color, make sure to call `init_console_color` before calling this function. Otherwise this function will panic.
88 pub(crate) fn original_console_color() -> u16 {
89 u16::try_from(ORIGINAL_CONSOLE_COLOR.load(Ordering::Relaxed))
90 // safe unwrap, initial console color was set with `init_console_color` in `WinApiColor::new()`
91 .expect("Initial console color not set")
92 }
93
94 // This is either a valid u16 in which case it stores the original console color or it is u32::MAX
95 // in which case it is uninitialized.
96 static ORIGINAL_CONSOLE_COLOR: AtomicU32 = AtomicU32::new(u32::MAX);
97
98 impl From<Colored> for u16 {
99 /// Returns the WinAPI color value (u16) from the `Colored` struct.
100 fn from(colored: Colored) -> Self {
101 match colored {
102 Colored::ForegroundColor(color) => {
103 match color {
104 Color::Black => 0,
105 Color::DarkGrey => FG_INTENSITY,
106 Color::Red => FG_INTENSITY | FG_RED,
107 Color::DarkRed => FG_RED,
108 Color::Green => FG_INTENSITY | FG_GREEN,
109 Color::DarkGreen => FG_GREEN,
110 Color::Yellow => FG_INTENSITY | FG_GREEN | FG_RED,
111 Color::DarkYellow => FG_GREEN | FG_RED,
112 Color::Blue => FG_INTENSITY | FG_BLUE,
113 Color::DarkBlue => FG_BLUE,
114 Color::Magenta => FG_INTENSITY | FG_RED | FG_BLUE,
115 Color::DarkMagenta => FG_RED | FG_BLUE,
116 Color::Cyan => FG_INTENSITY | FG_GREEN | FG_BLUE,
117 Color::DarkCyan => FG_GREEN | FG_BLUE,
118 Color::White => FG_INTENSITY | FG_RED | FG_GREEN | FG_BLUE,
119 Color::Grey => FG_RED | FG_GREEN | FG_BLUE,
120
121 Color::Reset => {
122 // safe unwrap, initial console color was set with `init_console_color`.
123 let original_color = original_console_color();
124
125 const REMOVE_BG_MASK: u16 = BG_INTENSITY | BG_RED | BG_GREEN | BG_BLUE;
126 // remove all background values from the original color, we don't want to reset those.
127
128 original_color & !REMOVE_BG_MASK
129 }
130
131 /* WinAPI will be used for systems that do not support ANSI, those are windows version less then 10. RGB and 255 (AnsiBValue) colors are not supported in that case.*/
132 Color::Rgb { .. } => 0,
133 Color::AnsiValue(_val) => 0,
134 }
135 }
136 Colored::BackgroundColor(color) => {
137 match color {
138 Color::Black => 0,
139 Color::DarkGrey => BG_INTENSITY,
140 Color::Red => BG_INTENSITY | BG_RED,
141 Color::DarkRed => BG_RED,
142 Color::Green => BG_INTENSITY | BG_GREEN,
143 Color::DarkGreen => BG_GREEN,
144 Color::Yellow => BG_INTENSITY | BG_GREEN | BG_RED,
145 Color::DarkYellow => BG_GREEN | BG_RED,
146 Color::Blue => BG_INTENSITY | BG_BLUE,
147 Color::DarkBlue => BG_BLUE,
148 Color::Magenta => BG_INTENSITY | BG_RED | BG_BLUE,
149 Color::DarkMagenta => BG_RED | BG_BLUE,
150 Color::Cyan => BG_INTENSITY | BG_GREEN | BG_BLUE,
151 Color::DarkCyan => BG_GREEN | BG_BLUE,
152 Color::White => BG_INTENSITY | BG_RED | BG_GREEN | BG_BLUE,
153 Color::Grey => BG_RED | BG_GREEN | BG_BLUE,
154
155 Color::Reset => {
156 let original_color = original_console_color();
157
158 const REMOVE_FG_MASK: u16 = FG_INTENSITY | FG_RED | FG_GREEN | FG_BLUE;
159 // remove all foreground values from the original color, we don't want to reset those.
160
161 original_color & !REMOVE_FG_MASK
162 }
163 /* WinAPI will be used for systems that do not support ANSI, those are windows version less then 10. RGB and 255 (AnsiBValue) colors are not supported in that case.*/
164 Color::Rgb { .. } => 0,
165 Color::AnsiValue(_val) => 0,
166 }
167 }
168 Colored::UnderlineColor(_) => 0,
169 }
170 }
171 }
172
173 #[cfg(test)]
174 mod tests {
175 use std::sync::atomic::Ordering;
176
177 use crate::style::sys::windows::set_foreground_color;
178
179 use super::{
180 Color, Colored, BG_INTENSITY, BG_RED, FG_INTENSITY, FG_RED, ORIGINAL_CONSOLE_COLOR,
181 };
182
183 #[test]
184 fn test_parse_fg_color() {
185 let colored = Colored::ForegroundColor(Color::Red);
186 assert_eq!(Into::<u16>::into(colored), FG_INTENSITY | FG_RED);
187 }
188
189 #[test]
190 fn test_parse_bg_color() {
191 let colored = Colored::BackgroundColor(Color::Red);
192 assert_eq!(Into::<u16>::into(colored), BG_INTENSITY | BG_RED);
193 }
194
195 #[test]
196 fn test_original_console_color_is_set() {
197 assert_eq!(ORIGINAL_CONSOLE_COLOR.load(Ordering::Relaxed), u32::MAX);
198
199 // will call `init_console_color`
200 set_foreground_color(Color::Blue).unwrap();
201
202 assert_ne!(ORIGINAL_CONSOLE_COLOR.load(Ordering::Relaxed), u32::MAX);
203 }
204 }