thing-tui: a restore that finds the writer held writes the restore bytes to a fresh stdout

The hook, in every build, claims the restore once, writes it to a fresh io::stdout() handle and
turns raw mode off; Drop then has nothing left to write. Proven by pty probes (unwind with and
without a destructor panic, and an abort build): red before, green after.

Per thing2:ruling:tui-panic-restore-rule and thing2:finding:cut-tui-host.s3.abort-lock-held-leaves-screen-modes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-29 02:44:07 +01:00
commit 5e1a436221

View file

@ -44,15 +44,19 @@ impl<W: Write + Send> Restore for Shared<W> {
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;
}