use std::sync::atomic::{AtomicIsize, Ordering};
use std::sync::Mutex;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::System::Console::{
GetConsoleMode, GetConsoleScreenBufferInfo, GetStdHandle, SetConsoleCtrlHandler,
SetConsoleMode, CONSOLE_MODE, CONSOLE_SCREEN_BUFFER_INFO, CTRL_CLOSE_EVENT, CTRL_C_EVENT,
DISABLE_NEWLINE_AUTO_RETURN, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT,
ENABLE_VIRTUAL_TERMINAL_INPUT, ENABLE_VIRTUAL_TERMINAL_PROCESSING, ENABLE_WINDOW_INPUT,
STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
};
use windows::Win32::System::Threading::SetEvent;
use windows_core::BOOL;
pub(super) struct ConsoleModeRestorer {
h_stdin: HANDLE,
h_stdout: HANDLE,
original_stdin_mode: CONSOLE_MODE,
original_stdout_mode: CONSOLE_MODE,
active: bool,
}
impl ConsoleModeRestorer {
pub(super) fn install_raw_vt() -> Self {
let h_stdin = unsafe { GetStdHandle(STD_INPUT_HANDLE) }.unwrap_or_default();
let h_stdout = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }.unwrap_or_default();
let mut original_stdin_mode = CONSOLE_MODE(0);
let mut original_stdout_mode = CONSOLE_MODE(0);
let stdin_ok = unsafe { GetConsoleMode(h_stdin, &mut original_stdin_mode) }.is_ok();
let stdout_ok = unsafe { GetConsoleMode(h_stdout, &mut original_stdout_mode) }.is_ok();
if !stdin_ok || !stdout_ok {
return Self {
h_stdin,
h_stdout,
original_stdin_mode,
original_stdout_mode,
active: false,
};
}
let raw_in = CONSOLE_MODE(
(original_stdin_mode.0 | ENABLE_VIRTUAL_TERMINAL_INPUT.0 | ENABLE_WINDOW_INPUT.0)
& !(ENABLE_PROCESSED_INPUT.0 | ENABLE_LINE_INPUT.0 | ENABLE_ECHO_INPUT.0),
);
let raw_out = CONSOLE_MODE(
original_stdout_mode.0
| ENABLE_VIRTUAL_TERMINAL_PROCESSING.0
| DISABLE_NEWLINE_AUTO_RETURN.0,
);
let in_set = unsafe { SetConsoleMode(h_stdin, raw_in) }.is_ok();
if !in_set {
return Self {
h_stdin,
h_stdout,
original_stdin_mode,
original_stdout_mode,
active: false,
};
}
let out_set = unsafe { SetConsoleMode(h_stdout, raw_out) }.is_ok();
if !out_set {
let _ = unsafe { SetConsoleMode(h_stdin, original_stdin_mode) };
return Self {
h_stdin,
h_stdout,
original_stdin_mode,
original_stdout_mode,
active: false,
};
}
Self {
h_stdin,
h_stdout,
original_stdin_mode,
original_stdout_mode,
active: true,
}
}
}
impl Drop for ConsoleModeRestorer {
fn drop(&mut self) {
if self.active {
unsafe {
let _ = SetConsoleMode(self.h_stdin, self.original_stdin_mode);
let _ = SetConsoleMode(self.h_stdout, self.original_stdout_mode);
}
}
}
}
static STDIN_STOP_EVENT_RAW: AtomicIsize = AtomicIsize::new(0);
static CTRL_HANDLER_LOCK: Mutex<()> = Mutex::new(());
fn lock_ctrl_handler() -> std::sync::MutexGuard<'static, ()> {
CTRL_HANDLER_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
unsafe extern "system" fn ctrl_handler(ctrl_type: u32) -> BOOL {
if ctrl_type == CTRL_C_EVENT || ctrl_type == CTRL_CLOSE_EVENT {
let _lock = lock_ctrl_handler();
let raw = STDIN_STOP_EVENT_RAW.load(Ordering::SeqCst);
#[cfg(test)]
tests::ctrl_handler_pause_point();
if raw != 0 {
let h = HANDLE(raw as *mut core::ffi::c_void);
let _ = SetEvent(h);
}
BOOL::from(true)
} else {
BOOL::from(false)
}
}
pub(super) struct CtrlHandlerGuard {
installed: bool,
}
impl CtrlHandlerGuard {
pub(super) fn install(stop_event: HANDLE) -> Self {
let _lock = lock_ctrl_handler();
STDIN_STOP_EVENT_RAW.store(stop_event.0 as isize, Ordering::SeqCst);
let installed = unsafe { SetConsoleCtrlHandler(Some(ctrl_handler), true) }.is_ok();
if !installed {
STDIN_STOP_EVENT_RAW.store(0, Ordering::SeqCst);
}
Self { installed }
}
}
impl Drop for CtrlHandlerGuard {
fn drop(&mut self) {
let _lock = lock_ctrl_handler();
if self.installed {
unsafe {
let _ = SetConsoleCtrlHandler(Some(ctrl_handler), false);
}
}
STDIN_STOP_EVENT_RAW.store(0, Ordering::SeqCst);
}
}
pub(super) fn get_local_console_size() -> Option<(u16, u16)> {
let h_stdout = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }.ok()?;
let mut info = CONSOLE_SCREEN_BUFFER_INFO::default();
if unsafe { GetConsoleScreenBufferInfo(h_stdout, &mut info) }.is_err() {
return None;
}
let cols = (info.srWindow.Right - info.srWindow.Left + 1).max(0) as u16;
let rows = (info.srWindow.Bottom - info.srWindow.Top + 1).max(0) as u16;
if cols == 0 || rows == 0 {
return None;
}
Some((cols, rows))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc;
use std::time::Duration;
use crate::mxc_common::process_util::OwnedHandle;
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::System::Console::{
CTRL_BREAK_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT,
};
use windows::Win32::System::Threading::{
CreateEventW, ResetEvent, SetEvent, WaitForSingleObject,
};
use windows_core::PCWSTR;
static CTRL_HANDLER_TEST_LOCK: Mutex<()> = Mutex::new(());
type PausePoint = (mpsc::Sender<()>, mpsc::Receiver<()>);
static CTRL_HANDLER_PAUSE: Mutex<Option<PausePoint>> = Mutex::new(None);
pub(super) fn ctrl_handler_pause_point() {
let pause = CTRL_HANDLER_PAUSE
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.take();
if let Some((loaded_tx, resume_rx)) = pause {
let _ = loaded_tx.send(());
let _ = resume_rx.recv();
}
}
fn make_stop_event() -> OwnedHandle {
let handle = unsafe { CreateEventW(None, true, false, PCWSTR::null()) }
.expect("create manual-reset test event");
OwnedHandle::new(handle)
}
#[test]
fn test_get_local_console_size_does_not_panic() {
if let Some((cols, rows)) = get_local_console_size() {
assert!(cols > 0);
assert!(rows > 0);
}
}
#[test]
fn test_console_mode_restorer_handles_non_console() {
let _restorer = ConsoleModeRestorer::install_raw_vt();
}
#[test]
fn test_ctrl_handler_guard_install_and_drop_do_not_panic() {
let _lock = CTRL_HANDLER_TEST_LOCK.lock().unwrap();
let owned = make_stop_event();
let event = owned.get();
{
let _guard = CtrlHandlerGuard::install(event);
assert_ne!(STDIN_STOP_EVENT_RAW.load(Ordering::SeqCst), 0);
}
assert_eq!(STDIN_STOP_EVENT_RAW.load(Ordering::SeqCst), 0);
}
#[test]
fn test_ctrl_handler_signals_event_on_tracked_signals() {
let _lock = CTRL_HANDLER_TEST_LOCK.lock().unwrap();
let owned = make_stop_event();
let event = owned.get();
let _guard = CtrlHandlerGuard::install(event);
for signal in [CTRL_C_EVENT, CTRL_CLOSE_EVENT] {
unsafe {
ResetEvent(event).unwrap();
}
let pre = unsafe { WaitForSingleObject(event, 0) };
assert_ne!(
pre, WAIT_OBJECT_0,
"event should be reset before handler runs (signal {})",
signal
);
let result = unsafe { ctrl_handler(signal) };
assert!(
result.as_bool(),
"handler must return TRUE for tracked signal {}",
signal
);
let post = unsafe { WaitForSingleObject(event, 100) };
assert_eq!(
post, WAIT_OBJECT_0,
"event should be signaled after handler runs (signal {})",
signal
);
}
drop(_guard);
}
#[test]
fn test_ctrl_handler_is_inert_after_guard_teardown() {
let _lock = CTRL_HANDLER_TEST_LOCK.lock().unwrap();
let owned = make_stop_event();
let event = owned.get();
{
let _guard = CtrlHandlerGuard::install(event);
assert_ne!(STDIN_STOP_EVENT_RAW.load(Ordering::SeqCst), 0);
}
assert_eq!(STDIN_STOP_EVENT_RAW.load(Ordering::SeqCst), 0);
unsafe {
ResetEvent(event).unwrap();
}
let result = unsafe { ctrl_handler(CTRL_C_EVENT) };
assert!(
result.as_bool(),
"handler still suppresses the OS default after teardown"
);
let post = unsafe { WaitForSingleObject(event, 0) };
assert_ne!(
post, WAIT_OBJECT_0,
"a handler after teardown must not signal the retired event"
);
}
#[test]
fn test_guard_teardown_waits_for_in_flight_handler() {
let _lock = CTRL_HANDLER_TEST_LOCK.lock().unwrap();
let owned = make_stop_event();
let event = owned.get();
let guard = CtrlHandlerGuard::install(event);
let (loaded_tx, loaded_rx) = mpsc::channel();
let (resume_tx, resume_rx) = mpsc::channel();
*CTRL_HANDLER_PAUSE.lock().unwrap() = Some((loaded_tx, resume_rx));
let handler = std::thread::spawn(|| unsafe { ctrl_handler(CTRL_C_EVENT) }.as_bool());
loaded_rx
.recv_timeout(Duration::from_secs(5))
.expect("handler should reach the pause point");
let (done_tx, done_rx) = mpsc::channel();
let teardown = std::thread::spawn(move || {
drop(guard);
let _ = done_tx.send(());
});
assert!(
matches!(
done_rx.recv_timeout(Duration::from_millis(250)),
Err(mpsc::RecvTimeoutError::Timeout)
),
"guard teardown must block while the handler is between load and SetEvent"
);
assert_ne!(
STDIN_STOP_EVENT_RAW.load(Ordering::SeqCst),
0,
"target must not be cleared while the handler is in flight"
);
resume_tx.send(()).unwrap();
assert!(handler.join().unwrap(), "handler must return TRUE");
done_rx
.recv_timeout(Duration::from_secs(5))
.expect("teardown should finish once the handler is done");
teardown.join().unwrap();
assert_eq!(
unsafe { WaitForSingleObject(event, 0) },
WAIT_OBJECT_0,
"the in-flight handler signals the still-open event"
);
assert_eq!(STDIN_STOP_EVENT_RAW.load(Ordering::SeqCst), 0);
}
#[test]
fn test_ctrl_handler_after_rollover_targets_only_current_execution() {
let _lock = CTRL_HANDLER_TEST_LOCK.lock().unwrap();
let owned_a = make_stop_event();
drop(CtrlHandlerGuard::install(owned_a.get()));
let owned_b = make_stop_event();
let guard_b = CtrlHandlerGuard::install(owned_b.get());
assert!(unsafe { ctrl_handler(CTRL_C_EVENT) }.as_bool());
assert_ne!(
unsafe { WaitForSingleObject(owned_a.get(), 0) },
WAIT_OBJECT_0,
"the retired execution's event must not be signaled"
);
assert_eq!(
unsafe { WaitForSingleObject(owned_b.get(), 0) },
WAIT_OBJECT_0,
"the current execution's event is signaled"
);
drop(guard_b);
}
#[test]
fn test_per_execution_stop_events_are_independent() {
let owned_a = make_stop_event();
let owned_b = make_stop_event();
unsafe {
SetEvent(owned_a.get()).unwrap();
}
let a_state = unsafe { WaitForSingleObject(owned_a.get(), 0) };
let b_state = unsafe { WaitForSingleObject(owned_b.get(), 0) };
assert_eq!(
a_state, WAIT_OBJECT_0,
"A's own event is signaled for A's relay"
);
assert_ne!(
b_state, WAIT_OBJECT_0,
"B's event is independent and stays unsignaled"
);
}
#[test]
fn test_ctrl_handler_returns_false_for_untracked_signals() {
let _lock = CTRL_HANDLER_TEST_LOCK.lock().unwrap();
for signal in [CTRL_BREAK_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT] {
let result = unsafe { ctrl_handler(signal) };
assert!(
!result.as_bool(),
"handler must return FALSE for untracked signal {}",
signal
);
}
}
#[test]
fn test_ctrl_handler_is_safe_with_no_target() {
let _lock = CTRL_HANDLER_TEST_LOCK.lock().unwrap();
STDIN_STOP_EVENT_RAW.store(0, Ordering::SeqCst);
for signal in [CTRL_C_EVENT, CTRL_CLOSE_EVENT] {
let result = unsafe { ctrl_handler(signal) };
assert!(
result.as_bool(),
"handler must return TRUE for signal {} even with no target",
signal
);
}
}
}