use std::io::{self, Stdout};
use crossterm::{
cursor::Show,
event::{DisableMouseCapture, EnableMouseCapture},
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{Terminal, backend::CrosstermBackend};
trait TerminalOps: Send {
fn leave(&mut self);
}
struct CrosstermOps;
impl TerminalOps for CrosstermOps {
fn leave(&mut self) {
let _ = disable_raw_mode();
let _ = execute!(
io::stdout(),
LeaveAlternateScreen,
DisableMouseCapture,
Show
);
}
}
pub struct TerminalGuard {
ops: Box<dyn TerminalOps>,
}
impl TerminalGuard {
pub fn enter() -> io::Result<(Self, Terminal<CrosstermBackend<Stdout>>)> {
enable_raw_mode()?;
let mut stdout = io::stdout();
if let Err(e) = execute!(stdout, EnterAlternateScreen, EnableMouseCapture) {
let _ = disable_raw_mode();
return Err(e);
}
let backend = CrosstermBackend::new(stdout);
let terminal = match Terminal::new(backend) {
Ok(t) => t,
Err(e) => {
let _ = disable_raw_mode();
let _ = execute!(
io::stdout(),
LeaveAlternateScreen,
DisableMouseCapture,
Show
);
return Err(e);
}
};
Ok((
Self {
ops: Box::new(CrosstermOps),
},
terminal,
))
}
#[cfg(test)]
fn with_ops(ops: Box<dyn TerminalOps>) -> Self {
Self { ops }
}
}
impl Drop for TerminalGuard {
fn drop(&mut self) {
self.ops.leave();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
struct RecordingOps(Arc<AtomicUsize>);
impl TerminalOps for RecordingOps {
fn leave(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
#[test]
fn drop_restores_on_normal_scope_exit() {
let count = Arc::new(AtomicUsize::new(0));
{
let _guard = TerminalGuard::with_ops(Box::new(RecordingOps(count.clone())));
assert_eq!(
count.load(Ordering::SeqCst),
0,
"must not restore on construction"
);
}
assert_eq!(count.load(Ordering::SeqCst), 1);
}
#[test]
fn drop_restores_on_panic_unwind() {
let count = Arc::new(AtomicUsize::new(0));
let count_in_closure = count.clone();
let result = panic::catch_unwind(AssertUnwindSafe(|| {
let _guard = TerminalGuard::with_ops(Box::new(RecordingOps(count_in_closure)));
panic!("simulated panic mid-render-loop");
}));
assert!(
result.is_err(),
"the panic must have propagated to catch_unwind"
);
assert_eq!(
count.load(Ordering::SeqCst),
1,
"TerminalGuard::drop must run during unwind, restoring the terminal exactly once"
);
}
#[test]
fn drop_restores_exactly_once_even_when_dropped_early() {
let count = Arc::new(AtomicUsize::new(0));
let guard = TerminalGuard::with_ops(Box::new(RecordingOps(count.clone())));
drop(guard);
assert_eq!(count.load(Ordering::SeqCst), 1);
}
}