diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 6111f81..1750d02 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -189,6 +189,14 @@ fn write_restore(out: &mut W) -> io::Result<()> { update.and(paste).and(rest) } +/// Whether a panic on `here` gives back the terminal a guard owned by `owner` holds. Unwinding runs +/// the owner's `Drop` for a panic elsewhere, so only the owner's own panic needs the hook (its message +/// would otherwise print on the alternate screen). Where panics abort nothing unwinds to any `Drop`, +/// so every panic restores. +fn restores_here(abort: bool, owner: ThreadId, here: ThreadId) -> bool { + abort || owner == here +} + /// Chain a hook ahead of the current one: a panic on a thread that owns an entered guard gives that /// terminal back before the previous hook prints, and a panic anywhere else goes to the previous /// hook alone. @@ -196,7 +204,7 @@ fn install_panic_hook() { let previous = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { let here = thread::current().id(); - let owned: Vec> = guards().iter().filter(|(owner, _)| *owner == here).map(|(_, guard)| guard.clone()).collect(); + let owned: Vec> = guards().iter().filter(|(owner, _)| restores_here(cfg!(panic = "abort"), *owner, here)).map(|(_, guard)| guard.clone()).collect(); for guard in owned { guard.restore(); } diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index 7e6e9b3..17dc793 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -11,7 +11,7 @@ use std::sync::{Arc, Mutex, Once}; use thing_contract::Rgba; use thing_core::layout::CellStyle; -use super::{Terminal, write_enter, write_restore}; +use super::{Terminal, restores_here, write_enter, write_restore}; use crate::{Op, Screen, diff}; /// A writer the test keeps a handle on after the terminal that owns it is gone. @@ -310,3 +310,15 @@ fn dropping_one_guard_leaves_the_others_registered() { assert!(caught.is_err()); assert_eq!(count(&at_hand_over().expect("hook ran"), LEAVE), 1, "the surviving guard is still restored by the hook"); } + +#[test] +fn a_panic_restores_on_the_owners_thread_and_on_any_thread_when_nothing_unwinds() { + let here = std::thread::current().id(); + let elsewhere = std::thread::spawn(|| std::thread::current().id()).join().unwrap(); + // Unwinding: the owner's panic restores, another thread's leaves the guard to its owner's Drop. + assert!(restores_here(false, here, here)); + assert!(!restores_here(false, here, elsewhere)); + // Aborting: no Drop will follow a panic anywhere, so every panic restores. + assert!(restores_here(true, here, here)); + assert!(restores_here(true, here, elsewhere)); +}