Debian Codegraph @

debian/rust-vendor/console/src/windows_term/mod.rs

raw
1 use core::fmt::Display;
2 use core::iter::once;
3 use core::mem::{self, MaybeUninit};
4 use core::{char, cmp};
5 use std::env;
6 use std::ffi::OsStr;
7 use std::io;
8 use std::os::raw::c_void;
9 use std::os::windows::ffi::OsStrExt;
10 use std::os::windows::io::AsRawHandle;
11
12 use encode_unicode::error::Utf16TupleError;
13 use encode_unicode::CharExt;
14 use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE, MAX_PATH};
15 use windows_sys::Win32::Storage::FileSystem::{FileNameInfo, GetFileInformationByHandleEx};
16 use windows_sys::Win32::System::Console::CONSOLE_MODE;
17 use windows_sys::Win32::System::Console::{
18 FillConsoleOutputAttribute, FillConsoleOutputCharacterA, GetConsoleCursorInfo, GetConsoleMode,
19 GetConsoleScreenBufferInfo, GetNumberOfConsoleInputEvents, GetStdHandle, ReadConsoleInputW,
20 SetConsoleCursorInfo, SetConsoleCursorPosition, SetConsoleMode, SetConsoleTitleW,
21 CONSOLE_CURSOR_INFO, CONSOLE_SCREEN_BUFFER_INFO, COORD, ENABLE_PROCESSED_INPUT,
22 ENABLE_VIRTUAL_TERMINAL_PROCESSING, INPUT_RECORD, INPUT_RECORD_0, KEY_EVENT, KEY_EVENT_RECORD,
23 STD_ERROR_HANDLE, STD_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
24 };
25 use windows_sys::Win32::UI::Input::KeyboardAndMouse::VIRTUAL_KEY;
26
27 use crate::kb::Key;
28 use crate::term::{Term, TermTarget};
29 use crate::{common_term, is_dumb};
30
31 #[cfg(feature = "windows-console-colors")]
32 mod colors;
33
34 #[cfg(feature = "windows-console-colors")]
35 pub(crate) use self::colors::*;
36
37 pub(crate) const DEFAULT_WIDTH: u16 = 79;
38
39 pub(crate) fn is_a_terminal(out: &Term) -> bool {
40 let (fd, others) = match out.target() {
41 TermTarget::Stdout => (STD_OUTPUT_HANDLE, [STD_INPUT_HANDLE, STD_ERROR_HANDLE]),
42 TermTarget::Stderr => (STD_ERROR_HANDLE, [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE]),
43 };
44
45 if unsafe { console_on_any(&[fd]) } {
46 // False positives aren't possible. If we got a console then
47 // we definitely have a tty on stdin.
48 return true;
49 }
50
51 // At this point, we *could* have a false negative. We can determine that
52 // this is true negative if we can detect the presence of a console on
53 // any of the other streams. If another stream has a console, then we know
54 // we're in a Windows console and can therefore trust the negative.
55 if unsafe { console_on_any(&others) } {
56 return false;
57 }
58
59 msys_tty_on(out)
60 }
61
62 pub(crate) fn is_a_color_terminal(out: &Term) -> bool {
63 if !is_a_terminal(out) {
64 return false;
65 }
66 if env::var("NO_COLOR").is_ok() {
67 return false;
68 }
69 if msys_tty_on(out) {
70 return !is_dumb();
71 }
72 enable_ansi_on(out)
73 }
74
75 pub(crate) fn is_a_true_color_terminal(out: &Term) -> bool {
76 if !is_a_color_terminal(out) {
77 return false;
78 }
79 // Powershell does not respect the COLORTERM var despite supporting true colors
80 // but other shells may respect it
81 if msys_tty_on(out) {
82 return match env::var("COLORTERM") {
83 Ok(term) => term == "truecolor" || term == "24bit",
84 Err(_) => true,
85 };
86 }
87 false
88 }
89
90 /// Enables or disables the `mode` flag on the given `HANDLE` and yields the previous mode.
91 fn set_console_mode(handle: HANDLE, mode: CONSOLE_MODE, enable: bool) -> Option<CONSOLE_MODE> {
92 unsafe {
93 let mut dw_mode = 0;
94 if GetConsoleMode(handle, &mut dw_mode) == 0 {
95 return None;
96 }
97
98 let new_dw_mode = match enable {
99 true => dw_mode | mode,
100 false => dw_mode & !mode,
101 };
102
103 if SetConsoleMode(handle, new_dw_mode) == 0 {
104 return None;
105 }
106
107 Some(dw_mode)
108 }
109 }
110
111 struct ConsoleModeGuard {
112 handle: HANDLE,
113 restore_mode: CONSOLE_MODE,
114 }
115
116 impl ConsoleModeGuard {
117 fn set(handle: HANDLE, mode: CONSOLE_MODE, enable: bool) -> Option<Self> {
118 Some(ConsoleModeGuard {
119 handle,
120 restore_mode: set_console_mode(handle, mode, enable)?,
121 })
122 }
123 }
124
125 impl Drop for ConsoleModeGuard {
126 fn drop(&mut self) {
127 unsafe {
128 SetConsoleMode(self.handle, self.restore_mode);
129 }
130 }
131 }
132
133 fn enable_ansi_on(out: &Term) -> bool {
134 set_console_mode(
135 out.as_raw_handle(),
136 ENABLE_VIRTUAL_TERMINAL_PROCESSING,
137 true,
138 )
139 .is_some()
140 }
141
142 unsafe fn console_on_any(fds: &[STD_HANDLE]) -> bool {
143 for &fd in fds {
144 let mut out = 0;
145 let handle = GetStdHandle(fd);
146 if GetConsoleMode(handle, &mut out) != 0 {
147 return true;
148 }
149 }
150 false
151 }
152
153 pub(crate) fn terminal_size(out: &Term) -> Option<(u16, u16)> {
154 use windows_sys::Win32::System::Console::SMALL_RECT;
155
156 // convert between windows_sys::Win32::Foundation::HANDLE and std::os::windows::raw::HANDLE
157 let handle = out.as_raw_handle();
158 let hand = handle as windows_sys::Win32::Foundation::HANDLE;
159
160 if hand == INVALID_HANDLE_VALUE {
161 return None;
162 }
163
164 let zc = COORD { X: 0, Y: 0 };
165 let mut csbi = CONSOLE_SCREEN_BUFFER_INFO {
166 dwSize: zc,
167 dwCursorPosition: zc,
168 wAttributes: 0,
169 srWindow: SMALL_RECT {
170 Left: 0,
171 Top: 0,
172 Right: 0,
173 Bottom: 0,
174 },
175 dwMaximumWindowSize: zc,
176 };
177 if unsafe { GetConsoleScreenBufferInfo(hand, &mut csbi) } == 0 {
178 return None;
179 }
180
181 let rows = (csbi.srWindow.Bottom - csbi.srWindow.Top + 1) as u16;
182 let columns = (csbi.srWindow.Right - csbi.srWindow.Left + 1) as u16;
183
184 Some((rows, columns))
185 }
186
187 pub(crate) fn move_cursor_to(out: &Term, x: usize, y: usize) -> io::Result<()> {
188 if out.is_msys_tty {
189 return common_term::move_cursor_to(out, x, y);
190 }
191 if let Some((hand, _)) = get_console_screen_buffer_info(out.as_raw_handle()) {
192 unsafe {
193 SetConsoleCursorPosition(
194 hand,
195 COORD {
196 X: x as i16,
197 Y: y as i16,
198 },
199 );
200 }
201 }
202 Ok(())
203 }
204
205 pub(crate) fn move_cursor_up(out: &Term, n: usize) -> io::Result<()> {
206 if out.is_msys_tty {
207 return common_term::move_cursor_up(out, n);
208 }
209
210 if let Some((_, csbi)) = get_console_screen_buffer_info(out.as_raw_handle()) {
211 move_cursor_to(out, 0, csbi.dwCursorPosition.Y as usize - n)?;
212 }
213 Ok(())
214 }
215
216 pub(crate) fn move_cursor_down(out: &Term, n: usize) -> io::Result<()> {
217 if out.is_msys_tty {
218 return common_term::move_cursor_down(out, n);
219 }
220
221 if let Some((_, csbi)) = get_console_screen_buffer_info(out.as_raw_handle()) {
222 move_cursor_to(out, 0, csbi.dwCursorPosition.Y as usize + n)?;
223 }
224 Ok(())
225 }
226
227 pub(crate) fn move_cursor_left(out: &Term, n: usize) -> io::Result<()> {
228 if out.is_msys_tty {
229 return common_term::move_cursor_left(out, n);
230 }
231
232 if let Some((_, csbi)) = get_console_screen_buffer_info(out.as_raw_handle()) {
233 move_cursor_to(
234 out,
235 csbi.dwCursorPosition.X as usize - n,
236 csbi.dwCursorPosition.Y as usize,
237 )?;
238 }
239 Ok(())
240 }
241
242 pub(crate) fn move_cursor_right(out: &Term, n: usize) -> io::Result<()> {
243 if out.is_msys_tty {
244 return common_term::move_cursor_right(out, n);
245 }
246
247 if let Some((_, csbi)) = get_console_screen_buffer_info(out.as_raw_handle()) {
248 move_cursor_to(
249 out,
250 csbi.dwCursorPosition.X as usize + n,
251 csbi.dwCursorPosition.Y as usize,
252 )?;
253 }
254 Ok(())
255 }
256
257 pub(crate) fn clear_line(out: &Term) -> io::Result<()> {
258 if out.is_msys_tty {
259 return common_term::clear_line(out);
260 }
261 if let Some((hand, csbi)) = get_console_screen_buffer_info(out.as_raw_handle()) {
262 unsafe {
263 let width = csbi.srWindow.Right - csbi.srWindow.Left;
264 let pos = COORD {
265 X: 0,
266 Y: csbi.dwCursorPosition.Y,
267 };
268 let mut written = 0;
269 FillConsoleOutputCharacterA(hand, b' ' as i8, width as u32, pos, &mut written);
270 FillConsoleOutputAttribute(hand, csbi.wAttributes, width as u32, pos, &mut written);
271 SetConsoleCursorPosition(hand, pos);
272 }
273 }
274 Ok(())
275 }
276
277 pub(crate) fn clear_chars(out: &Term, n: usize) -> io::Result<()> {
278 if out.is_msys_tty {
279 return common_term::clear_chars(out, n);
280 }
281 if let Some((hand, csbi)) = get_console_screen_buffer_info(out.as_raw_handle()) {
282 unsafe {
283 let width = cmp::min(csbi.dwCursorPosition.X, n as i16);
284 let pos = COORD {
285 X: csbi.dwCursorPosition.X - width,
286 Y: csbi.dwCursorPosition.Y,
287 };
288 let mut written = 0;
289 FillConsoleOutputCharacterA(hand, b' ' as i8, width as u32, pos, &mut written);
290 FillConsoleOutputAttribute(hand, csbi.wAttributes, width as u32, pos, &mut written);
291 SetConsoleCursorPosition(hand, pos);
292 }
293 }
294 Ok(())
295 }
296
297 pub(crate) fn clear_screen(out: &Term) -> io::Result<()> {
298 if out.is_msys_tty {
299 return common_term::clear_screen(out);
300 }
301 if let Some((hand, csbi)) = get_console_screen_buffer_info(out.as_raw_handle()) {
302 unsafe {
303 let cells = csbi.dwSize.X as u32 * csbi.dwSize.Y as u32; // as u32, or else this causes stack overflows.
304 let pos = COORD { X: 0, Y: 0 };
305 let mut written = 0;
306 FillConsoleOutputCharacterA(hand, b' ' as i8, cells, pos, &mut written); // cells as u32 no longer needed.
307 FillConsoleOutputAttribute(hand, csbi.wAttributes, cells, pos, &mut written);
308 SetConsoleCursorPosition(hand, pos);
309 }
310 }
311 Ok(())
312 }
313
314 pub(crate) fn clear_to_end_of_screen(out: &Term) -> io::Result<()> {
315 if out.is_msys_tty {
316 return common_term::clear_to_end_of_screen(out);
317 }
318 if let Some((hand, csbi)) = get_console_screen_buffer_info(out.as_raw_handle()) {
319 unsafe {
320 let bottom = csbi.srWindow.Right as u32 * csbi.srWindow.Bottom as u32;
321 let cells = bottom - (csbi.dwCursorPosition.X as u32 * csbi.dwCursorPosition.Y as u32); // as u32, or else this causes stack overflows.
322 let pos = COORD {
323 X: 0,
324 Y: csbi.dwCursorPosition.Y,
325 };
326 let mut written = 0;
327 FillConsoleOutputCharacterA(hand, b' ' as i8, cells, pos, &mut written); // cells as u32 no longer needed.
328 FillConsoleOutputAttribute(hand, csbi.wAttributes, cells, pos, &mut written);
329 SetConsoleCursorPosition(hand, pos);
330 }
331 }
332 Ok(())
333 }
334
335 pub(crate) fn show_cursor(out: &Term) -> io::Result<()> {
336 if out.is_msys_tty {
337 return common_term::show_cursor(out);
338 }
339 if let Some((hand, mut cci)) = get_console_cursor_info(out.as_raw_handle()) {
340 unsafe {
341 cci.bVisible = 1;
342 SetConsoleCursorInfo(hand, &cci);
343 }
344 }
345 Ok(())
346 }
347
348 pub(crate) fn hide_cursor(out: &Term) -> io::Result<()> {
349 if out.is_msys_tty {
350 return common_term::hide_cursor(out);
351 }
352 if let Some((hand, mut cci)) = get_console_cursor_info(out.as_raw_handle()) {
353 unsafe {
354 cci.bVisible = 0;
355 SetConsoleCursorInfo(hand, &cci);
356 }
357 }
358 Ok(())
359 }
360
361 fn get_console_screen_buffer_info(hand: HANDLE) -> Option<(HANDLE, CONSOLE_SCREEN_BUFFER_INFO)> {
362 let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = unsafe { mem::zeroed() };
363 match unsafe { GetConsoleScreenBufferInfo(hand, &mut csbi) } {
364 0 => None,
365 _ => Some((hand, csbi)),
366 }
367 }
368
369 fn get_console_cursor_info(hand: HANDLE) -> Option<(HANDLE, CONSOLE_CURSOR_INFO)> {
370 let mut cci: CONSOLE_CURSOR_INFO = unsafe { mem::zeroed() };
371 match unsafe { GetConsoleCursorInfo(hand, &mut cci) } {
372 0 => None,
373 _ => Some((hand, cci)),
374 }
375 }
376
377 pub(crate) fn key_from_key_code(code: VIRTUAL_KEY) -> Key {
378 use windows_sys::Win32::UI::Input::KeyboardAndMouse;
379
380 match code {
381 KeyboardAndMouse::VK_LEFT => Key::ArrowLeft,
382 KeyboardAndMouse::VK_RIGHT => Key::ArrowRight,
383 KeyboardAndMouse::VK_UP => Key::ArrowUp,
384 KeyboardAndMouse::VK_DOWN => Key::ArrowDown,
385 KeyboardAndMouse::VK_RETURN => Key::Enter,
386 KeyboardAndMouse::VK_ESCAPE => Key::Escape,
387 KeyboardAndMouse::VK_BACK => Key::Backspace,
388 KeyboardAndMouse::VK_TAB => Key::Tab,
389 KeyboardAndMouse::VK_HOME => Key::Home,
390 KeyboardAndMouse::VK_END => Key::End,
391 KeyboardAndMouse::VK_DELETE => Key::Del,
392 KeyboardAndMouse::VK_SHIFT => Key::Shift,
393 KeyboardAndMouse::VK_MENU => Key::Alt,
394 _ => Key::Unknown,
395 }
396 }
397
398 pub(crate) fn read_secure() -> io::Result<String> {
399 let mut rv = String::new();
400 loop {
401 match read_single_key(false)? {
402 Key::Enter => {
403 break;
404 }
405 Key::Char('\x08') if !rv.is_empty() => {
406 let new_len = rv.len() - 1;
407 rv.truncate(new_len);
408 }
409 Key::Char(c) => {
410 rv.push(c);
411 }
412 _ => {}
413 }
414 }
415 Ok(rv)
416 }
417
418 pub(crate) fn read_single_key(ctrlc_key: bool) -> io::Result<Key> {
419 let key_event = {
420 let _guard = ctrlc_key.then(|| {
421 ConsoleModeGuard::set(
422 unsafe { GetStdHandle(STD_INPUT_HANDLE) },
423 ENABLE_PROCESSED_INPUT,
424 false,
425 )
426 });
427 read_key_event()?
428 };
429
430 let unicode_char = unsafe { key_event.uChar.UnicodeChar };
431 if unicode_char == 0 {
432 Ok(key_from_key_code(key_event.wVirtualKeyCode))
433 } else {
434 // This is a unicode character, in utf-16. Try to decode it by itself.
435 match char::from_utf16_tuple((unicode_char, None)) {
436 Ok(c) => {
437 // Maintain backward compatibility. The previous implementation (_getwch()) would return
438 // a special keycode for `Enter`, while ReadConsoleInputW() prefers to use '\r'.
439 if c == '\r' {
440 Ok(Key::Enter)
441 } else if c == '\t' {
442 Ok(Key::Tab)
443 } else if c == '\x08' {
444 Ok(Key::Backspace)
445 } else if c == '\x1B' {
446 Ok(Key::Escape)
447 } else if c == '\x03' && ctrlc_key {
448 Ok(Key::CtrlC)
449 } else {
450 Ok(Key::Char(c))
451 }
452 }
453 // This is part of a surrogate pair. Try to read the second half.
454 Err(Utf16TupleError::MissingSecond) => {
455 // Confirm that there is a next character to read.
456 if get_key_event_count()? == 0 {
457 let message = format!(
458 "Read invalid utf16 {}: {}",
459 unicode_char,
460 Utf16TupleError::MissingSecond
461 );
462 return Err(io::Error::new(io::ErrorKind::InvalidData, message));
463 }
464
465 // Read the next character.
466 let next_event = read_key_event()?;
467 let next_surrogate = unsafe { next_event.uChar.UnicodeChar };
468
469 // Attempt to decode it.
470 match char::from_utf16_tuple((unicode_char, Some(next_surrogate))) {
471 Ok(c) => Ok(Key::Char(c)),
472
473 // Return an InvalidData error. This is the recommended value for UTF-related I/O errors.
474 // (This error is given when reading a non-UTF8 file into a String, for example.)
475 Err(e) => {
476 let message = format!(
477 "Read invalid surrogate pair ({unicode_char}, {next_surrogate}): {e}",
478 );
479 Err(io::Error::new(io::ErrorKind::InvalidData, message))
480 }
481 }
482 }
483
484 // Return an InvalidData error. This is the recommended value for UTF-related I/O errors.
485 // (This error is given when reading a non-UTF8 file into a String, for example.)
486 Err(e) => {
487 let message = format!("Read invalid utf16 {unicode_char}: {e}");
488 Err(io::Error::new(io::ErrorKind::InvalidData, message))
489 }
490 }
491 }
492 }
493
494 fn get_stdin_handle() -> io::Result<HANDLE> {
495 let handle = unsafe { GetStdHandle(STD_INPUT_HANDLE) };
496 if handle == INVALID_HANDLE_VALUE {
497 Err(io::Error::last_os_error())
498 } else {
499 Ok(handle)
500 }
501 }
502
503 /// Get the number of pending events in the ReadConsoleInput queue. Note that while
504 /// these aren't necessarily key events, the only way that multiple events can be
505 /// put into the queue simultaneously is if a unicode character spanning multiple u16's
506 /// is read.
507 ///
508 /// Therefore, this is accurate as long as at least one KEY_EVENT has already been read.
509 fn get_key_event_count() -> io::Result<u32> {
510 let handle = get_stdin_handle()?;
511 let mut event_count: u32 = unsafe { mem::zeroed() };
512
513 let success = unsafe { GetNumberOfConsoleInputEvents(handle, &mut event_count) };
514 if success == 0 {
515 Err(io::Error::last_os_error())
516 } else {
517 Ok(event_count)
518 }
519 }
520
521 fn read_key_event() -> io::Result<KEY_EVENT_RECORD> {
522 let handle = get_stdin_handle()?;
523 let mut buffer: INPUT_RECORD = unsafe { mem::zeroed() };
524
525 let mut events_read: u32 = unsafe { mem::zeroed() };
526
527 let mut key_event: KEY_EVENT_RECORD;
528 loop {
529 let success = unsafe { ReadConsoleInputW(handle, &mut buffer, 1, &mut events_read) };
530 if success == 0 {
531 return Err(io::Error::last_os_error());
532 }
533 if events_read == 0 {
534 return Err(io::Error::new(
535 io::ErrorKind::Other,
536 "ReadConsoleInput returned no events, instead of waiting for an event",
537 ));
538 }
539
540 if events_read == 1 && buffer.EventType != KEY_EVENT as u16 {
541 // This isn't a key event; ignore it.
542 continue;
543 }
544
545 key_event = unsafe { mem::transmute::<INPUT_RECORD_0, KEY_EVENT_RECORD>(buffer.Event) };
546
547 if key_event.bKeyDown == 0 {
548 // This is a key being released; ignore it.
549 continue;
550 }
551
552 return Ok(key_event);
553 }
554 }
555
556 pub(crate) fn wants_emoji() -> bool {
557 // If WT_SESSION is set, we can assume we're running in the new
558 // Windows Terminal. The correct way to detect this is not available
559 // yet. See https://github.com/microsoft/terminal/issues/1040
560 env::var("WT_SESSION").is_ok()
561 }
562
563 /// Returns true if there is an MSYS tty on the given handle.
564 pub(crate) fn msys_tty_on(term: &Term) -> bool {
565 let handle = term.as_raw_handle();
566 unsafe {
567 // Check whether the Windows 10 native pty is enabled
568 {
569 let mut out = MaybeUninit::uninit();
570 let res = GetConsoleMode(handle as HANDLE, out.as_mut_ptr());
571 if res != 0 // If res is true then out was initialized.
572 && (out.assume_init() & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
573 == ENABLE_VIRTUAL_TERMINAL_PROCESSING
574 {
575 return true;
576 }
577 }
578
579 /// Mirrors windows_sys::Win32::Storage::FileSystem::FILE_NAME_INFO, giving
580 /// it a fixed length that we can stack allocate
581 #[repr(C)]
582 #[allow(non_snake_case)]
583 struct FILE_NAME_INFO {
584 FileNameLength: u32,
585 FileName: [u16; MAX_PATH as usize],
586 }
587
588 let mut name_info = FILE_NAME_INFO {
589 FileNameLength: 0,
590 FileName: [0; MAX_PATH as usize],
591 };
592 let res = GetFileInformationByHandleEx(
593 handle as HANDLE,
594 FileNameInfo,
595 &mut name_info as *mut _ as *mut c_void,
596 mem::size_of::<FILE_NAME_INFO>() as u32,
597 );
598 if res == 0 {
599 return false;
600 }
601
602 // Use `get` because `FileNameLength` can be out of range.
603 let s = match name_info
604 .FileName
605 .get(..name_info.FileNameLength as usize / 2)
606 {
607 Some(s) => s,
608 None => return false,
609 };
610 let name = String::from_utf16_lossy(s);
611 // This checks whether 'pty' exists in the file name, which indicates that
612 // a pseudo-terminal is attached. To mitigate against false positives
613 // (e.g., an actual file name that contains 'pty'), we also require that
614 // either the strings 'msys-' or 'cygwin-' are in the file name as well.)
615 let is_msys = name.contains("msys-") || name.contains("cygwin-");
616 let is_pty = name.contains("-pty");
617 is_msys && is_pty
618 }
619 }
620
621 pub(crate) fn set_title<T: Display>(title: T) {
622 let buffer: Vec<u16> = OsStr::new(&format!("{title}"))
623 .encode_wide()
624 .chain(once(0))
625 .collect();
626 unsafe {
627 SetConsoleTitleW(buffer.as_ptr());
628 }
629 }