diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 16bce9e..60f9858 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -27,13 +27,21 @@ struct Shared { out: Mutex, entered: AtomicBool, raw: bool, + /// The thread that last entered or drew through the guard: a panic there is a panic in the guard's + /// user, and a guard moved to another thread is owned by whoever uses it. + owner: Mutex, } trait Restore: Send + Sync { + fn owner(&self) -> ThreadId; fn restore(&self); } impl Restore for Shared { + fn owner(&self) -> ThreadId { + *self.owner.lock().unwrap_or_else(PoisonError::into_inner) + } + fn restore(&self) { // The lock is held across a write: a panic inside one (on this thread) reaches the hook with // it taken. The escape bytes are left to `Drop`, which runs once the unwinding has released @@ -61,10 +69,10 @@ impl Restore for Shared { /// The guards that are entered, each with the thread that entered it: the only terminals a panic /// hook may give back, and only to a panic on the thread that owns one. -static GUARDS: Mutex)>> = Mutex::new(Vec::new()); +static GUARDS: Mutex>> = Mutex::new(Vec::new()); static HOOK: Once = Once::new(); -fn guards() -> MutexGuard<'static, Vec<(ThreadId, Arc)>> { +fn guards() -> MutexGuard<'static, Vec>> { GUARDS.lock().unwrap_or_else(PoisonError::into_inner) } @@ -110,8 +118,8 @@ impl Terminal { enable_raw_mode()?; } // Registered before anything is written, so a failure part-way still restores on drop. - let shared = Arc::new(Shared { out: Mutex::new(out), entered: AtomicBool::new(true), raw }); - guards().push((thread::current().id(), shared.clone())); + let shared = Arc::new(Shared { out: Mutex::new(out), entered: AtomicBool::new(true), raw, owner: Mutex::new(thread::current().id()) }); + guards().push(shared.clone()); let terminal = Self { shared }; { let mut out = terminal.out(); @@ -127,6 +135,7 @@ impl Terminal { /// Serialize `ops` as one synchronized update and flush once. No ops write nothing. pub fn draw(&mut self, ops: &[Op]) -> io::Result<()> { + *self.shared.owner.lock().unwrap_or_else(PoisonError::into_inner) = thread::current().id(); if ops.is_empty() { return Ok(()); } @@ -153,7 +162,7 @@ impl Terminal { impl Drop for Terminal { fn drop(&mut self) { - guards().retain(|(_, guard)| !std::ptr::addr_eq(Arc::as_ptr(guard), Arc::as_ptr(&self.shared))); + guards().retain(|guard| !std::ptr::addr_eq(Arc::as_ptr(guard), Arc::as_ptr(&self.shared))); self.shared.restore(); } } @@ -211,7 +220,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, _)| restores_here(cfg!(panic = "abort"), *owner, here)).map(|(_, guard)| guard.clone()).collect(); + let owned: Vec> = guards().iter().filter(|guard| restores_here(cfg!(panic = "abort"), guard.owner(), here)).cloned().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 17dc793..655f147 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -322,3 +322,45 @@ fn a_panic_restores_on_the_owners_thread_and_on_any_thread_when_nothing_unwinds( assert!(restores_here(true, here, here)); assert!(restores_here(true, here, elsewhere)); } + +#[test] +fn a_guard_moved_to_a_render_thread_follows_its_user() { + let out = Shared::default(); + let terminal = guard(&out); + let watched = out.clone(); + let at_hook = std::thread::spawn(move || { + WATCH.with(|watch| *watch.borrow_mut() = Some(watched)); + AT_HAND_OVER.with(|seen| *seen.borrow_mut() = None); + let mut terminal = terminal; + terminal.draw(&[Op::MoveTo(0, 0), Op::Print("x".into())]).unwrap(); + let _ = catch_unwind(AssertUnwindSafe(move || { + let _terminal = terminal; + panic!("forced on the render thread"); + })); + at_hand_over() + }) + .join() + .unwrap(); + assert_eq!(count(&at_hook.expect("the previous hook was reached"), LEAVE), 1, "the thread that drew restores before its message"); + assert_eq!(count(&out.bytes(), LEAVE), 1); +} + +#[test] +fn a_panic_on_the_thread_that_built_a_guard_it_gave_away_leaves_it_alone() { + let out = Shared::default(); + let mut terminal = guard(&out); + let terminal = std::thread::spawn(move || { + terminal.draw(&[Op::MoveTo(0, 0), Op::Print("x".into())]).unwrap(); + terminal + }) + .join() + .unwrap(); + let caught = catch_unwind(AssertUnwindSafe(move || { + let _terminal = terminal; + panic!("forced on the thread that built it"); + })); + assert!(caught.is_err()); + let seen = at_hand_over().expect("the previous hook was reached"); + assert_eq!(count(&seen, LEAVE), 0, "the render thread owns it now; this panic's unwinding drop restores"); + assert_eq!(count(&out.bytes(), LEAVE), 1); +}