| 1 |
use std::{ |
| 2 |
fmt, |
| 3 |
fs::{self, File}, |
| 4 |
io::{self, BufWriter, IsTerminal as _, Write as _}, |
| 5 |
mem, |
| 6 |
os::windows::prelude::*, |
| 7 |
ptr, |
| 8 |
}; |
| 9 |
|
| 10 |
use windows_sys::Win32::{ |
| 11 |
Storage::FileSystem::WriteFile, |
| 12 |
System::Console::{ |
| 13 |
self, GetConsoleCP, GetConsoleMode, GetConsoleOutputCP, GetConsoleScreenBufferInfo, |
| 14 |
GetNumberOfConsoleInputEvents, ReadConsoleInputA, ReadConsoleInputW, SetConsoleCP, |
| 15 |
SetConsoleMode, SetConsoleOutputCP, CONSOLE_MODE, CONSOLE_SCREEN_BUFFER_INFO, INPUT_RECORD, |
| 16 |
}, |
| 17 |
}; |
| 18 |
|
| 19 |
use crate::{ |
| 20 |
event::source::WindowsEventSource, windows::InputReaderMode, Event, EventReader, OneBased, |
| 21 |
WindowSize, |
| 22 |
}; |
| 23 |
|
| 24 |
use super::Terminal; |
| 25 |
|
| 26 |
macro_rules! bail { |
| 27 |
($msg:literal $(,)?) => { |
| 28 |
return Err(::std::io::Error::new(::std::io::ErrorKind::Other, $msg)) |
| 29 |
}; |
| 30 |
($fmt:expr $(,)?, $($arg:tt)*) => { |
| 31 |
return Err(::std::io::Error::new(::std::io::ErrorKind::Other, format!($fmt, $($arg)*))) |
| 32 |
}; |
| 33 |
} |
| 34 |
|
| 35 |
const BUF_SIZE: usize = 128; |
| 36 |
|
| 37 |
type CodePageID = u32; |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
const CP_UTF8: CodePageID = 65001; |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
#[derive(Debug)] |
| 53 |
pub enum Handle { |
| 54 |
|
| 55 |
Owned(OwnedHandle), |
| 56 |
|
| 57 |
|
| 58 |
Borrowed(BorrowedHandle<'static>), |
| 59 |
} |
| 60 |
|
| 61 |
impl AsRawHandle for Handle { |
| 62 |
fn as_raw_handle(&self) -> RawHandle { |
| 63 |
match self { |
| 64 |
Self::Owned(handle) => handle.as_raw_handle(), |
| 65 |
Self::Borrowed(handle) => handle.as_raw_handle(), |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
impl Handle { |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
pub fn stdin() -> Self { |
| 76 |
let stdin = io::stdin().as_raw_handle(); |
| 77 |
Self::Borrowed(unsafe { BorrowedHandle::borrow_raw(stdin) }) |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
pub fn stdout() -> Self { |
| 82 |
let stdout = io::stdout().as_raw_handle(); |
| 83 |
Self::Borrowed(unsafe { BorrowedHandle::borrow_raw(stdout) }) |
| 84 |
} |
| 85 |
|
| 86 |
pub fn try_clone(&self) -> io::Result<Self> { |
| 87 |
let this = match self { |
| 88 |
Self::Owned(handle) => Self::Owned(handle.try_clone()?), |
| 89 |
Self::Borrowed(handle) => Self::Borrowed(*handle), |
| 90 |
}; |
| 91 |
Ok(this) |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
impl From<File> for Handle { |
| 96 |
fn from(file: File) -> Self { |
| 97 |
Self::Owned(OwnedHandle::from(file)) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
pub(crate) struct InputHandle { |
| 102 |
handle: Handle, |
| 103 |
input_buf: Vec<INPUT_RECORD>, |
| 104 |
mode: InputReaderMode, |
| 105 |
} |
| 106 |
|
| 107 |
impl fmt::Debug for InputHandle { |
| 108 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 109 |
f.debug_struct("InputHandle") |
| 110 |
.field("handle", &self.handle) |
| 111 |
.finish_non_exhaustive() |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
impl InputHandle { |
| 116 |
fn new(handle: Handle, mode: InputReaderMode) -> Self { |
| 117 |
let mut input_buf = Vec::with_capacity(BUF_SIZE); |
| 118 |
let zeroed: INPUT_RECORD = unsafe { mem::zeroed() }; |
| 119 |
input_buf.resize(BUF_SIZE, zeroed); |
| 120 |
|
| 121 |
Self { |
| 122 |
handle, |
| 123 |
mode, |
| 124 |
input_buf, |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
fn try_clone(&self) -> io::Result<Self> { |
| 129 |
Ok(Self { |
| 130 |
handle: self.handle.try_clone()?, |
| 131 |
input_buf: self.input_buf.clone(), |
| 132 |
mode: self.mode, |
| 133 |
}) |
| 134 |
} |
| 135 |
|
| 136 |
fn get_mode(&self) -> io::Result<CONSOLE_MODE> { |
| 137 |
let mut mode = 0; |
| 138 |
if unsafe { GetConsoleMode(self.as_raw_handle(), &mut mode) } == 0 { |
| 139 |
bail!( |
| 140 |
"failed to get input console mode: {}", |
| 141 |
io::Error::last_os_error() |
| 142 |
); |
| 143 |
} |
| 144 |
Ok(mode) |
| 145 |
} |
| 146 |
|
| 147 |
fn set_mode(&mut self, mode: CONSOLE_MODE) -> io::Result<()> { |
| 148 |
if unsafe { SetConsoleMode(self.as_raw_handle(), mode) } == 0 { |
| 149 |
bail!( |
| 150 |
"failed to set input console mode: {}", |
| 151 |
io::Error::last_os_error() |
| 152 |
); |
| 153 |
} |
| 154 |
|
| 155 |
Ok(()) |
| 156 |
} |
| 157 |
|
| 158 |
fn get_code_page(&self) -> io::Result<CodePageID> { |
| 159 |
let cp = unsafe { GetConsoleCP() }; |
| 160 |
if cp == 0 { |
| 161 |
bail!( |
| 162 |
"failed to get input console codepage ID: {}", |
| 163 |
io::Error::last_os_error() |
| 164 |
); |
| 165 |
} |
| 166 |
Ok(cp) |
| 167 |
} |
| 168 |
|
| 169 |
fn set_code_page(&mut self, cp: CodePageID) -> io::Result<()> { |
| 170 |
if unsafe { SetConsoleCP(cp) } == 0 { |
| 171 |
bail!( |
| 172 |
"failed to set input console codepage ID: {}", |
| 173 |
io::Error::last_os_error() |
| 174 |
); |
| 175 |
} |
| 176 |
Ok(()) |
| 177 |
} |
| 178 |
|
| 179 |
pub fn has_pending_input_events(&mut self) -> io::Result<bool> { |
| 180 |
let mut num = 0; |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
if unsafe { GetNumberOfConsoleInputEvents(self.as_raw_handle(), &mut num) } == 0 { |
| 187 |
bail!( |
| 188 |
"failed to read input console number of pending events: {}", |
| 189 |
io::Error::last_os_error() |
| 190 |
); |
| 191 |
} |
| 192 |
Ok(num > 0) |
| 193 |
} |
| 194 |
|
| 195 |
pub fn read_console_input(&mut self) -> io::Result<&[INPUT_RECORD]> { |
| 196 |
let mut num = 0; |
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
if unsafe { |
| 202 |
match self.mode { |
| 203 |
InputReaderMode::Vte => ReadConsoleInputA( |
| 204 |
self.as_raw_handle(), |
| 205 |
self.input_buf.as_mut_ptr(), |
| 206 |
self.input_buf.capacity() as u32, |
| 207 |
&mut num, |
| 208 |
), |
| 209 |
InputReaderMode::Legacy => |
| 210 |
|
| 211 |
|
| 212 |
{ |
| 213 |
ReadConsoleInputW( |
| 214 |
self.as_raw_handle(), |
| 215 |
self.input_buf.as_mut_ptr(), |
| 216 |
self.input_buf.capacity() as u32, |
| 217 |
&mut num, |
| 218 |
) |
| 219 |
} |
| 220 |
} |
| 221 |
} == 0 |
| 222 |
{ |
| 223 |
bail!( |
| 224 |
"failed to read console input events: {}", |
| 225 |
io::Error::last_os_error() |
| 226 |
); |
| 227 |
} |
| 228 |
unsafe { self.input_buf.set_len(num as usize) }; |
| 229 |
Ok(&self.input_buf) |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
impl AsRawHandle for InputHandle { |
| 234 |
fn as_raw_handle(&self) -> RawHandle { |
| 235 |
self.handle.as_raw_handle() |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
#[derive(Debug)] |
| 244 |
pub struct OutputHandle { |
| 245 |
handle: Handle, |
| 246 |
} |
| 247 |
|
| 248 |
impl OutputHandle { |
| 249 |
fn new(handle: Handle) -> Self { |
| 250 |
Self { handle } |
| 251 |
} |
| 252 |
|
| 253 |
fn get_mode(&self) -> io::Result<CONSOLE_MODE> { |
| 254 |
let mut mode = 0; |
| 255 |
if unsafe { GetConsoleMode(self.as_raw_handle(), &mut mode) } == 0 { |
| 256 |
bail!( |
| 257 |
"failed to get output console mode: {}", |
| 258 |
io::Error::last_os_error() |
| 259 |
); |
| 260 |
} |
| 261 |
Ok(mode) |
| 262 |
} |
| 263 |
|
| 264 |
fn set_mode(&mut self, mode: CONSOLE_MODE) -> io::Result<()> { |
| 265 |
if unsafe { SetConsoleMode(self.as_raw_handle(), mode) } == 0 { |
| 266 |
bail!( |
| 267 |
"failed to set output console mode: {}", |
| 268 |
io::Error::last_os_error() |
| 269 |
); |
| 270 |
} |
| 271 |
|
| 272 |
Ok(()) |
| 273 |
} |
| 274 |
|
| 275 |
fn get_code_page(&self) -> io::Result<CodePageID> { |
| 276 |
let cp = unsafe { GetConsoleOutputCP() }; |
| 277 |
if cp == 0 { |
| 278 |
bail!( |
| 279 |
"failed to get output console codepage ID: {}", |
| 280 |
io::Error::last_os_error() |
| 281 |
); |
| 282 |
} |
| 283 |
Ok(cp) |
| 284 |
} |
| 285 |
|
| 286 |
fn set_code_page(&mut self, cp: CodePageID) -> io::Result<()> { |
| 287 |
if unsafe { SetConsoleOutputCP(cp) } == 0 { |
| 288 |
bail!( |
| 289 |
"failed to set output console codepage ID: {}", |
| 290 |
io::Error::last_os_error() |
| 291 |
); |
| 292 |
} |
| 293 |
Ok(()) |
| 294 |
} |
| 295 |
|
| 296 |
fn get_dimensions(&self) -> io::Result<WindowSize> { |
| 297 |
let mut info: CONSOLE_SCREEN_BUFFER_INFO = unsafe { mem::zeroed() }; |
| 298 |
if unsafe { GetConsoleScreenBufferInfo(self.as_raw_handle(), &mut info) } == 0 { |
| 299 |
bail!( |
| 300 |
"failed to get console screen buffer info: {}", |
| 301 |
io::Error::last_os_error() |
| 302 |
); |
| 303 |
} |
| 304 |
let rows = OneBased::from_zero_based((info.srWindow.Bottom - info.srWindow.Top) as u16); |
| 305 |
let cols = OneBased::from_zero_based((info.srWindow.Right - info.srWindow.Left) as u16); |
| 306 |
Ok(WindowSize { |
| 307 |
rows: rows.get(), |
| 308 |
cols: cols.get(), |
| 309 |
pixel_width: None, |
| 310 |
pixel_height: None, |
| 311 |
}) |
| 312 |
} |
| 313 |
} |
| 314 |
|
| 315 |
impl AsRawHandle for OutputHandle { |
| 316 |
fn as_raw_handle(&self) -> RawHandle { |
| 317 |
self.handle.as_raw_handle() |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
impl io::Write for OutputHandle { |
| 322 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 323 |
let mut num_written = 0; |
| 324 |
if unsafe { |
| 325 |
WriteFile( |
| 326 |
self.as_raw_handle(), |
| 327 |
buf.as_ptr(), |
| 328 |
buf.len() as u32, |
| 329 |
&mut num_written, |
| 330 |
ptr::null_mut(), |
| 331 |
) |
| 332 |
} == 0 |
| 333 |
{ |
| 334 |
Err(io::Error::last_os_error()) |
| 335 |
} else { |
| 336 |
Ok(num_written as usize) |
| 337 |
} |
| 338 |
} |
| 339 |
|
| 340 |
fn flush(&mut self) -> io::Result<()> { |
| 341 |
Ok(()) |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
fn open_pty(mode: InputReaderMode) -> io::Result<(InputHandle, OutputHandle)> { |
| 346 |
let input = if io::stdin().is_terminal() { |
| 347 |
Handle::stdin() |
| 348 |
} else { |
| 349 |
open_file("CONIN$")?.into() |
| 350 |
}; |
| 351 |
let output = if io::stdout().is_terminal() { |
| 352 |
Handle::stdout() |
| 353 |
} else { |
| 354 |
open_file("CONOUT$")?.into() |
| 355 |
}; |
| 356 |
Ok((InputHandle::new(input, mode), OutputHandle::new(output))) |
| 357 |
} |
| 358 |
|
| 359 |
fn open_file(path: &str) -> io::Result<File> { |
| 360 |
fs::OpenOptions::new().read(true).write(true).open(path) |
| 361 |
} |
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
#[derive(Debug)] |
| 374 |
pub struct WindowsTerminal { |
| 375 |
input: InputHandle, |
| 376 |
output: BufWriter<OutputHandle>, |
| 377 |
reader: EventReader, |
| 378 |
original_input_mode: CONSOLE_MODE, |
| 379 |
original_output_mode: CONSOLE_MODE, |
| 380 |
original_input_cp: CodePageID, |
| 381 |
original_output_cp: CodePageID, |
| 382 |
has_panic_hook: bool, |
| 383 |
mode: InputReaderMode, |
| 384 |
} |
| 385 |
|
| 386 |
impl WindowsTerminal { |
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
pub fn new() -> io::Result<Self> { |
| 392 |
Self::with_mode_internal(InputReaderMode::Vte) |
| 393 |
} |
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
#[cfg(feature = "windows-legacy")] |
| 400 |
pub fn with_mode(mode: InputReaderMode) -> io::Result<Self> { |
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
Self::with_mode_internal(mode) |
| 406 |
} |
| 407 |
|
| 408 |
fn with_mode_internal(mode: InputReaderMode) -> io::Result<Self> { |
| 409 |
let (mut input, mut output) = open_pty(mode)?; |
| 410 |
|
| 411 |
let original_input_mode = input.get_mode()?; |
| 412 |
let original_output_mode = output.get_mode()?; |
| 413 |
let original_input_cp = input.get_code_page()?; |
| 414 |
let original_output_cp = output.get_code_page()?; |
| 415 |
if mode == InputReaderMode::Vte { |
| 416 |
input.set_code_page(CP_UTF8)?; |
| 417 |
output.set_code_page(CP_UTF8)?; |
| 418 |
} |
| 419 |
|
| 420 |
|
| 421 |
let desired_output_mode = original_output_mode |
| 422 |
| Console::ENABLE_VIRTUAL_TERMINAL_PROCESSING |
| 423 |
| Console::DISABLE_NEWLINE_AUTO_RETURN; |
| 424 |
if output.set_mode(desired_output_mode).is_err() { |
| 425 |
bail!("virtual terminal processing could not be enabled for the output handle"); |
| 426 |
} |
| 427 |
|
| 428 |
if mode == InputReaderMode::Vte { |
| 429 |
|
| 430 |
let desired_input_mode = original_input_mode | Console::ENABLE_VIRTUAL_TERMINAL_INPUT; |
| 431 |
if input.set_mode(desired_input_mode).is_err() { |
| 432 |
bail!("virtual terminal processing could not be enabled for the input handle"); |
| 433 |
} |
| 434 |
} |
| 435 |
|
| 436 |
let reader = EventReader::new(WindowsEventSource::new(input.try_clone()?, mode)?); |
| 437 |
|
| 438 |
Ok(Self { |
| 439 |
input, |
| 440 |
output: BufWriter::with_capacity(BUF_SIZE, output), |
| 441 |
reader, |
| 442 |
original_input_mode, |
| 443 |
original_output_mode, |
| 444 |
original_input_cp, |
| 445 |
original_output_cp, |
| 446 |
mode, |
| 447 |
has_panic_hook: false, |
| 448 |
}) |
| 449 |
} |
| 450 |
} |
| 451 |
|
| 452 |
impl Terminal for WindowsTerminal { |
| 453 |
fn enter_raw_mode(&mut self) -> io::Result<()> { |
| 454 |
let mode = self.output.get_mut().get_mode()?; |
| 455 |
self.output |
| 456 |
.get_mut() |
| 457 |
.set_mode(mode | Console::DISABLE_NEWLINE_AUTO_RETURN) |
| 458 |
.ok(); |
| 459 |
let mode = self.input.get_mode()?; |
| 460 |
self.input.set_mode( |
| 461 |
(mode |
| 462 |
& !(Console::ENABLE_ECHO_INPUT |
| 463 |
| Console::ENABLE_LINE_INPUT |
| 464 |
| Console::ENABLE_PROCESSED_INPUT)) |
| 465 |
| Console::ENABLE_MOUSE_INPUT |
| 466 |
| Console::ENABLE_WINDOW_INPUT, |
| 467 |
)?; |
| 468 |
|
| 469 |
Ok(()) |
| 470 |
} |
| 471 |
|
| 472 |
fn enter_cooked_mode(&mut self) -> io::Result<()> { |
| 473 |
let mode = self.output.get_mut().get_mode()?; |
| 474 |
self.output |
| 475 |
.get_mut() |
| 476 |
.set_mode(mode & !Console::DISABLE_NEWLINE_AUTO_RETURN) |
| 477 |
.ok(); |
| 478 |
|
| 479 |
let mode = self.input.get_mode()?; |
| 480 |
self.input.set_mode( |
| 481 |
(mode & !(Console::ENABLE_MOUSE_INPUT | Console::ENABLE_WINDOW_INPUT)) |
| 482 |
| Console::ENABLE_ECHO_INPUT |
| 483 |
| Console::ENABLE_LINE_INPUT |
| 484 |
| Console::ENABLE_PROCESSED_INPUT, |
| 485 |
)?; |
| 486 |
Ok(()) |
| 487 |
} |
| 488 |
|
| 489 |
fn get_dimensions(&self) -> io::Result<WindowSize> { |
| 490 |
|
| 491 |
|
| 492 |
self.output.get_ref().get_dimensions() |
| 493 |
} |
| 494 |
|
| 495 |
fn event_reader(&self) -> EventReader { |
| 496 |
self.reader.clone() |
| 497 |
} |
| 498 |
|
| 499 |
fn poll<F: Fn(&Event) -> bool>( |
| 500 |
&self, |
| 501 |
filter: F, |
| 502 |
timeout: Option<std::time::Duration>, |
| 503 |
) -> io::Result<bool> { |
| 504 |
self.reader.poll(timeout, filter) |
| 505 |
} |
| 506 |
|
| 507 |
fn read<F: Fn(&Event) -> bool>(&self, filter: F) -> io::Result<Event> { |
| 508 |
self.reader.read(filter) |
| 509 |
} |
| 510 |
|
| 511 |
fn set_panic_hook(&mut self, f: impl Fn(&mut OutputHandle) + Send + Sync + 'static) { |
| 512 |
let original_input_cp = self.original_input_cp; |
| 513 |
let original_input_mode = self.original_input_mode; |
| 514 |
let original_output_cp = self.original_output_cp; |
| 515 |
let original_output_mode = self.original_output_mode; |
| 516 |
let hook = std::panic::take_hook(); |
| 517 |
let mode = self.mode; |
| 518 |
std::panic::set_hook(Box::new(move |info| { |
| 519 |
if let Ok((mut input, mut output)) = open_pty(mode) { |
| 520 |
f(&mut output); |
| 521 |
let _ = input.set_code_page(original_input_cp); |
| 522 |
let _ = input.set_mode(original_input_mode); |
| 523 |
let _ = output.set_code_page(original_output_cp); |
| 524 |
let _ = output.set_mode(original_output_mode); |
| 525 |
} |
| 526 |
hook(info); |
| 527 |
})); |
| 528 |
self.has_panic_hook = true; |
| 529 |
} |
| 530 |
} |
| 531 |
|
| 532 |
impl Drop for WindowsTerminal { |
| 533 |
fn drop(&mut self) { |
| 534 |
if !self.has_panic_hook || !std::thread::panicking() { |
| 535 |
let _ = self.flush(); |
| 536 |
let _ = self.input.set_code_page(self.original_input_cp); |
| 537 |
let _ = self.output.get_mut().set_code_page(self.original_output_cp); |
| 538 |
let _ = self.input.set_mode(self.original_input_mode); |
| 539 |
let _ = self.output.get_mut().set_mode(self.original_output_mode); |
| 540 |
} |
| 541 |
} |
| 542 |
} |
| 543 |
|
| 544 |
impl io::Write for WindowsTerminal { |
| 545 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 546 |
self.output.write(buf) |
| 547 |
} |
| 548 |
|
| 549 |
fn flush(&mut self) -> io::Result<()> { |
| 550 |
self.output.flush() |
| 551 |
} |
| 552 |
} |