This repository has been archived on 2026-10-08. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
maestro/crates/maestro-tui/src/terminal.rs
T

86 lines
2.2 KiB
Rust

//! `TerminalGuard` — RAII setup/teardown of raw mode, the alternate screen
//! buffer, and mouse capture. Restores everything on drop or panic.
//!
//! Pattern matches `crates/maestro-cli/src/attach.rs::RawTty`.
use std::io;
use crossterm::event::{
DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
};
use crossterm::execute;
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
#[derive(Debug)]
pub struct TerminalGuard;
#[derive(Debug, thiserror::Error)]
pub enum TerminalError {
#[error("io: {0}")]
Io(#[from] io::Error),
}
impl TerminalGuard {
/// Enter raw mode, switch to alt screen, enable mouse capture. Returns a
/// guard whose `Drop` impl reverses each step.
pub fn enter() -> Result<Self, TerminalError> {
enable_raw_mode()?;
let mut out = io::stdout();
execute!(
out,
EnterAlternateScreen,
EnableMouseCapture,
EnableBracketedPaste
)?;
Ok(TerminalGuard)
}
/// Restore terminal state. Idempotent so the panic hook + `Drop` can both
/// call it without producing weird errors.
fn restore() {
let mut out = io::stdout();
let _ = execute!(
out,
DisableBracketedPaste,
DisableMouseCapture,
LeaveAlternateScreen
);
let _ = disable_raw_mode();
}
}
impl Drop for TerminalGuard {
fn drop(&mut self) {
Self::restore();
}
}
static HOOK_INSTALLED: std::sync::Once = std::sync::Once::new();
/// Install a panic hook that restores the terminal before re-panicking, so
/// a backtrace lands in cooked mode instead of glitching against the alt
/// screen. Idempotent — safe to call from `run()` every time.
pub fn install_panic_hook() {
HOOK_INSTALLED.call_once(|| {
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
TerminalGuard::restore();
prev(info);
}));
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn install_panic_hook_is_idempotent() {
install_panic_hook();
install_panic_hook();
install_panic_hook();
}
}