| 1 | //! WinAPI related logic for terminal manipulation. |
| 2 | |
| 3 | use std::fmt::{self, Write}; |
| 4 | use std::io::{self}; |
| 5 | |
| 6 | use crossterm_winapi::{Console, ConsoleMode, Coord, Handle, ScreenBuffer, Size}; |
| 7 | use winapi::{ |
| 8 | shared::minwindef::DWORD, |
| 9 | um::wincon::{SetConsoleTitleW, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT}, |
| 10 | }; |
| 11 | |
| 12 | use crate::{ |
| 13 | cursor, |
| 14 | terminal::{ClearType, WindowSize}, |
| 15 | }; |
| 16 | |
| 17 | /// bits which can't be set in raw mode |
| 18 | const NOT_RAW_MODE_MASK: DWORD = ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT; |
| 19 | |
| 20 | pub(crate) fn is_raw_mode_enabled() -> std::io::Result<bool> { |
| 21 | let console_mode = ConsoleMode::from(Handle::current_in_handle()?); |
| 22 | |
| 23 | let dw_mode = console_mode.mode()?; |
| 24 | |
| 25 | Ok( |
| 26 | // check none of the "not raw" bits is set |
| 27 | dw_mode & NOT_RAW_MODE_MASK == 0, |
| 28 | ) |
| 29 | } |
| 30 | |
| 31 | pub(crate) fn enable_raw_mode() -> std::io::Result<()> { |
| 32 | let console_mode = ConsoleMode::from(Handle::current_in_handle()?); |
| 33 | |
| 34 | let dw_mode = console_mode.mode()?; |
| 35 | |
| 36 | let new_mode = dw_mode & !NOT_RAW_MODE_MASK; |
| 37 | |
| 38 | console_mode.set_mode(new_mode)?; |
| 39 | |
| 40 | Ok(()) |
| 41 | } |
| 42 | |
| 43 | pub(crate) fn disable_raw_mode() -> std::io::Result<()> { |
| 44 | let console_mode = ConsoleMode::from(Handle::current_in_handle()?); |
| 45 | |
| 46 | let dw_mode = console_mode.mode()?; |
| 47 | |
| 48 | let new_mode = dw_mode | NOT_RAW_MODE_MASK; |
| 49 | |
| 50 | console_mode.set_mode(new_mode)?; |
| 51 | |
| 52 | Ok(()) |
| 53 | } |
| 54 | |
| 55 | pub(crate) fn size() -> io::Result<(u16, u16)> { |
| 56 | let terminal_size = ScreenBuffer::current()?.info()?.terminal_size(); |
| 57 | // windows starts counting at 0, unix at 1, add one to replicated unix behaviour. |
| 58 | Ok(( |
| 59 | (terminal_size.width + 1) as u16, |
| 60 | (terminal_size.height + 1) as u16, |
| 61 | )) |
| 62 | } |
| 63 | |
| 64 | pub(crate) fn window_size() -> io::Result<WindowSize> { |
| 65 | Err(io::Error::new( |
| 66 | io::ErrorKind::Unsupported, |
| 67 | "Window pixel size not implemented for the Windows API.", |
| 68 | )) |
| 69 | } |
| 70 | |
| 71 | /// Queries the terminal's support for progressive keyboard enhancement. |
| 72 | /// |
| 73 | /// This always returns `Ok(false)` on Windows. |
| 74 | #[cfg(feature = "events")] |
| 75 | pub fn supports_keyboard_enhancement() -> std::io::Result<bool> { |
| 76 | Ok(false) |
| 77 | } |
| 78 | |
| 79 | pub(crate) fn clear(clear_type: ClearType) -> std::io::Result<()> { |
| 80 | let screen_buffer = ScreenBuffer::current()?; |
| 81 | let csbi = screen_buffer.info()?; |
| 82 | |
| 83 | let pos = csbi.cursor_pos(); |
| 84 | let buffer_size = csbi.buffer_size(); |
| 85 | let current_attribute = csbi.attributes(); |
| 86 | |
| 87 | match clear_type { |
| 88 | ClearType::All => { |
| 89 | clear_entire_screen(buffer_size, current_attribute)?; |
| 90 | } |
| 91 | ClearType::FromCursorDown => clear_after_cursor(pos, buffer_size, current_attribute)?, |
| 92 | ClearType::FromCursorUp => clear_before_cursor(pos, buffer_size, current_attribute)?, |
| 93 | ClearType::CurrentLine => clear_current_line(pos, buffer_size, current_attribute)?, |
| 94 | ClearType::UntilNewLine => clear_until_line(pos, buffer_size, current_attribute)?, |
| 95 | _ => { |
| 96 | clear_entire_screen(buffer_size, current_attribute)?; |
| 97 | } //TODO: make purge flush the entire screen buffer not just the visible window. |
| 98 | }; |
| 99 | Ok(()) |
| 100 | } |
| 101 | |
| 102 | pub(crate) fn scroll_up(row_count: u16) -> std::io::Result<()> { |
| 103 | let csbi = ScreenBuffer::current()?; |
| 104 | let mut window = csbi.info()?.terminal_window(); |
| 105 | |
| 106 | // check whether the window is too close to the screen buffer top |
| 107 | let count = row_count as i16; |
| 108 | if window.top >= count { |
| 109 | window.top -= count; // move top down |
| 110 | window.bottom -= count; // move bottom down |
| 111 | |
| 112 | Console::output()?.set_console_info(true, window)?; |
| 113 | } |
| 114 | Ok(()) |
| 115 | } |
| 116 | |
| 117 | pub(crate) fn scroll_down(row_count: u16) -> std::io::Result<()> { |
| 118 | let screen_buffer = ScreenBuffer::current()?; |
| 119 | let csbi = screen_buffer.info()?; |
| 120 | let mut window = csbi.terminal_window(); |
| 121 | let buffer_size = csbi.buffer_size(); |
| 122 | |
| 123 | // check whether the window is too close to the screen buffer top |
| 124 | let count = row_count as i16; |
| 125 | if window.bottom < buffer_size.height - count { |
| 126 | window.top += count; // move top down |
| 127 | window.bottom += count; // move bottom down |
| 128 | |
| 129 | Console::output()?.set_console_info(true, window)?; |
| 130 | } |
| 131 | Ok(()) |
| 132 | } |
| 133 | |
| 134 | pub(crate) fn set_size(width: u16, height: u16) -> std::io::Result<()> { |
| 135 | if width <= 1 { |
| 136 | return Err(io::Error::new( |
| 137 | io::ErrorKind::InvalidInput, |
| 138 | "terminal width must be at least 1", |
| 139 | )); |
| 140 | } |
| 141 | |
| 142 | if height <= 1 { |
| 143 | return Err(io::Error::new( |
| 144 | io::ErrorKind::InvalidInput, |
| 145 | "terminal height must be at least 1", |
| 146 | )); |
| 147 | } |
| 148 | |
| 149 | // get the position of the current console window |
| 150 | let screen_buffer = ScreenBuffer::current()?; |
| 151 | let console = Console::from(screen_buffer.handle().clone()); |
| 152 | let csbi = screen_buffer.info()?; |
| 153 | |
| 154 | let current_size = csbi.buffer_size(); |
| 155 | let window = csbi.terminal_window(); |
| 156 | |
| 157 | let mut new_size = Size::new(current_size.width, current_size.height); |
| 158 | |
| 159 | // If the buffer is smaller than this new window size, resize the |
| 160 | // buffer to be large enough. Include window position. |
| 161 | let mut resize_buffer = false; |
| 162 | |
| 163 | let width = width as i16; |
| 164 | if current_size.width < window.left + width { |
| 165 | if window.left >= i16::MAX - width { |
| 166 | return Err(io::Error::new( |
| 167 | io::ErrorKind::InvalidInput, |
| 168 | "terminal width too large", |
| 169 | )); |
| 170 | } |
| 171 | |
| 172 | new_size.width = window.left + width; |
| 173 | resize_buffer = true; |
| 174 | } |
| 175 | let height = height as i16; |
| 176 | if current_size.height < window.top + height { |
| 177 | if window.top >= i16::MAX - height { |
| 178 | return Err(io::Error::new( |
| 179 | io::ErrorKind::InvalidInput, |
| 180 | "terminal height too large", |
| 181 | )); |
| 182 | } |
| 183 | |
| 184 | new_size.height = window.top + height; |
| 185 | resize_buffer = true; |
| 186 | } |
| 187 | |
| 188 | if resize_buffer { |
| 189 | screen_buffer.set_size(new_size.width - 1, new_size.height - 1)?; |
| 190 | } |
| 191 | |
| 192 | let mut window = window; |
| 193 | |
| 194 | // preserve the position, but change the size. |
| 195 | window.bottom = window.top + height - 1; |
| 196 | window.right = window.left + width - 1; |
| 197 | console.set_console_info(true, window)?; |
| 198 | |
| 199 | // if we resized the buffer, un-resize it. |
| 200 | if resize_buffer { |
| 201 | screen_buffer.set_size(current_size.width - 1, current_size.height - 1)?; |
| 202 | } |
| 203 | |
| 204 | let bounds = console.largest_window_size()?; |
| 205 | |
| 206 | if width > bounds.x { |
| 207 | return Err(io::Error::new( |
| 208 | io::ErrorKind::InvalidInput, |
| 209 | format!("terminal width {width} too large"), |
| 210 | )); |
| 211 | } |
| 212 | if height > bounds.y { |
| 213 | return Err(io::Error::new( |
| 214 | io::ErrorKind::InvalidInput, |
| 215 | format!("terminal height {height} too large"), |
| 216 | )); |
| 217 | } |
| 218 | |
| 219 | Ok(()) |
| 220 | } |
| 221 | |
| 222 | pub(crate) fn set_window_title(title: impl fmt::Display) -> std::io::Result<()> { |
| 223 | struct Utf16Encoder(Vec<u16>); |
| 224 | impl Write for Utf16Encoder { |
| 225 | fn write_str(&mut self, s: &str) -> fmt::Result { |
| 226 | self.0.extend(s.encode_utf16()); |
| 227 | Ok(()) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | let mut title_utf16 = Utf16Encoder(Vec::new()); |
| 232 | write!(title_utf16, "{title}").expect("formatting failed"); |
| 233 | title_utf16.0.push(0); |
| 234 | let title = title_utf16.0; |
| 235 | |
| 236 | let result = unsafe { SetConsoleTitleW(title.as_ptr()) }; |
| 237 | if result != 0 { |
| 238 | Ok(()) |
| 239 | } else { |
| 240 | Err(io::Error::last_os_error()) |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | fn clear_after_cursor( |
| 245 | location: Coord, |
| 246 | buffer_size: Size, |
| 247 | current_attribute: u16, |
| 248 | ) -> std::io::Result<()> { |
| 249 | let (mut x, mut y) = (location.x, location.y); |
| 250 | |
| 251 | // if cursor position is at the outer right position |
| 252 | if x > buffer_size.width { |
| 253 | y += 1; |
| 254 | x = 0; |
| 255 | } |
| 256 | |
| 257 | // location where to start clearing |
| 258 | let start_location = Coord::new(x, y); |
| 259 | |
| 260 | // get sum cells before cursor |
| 261 | let cells_to_write = buffer_size.width as u32 * buffer_size.height as u32; |
| 262 | |
| 263 | clear_winapi(start_location, cells_to_write, current_attribute) |
| 264 | } |
| 265 | |
| 266 | fn clear_before_cursor( |
| 267 | location: Coord, |
| 268 | buffer_size: Size, |
| 269 | current_attribute: u16, |
| 270 | ) -> std::io::Result<()> { |
| 271 | let (xpos, ypos) = (location.x, location.y); |
| 272 | |
| 273 | // one cell after cursor position |
| 274 | let x = 0; |
| 275 | // one at row of cursor position |
| 276 | let y = 0; |
| 277 | |
| 278 | // location where to start clearing |
| 279 | let start_location = Coord::new(x, y); |
| 280 | |
| 281 | // get sum cells before cursor |
| 282 | let cells_to_write = (buffer_size.width as u32 * ypos as u32) + (xpos as u32 + 1); |
| 283 | |
| 284 | // clear everything before cursor position |
| 285 | clear_winapi(start_location, cells_to_write, current_attribute) |
| 286 | } |
| 287 | |
| 288 | fn clear_entire_screen(buffer_size: Size, current_attribute: u16) -> std::io::Result<()> { |
| 289 | // get sum cells before cursor |
| 290 | let cells_to_write = buffer_size.width as u32 * buffer_size.height as u32; |
| 291 | |
| 292 | // location where to start clearing |
| 293 | let start_location = Coord::new(0, 0); |
| 294 | |
| 295 | // clear the entire screen |
| 296 | clear_winapi(start_location, cells_to_write, current_attribute)?; |
| 297 | |
| 298 | // put the cursor back at cell 0,0 |
| 299 | cursor::sys::move_to(0, 0)?; |
| 300 | Ok(()) |
| 301 | } |
| 302 | |
| 303 | fn clear_current_line( |
| 304 | location: Coord, |
| 305 | buffer_size: Size, |
| 306 | current_attribute: u16, |
| 307 | ) -> std::io::Result<()> { |
| 308 | // location where to start clearing |
| 309 | let start_location = Coord::new(0, location.y); |
| 310 | |
| 311 | // get sum cells before cursor |
| 312 | let cells_to_write = buffer_size.width as u32; |
| 313 | |
| 314 | // clear the whole current line |
| 315 | clear_winapi(start_location, cells_to_write, current_attribute)?; |
| 316 | |
| 317 | // put the cursor back at cell 1 on current row |
| 318 | cursor::sys::move_to(0, location.y as u16)?; |
| 319 | Ok(()) |
| 320 | } |
| 321 | |
| 322 | fn clear_until_line( |
| 323 | location: Coord, |
| 324 | buffer_size: Size, |
| 325 | current_attribute: u16, |
| 326 | ) -> std::io::Result<()> { |
| 327 | let (x, y) = (location.x, location.y); |
| 328 | |
| 329 | // location where to start clearing |
| 330 | let start_location = Coord::new(x, y); |
| 331 | |
| 332 | // get sum cells before cursor |
| 333 | let cells_to_write = (buffer_size.width - x) as u32; |
| 334 | |
| 335 | // clear until the current line |
| 336 | clear_winapi(start_location, cells_to_write, current_attribute)?; |
| 337 | |
| 338 | // put the cursor back at original cursor position before we did the clearing |
| 339 | cursor::sys::move_to(x as u16, y as u16)?; |
| 340 | Ok(()) |
| 341 | } |
| 342 | |
| 343 | fn clear_winapi( |
| 344 | start_location: Coord, |
| 345 | cells_to_write: u32, |
| 346 | current_attribute: u16, |
| 347 | ) -> std::io::Result<()> { |
| 348 | let console = Console::from(Handle::current_out_handle()?); |
| 349 | console.fill_whit_character(start_location, cells_to_write, ' ')?; |
| 350 | console.fill_whit_attribute(start_location, cells_to_write, current_attribute)?; |
| 351 | Ok(()) |
| 352 | } |
| 353 | |
| 354 | #[cfg(test)] |
| 355 | // Create a new screen buffer to avoid changing the terminal the test |
| 356 | // is running within. |
| 357 | pub fn temp_screen_buffer() -> std::io::Result<ScreenBuffer> { |
| 358 | let alternate_screen = ScreenBuffer::create()?; |
| 359 | alternate_screen.show().unwrap(); |
| 360 | Ok(alternate_screen) |
| 361 | } |
| 362 | |
| 363 | #[cfg(test)] |
| 364 | mod tests { |
| 365 | use std::{ffi::OsString, os::windows::ffi::OsStringExt}; |
| 366 | |
| 367 | use crossterm_winapi::ScreenBuffer; |
| 368 | use serial_test::serial; |
| 369 | use winapi::um::wincon::GetConsoleTitleW; |
| 370 | |
| 371 | use super::{scroll_down, scroll_up, set_size, set_window_title, size, temp_screen_buffer}; |
| 372 | |
| 373 | #[test] |
| 374 | #[serial] |
| 375 | fn test_resize_winapi_20_21() { |
| 376 | let _test_screen = temp_screen_buffer().unwrap(); |
| 377 | |
| 378 | let (width, height) = size().unwrap(); |
| 379 | |
| 380 | // The values 20 and 21 are arbitrary and different from each other |
| 381 | // just to see they're not crossed over. |
| 382 | set_size(20, 21).unwrap(); |
| 383 | assert_eq!((20, 21), size().unwrap()); |
| 384 | |
| 385 | // reset to previous size |
| 386 | set_size(width, height).unwrap(); |
| 387 | assert_eq!((width, height), size().unwrap()); |
| 388 | } |
| 389 | |
| 390 | // This is similar to test_resize_winapi_20_21() above. This verifies that |
| 391 | // another test of similar functionality runs independently (that a testing |
| 392 | // race condition has been addressed). |
| 393 | #[test] |
| 394 | #[serial] |
| 395 | #[ignore] |
| 396 | fn test_resize_winapi_30_31() { |
| 397 | let _test_screen = temp_screen_buffer().unwrap(); |
| 398 | |
| 399 | let (width, height) = size().unwrap(); |
| 400 | |
| 401 | set_size(30, 31).unwrap(); |
| 402 | assert_eq!((30, 31), size().unwrap()); |
| 403 | |
| 404 | // reset to previous size |
| 405 | set_size(width, height).unwrap(); |
| 406 | assert_eq!((width, height), size().unwrap()); |
| 407 | } |
| 408 | |
| 409 | // Test is disabled, because it's failing on Travis CI |
| 410 | #[test] |
| 411 | #[ignore] |
| 412 | fn test_scroll_down_winapi() { |
| 413 | let current_window = ScreenBuffer::current() |
| 414 | .unwrap() |
| 415 | .info() |
| 416 | .unwrap() |
| 417 | .terminal_window(); |
| 418 | |
| 419 | scroll_down(2).unwrap(); |
| 420 | |
| 421 | let new_window = ScreenBuffer::current() |
| 422 | .unwrap() |
| 423 | .info() |
| 424 | .unwrap() |
| 425 | .terminal_window(); |
| 426 | |
| 427 | assert_eq!(new_window.top, current_window.top + 2); |
| 428 | assert_eq!(new_window.bottom, current_window.bottom + 2); |
| 429 | } |
| 430 | |
| 431 | // Test is disabled, because it's failing on Travis CI |
| 432 | #[test] |
| 433 | #[ignore] |
| 434 | fn test_scroll_up_winapi() { |
| 435 | // move the terminal buffer down before moving it up |
| 436 | test_scroll_down_winapi(); |
| 437 | |
| 438 | let current_window = ScreenBuffer::current() |
| 439 | .unwrap() |
| 440 | .info() |
| 441 | .unwrap() |
| 442 | .terminal_window(); |
| 443 | |
| 444 | scroll_up(2).unwrap(); |
| 445 | |
| 446 | let new_window = ScreenBuffer::current() |
| 447 | .unwrap() |
| 448 | .info() |
| 449 | .unwrap() |
| 450 | .terminal_window(); |
| 451 | |
| 452 | assert_eq!(new_window.top, current_window.top - 2); |
| 453 | assert_eq!(new_window.bottom, current_window.bottom - 2); |
| 454 | } |
| 455 | |
| 456 | #[test] |
| 457 | #[serial] |
| 458 | fn test_set_title_winapi() { |
| 459 | let _test_screen = temp_screen_buffer().unwrap(); |
| 460 | |
| 461 | let test_title = "this is a crossterm test title"; |
| 462 | set_window_title(test_title).unwrap(); |
| 463 | |
| 464 | let mut raw = [0_u16; 128]; |
| 465 | let length = unsafe { GetConsoleTitleW(raw.as_mut_ptr(), raw.len() as u32) } as usize; |
| 466 | assert_ne!(0, length); |
| 467 | |
| 468 | let console_title = OsString::from_wide(&raw[..length]).into_string().unwrap(); |
| 469 | assert_eq!(test_title, &console_title[..]); |
| 470 | } |
| 471 | } |
| 472 |