diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 4d11024..01f882c 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -44,15 +44,19 @@ impl Restore for Shared { 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 - // the writer; raw mode needs no writer, so it is given back now, because `Drop` may never run - // (a second panic during the unwind, or an abort). + // it taken, and the writer is the thing that panicked. `Drop` may never run (a second panic + // during the unwind, or an abort), so the restore is made now, once: the escape bytes go to a + // fresh stdout handle, best effort, and raw mode, which needs no writer, is given back. let mut out = match self.out.try_lock() { Ok(out) => out, Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), Err(TryLockError::WouldBlock) => { - if self.raw { - let _ = disable_raw_mode(); + if self.entered.swap(false, Ordering::SeqCst) { + let mut fresh = io::stdout(); + let _ = write_restore(&mut fresh).and_then(|()| fresh.flush()); + if self.raw { + let _ = disable_raw_mode(); + } } return; }