diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 60f9858..50de37c 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -21,7 +21,7 @@ use thing_contract::Rgba; use crate::diff::Op; -/// What a guard holds, shared with the panic hook through `GUARDS`. `entered` is claimed by whichever +/// What a guard holds, shared with the panic hook through `ACTIVE`. `entered` is claimed by whichever /// restores first (the hook on a panic, `Drop` otherwise), so the restore is written once. struct Shared { out: Mutex, @@ -67,13 +67,14 @@ 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()); +/// The one guard that is entered, if any: the only terminal a panic hook may give back. Raw mode, the +/// alternate screen and the cursor belong to the process, not to a writer, so a second guard while +/// one lives is refused rather than left to take the first one's terminal when it drops. +static ACTIVE: Mutex>> = Mutex::new(None); static HOOK: Once = Once::new(); -fn guards() -> MutexGuard<'static, Vec>> { - GUARDS.lock().unwrap_or_else(PoisonError::into_inner) +fn active() -> MutexGuard<'static, Option>> { + ACTIVE.lock().unwrap_or_else(PoisonError::into_inner) } /// The guard's surface is `stdout`, `enter` and `draw`: the byte helpers and a way to enter without @@ -108,18 +109,26 @@ impl Terminal { /// back before the previous panic hook speaks, so its message lands on the user's screen; a /// panic on another thread leaves it alone. The first guard of the process installs that hook, /// chained ahead of the hook already there. + /// + /// One guard may be live in a process: raw mode and the screen modes are the process's, so a second + /// `enter` or `stdout()` while one is alive fails with `AlreadyExists`. pub fn enter(out: W) -> io::Result { Self::start(out, true) } fn start(out: W, raw: bool) -> io::Result { HOOK.call_once(install_panic_hook); + let mut slot = active(); + if slot.is_some() { + return Err(io::Error::new(io::ErrorKind::AlreadyExists, "a terminal guard is already live in this process")); + } if raw { 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, owner: Mutex::new(thread::current().id()) }); - guards().push(shared.clone()); + *slot = Some(shared.clone()); + drop(slot); let terminal = Self { shared }; { let mut out = terminal.out(); @@ -162,7 +171,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))); + *active() = None; self.shared.restore(); } } @@ -213,15 +222,15 @@ 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. +/// Chain a hook ahead of the current one: a panic that `restores_here` gives the live guard's terminal +/// back before the previous hook prints, and any other panic goes to the previous hook alone. 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(|guard| restores_here(cfg!(panic = "abort"), guard.owner(), here)).cloned().collect(); - for guard in owned { + let live = active().clone(); + if let Some(guard) = live + && restores_here(cfg!(panic = "abort"), guard.owner(), thread::current().id()) + { guard.restore(); } previous(info); diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index 655f147..6c2cbff 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -42,6 +42,14 @@ thread_local! { static SPY: Once = Once::new(); +/// One terminal guard may be live in a process, and tests run on threads of one: each that builds a +/// guard holds this for its whole body. +static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); + +fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> { + ONE_AT_A_TIME.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// Make the spy the hook the guard's hook will chain to. Every test that builds a guard calls this /// first, so the spy is installed before the guard's hook is. fn spy() { @@ -88,6 +96,7 @@ fn owner_panics(out: &Shared) { #[test] fn a_panic_on_the_owning_thread_restores_exactly_once() { + let _one = one_at_a_time(); let out = Shared::default(); owner_panics(&out); assert_eq!(count(&out.bytes(), LEAVE), 1); @@ -96,6 +105,7 @@ fn a_panic_on_the_owning_thread_restores_exactly_once() { #[test] fn a_panic_on_another_thread_leaves_the_guard_alone() { + let _one = one_at_a_time(); let out = Shared::default(); let terminal = guard(&out); let worker = std::thread::spawn(|| panic!("forced on a worker")); @@ -111,6 +121,7 @@ fn a_panic_on_another_thread_leaves_the_guard_alone() { #[test] fn a_panic_after_the_guard_dropped_writes_nothing() { + let _one = one_at_a_time(); let out = Shared::default(); drop(guard(&out)); let after_drop = out.bytes(); @@ -124,6 +135,7 @@ fn a_panic_after_the_guard_dropped_writes_nothing() { } #[test] fn building_a_guard_installs_the_hook() { + let _one = one_at_a_time(); let out = Shared::default(); owner_panics(&out); let seen = at_hand_over().expect("the previous hook was reached"); @@ -149,6 +161,7 @@ fn rgb(r: u8, g: u8, b: u8) -> Option { #[test] fn a_one_cell_diff_is_one_synchronized_update_with_one_move() { + let _one = one_at_a_time(); let old = Screen::new(4, 2); let mut new = old.clone(); new.cells[4 + 2].glyph = "x".into(); @@ -164,17 +177,20 @@ fn a_one_cell_diff_is_one_synchronized_update_with_one_move() { #[test] fn no_ops_write_nothing() { + let _one = one_at_a_time(); assert_eq!(drawn(&[]), Vec::::new()); } #[test] fn a_move_beyond_the_terminal_addressing_saturates() { + let _one = one_at_a_time(); let bytes = drawn(&[Op::MoveTo(70_000, 1)]); assert!(has(&bytes, "\x1b[2;65535H"), "{bytes:?}"); } #[test] fn style_none_resets_the_colour_and_some_is_truecolor() { + let _one = one_at_a_time(); let plain = drawn(&[Op::Style(None, None, CellStyle::default())]); assert!(has(&plain, "\x1b[39m") && has(&plain, "\x1b[49m"), "{plain:?}"); assert!(!has(&plain, "38;2") && !has(&plain, "48;2"), "{plain:?}"); @@ -188,6 +204,7 @@ fn style_none_resets_the_colour_and_some_is_truecolor() { #[test] fn each_attribute_is_set_and_each_absent_one_is_cleared() { + let _one = one_at_a_time(); let off = drawn(&[Op::Style(None, None, CellStyle::default())]); for cleared in ["\x1b[22m", "\x1b[23m", "\x1b[24m"] { assert!(has(&off, cleared), "{cleared:?} missing in {off:?}"); @@ -210,6 +227,7 @@ fn each_attribute_is_set_and_each_absent_one_is_cleared() { #[test] fn print_writes_the_text_in_place() { + let _one = one_at_a_time(); let bytes = drawn(&[Op::MoveTo(0, 0), Op::Print("h\u{e9}llo".into())]); assert!(has(&bytes, "\x1b[1;1Hh\u{e9}llo"), "{bytes:?}"); } @@ -242,6 +260,7 @@ fn entering_writes_every_mode_and_restoring_undoes_each() { #[test] fn dropping_the_guard_restores_once() { + let _one = one_at_a_time(); let out = Shared::default(); let terminal = guard(&out); for sequence in modes(ENTER) { @@ -282,6 +301,7 @@ impl Write for Flaky { #[test] fn an_error_mid_draw_does_not_leave_the_synchronized_update_open() { + let _one = one_at_a_time(); spy(); let out = Shared::default(); let left = Arc::new(std::sync::atomic::AtomicIsize::new(-1)); @@ -297,20 +317,6 @@ fn an_error_mid_draw_does_not_leave_the_synchronized_update_open() { assert!(end < bytes.rfind(LEAVE).unwrap(), "closed before the alternate screen is left"); } -#[test] -fn dropping_one_guard_leaves_the_others_registered() { - let (kept, dropped) = (Shared::default(), Shared::default()); - let other = Terminal::start(dropped.clone(), false).unwrap(); - let live = guard(&kept); - drop(other); - let caught = catch_unwind(AssertUnwindSafe(move || { - let _live = live; - panic!("forced with a guard that outlived another"); - })); - 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(); @@ -325,6 +331,7 @@ fn a_panic_restores_on_the_owners_thread_and_on_any_thread_when_nothing_unwinds( #[test] fn a_guard_moved_to_a_render_thread_follows_its_user() { + let _one = one_at_a_time(); let out = Shared::default(); let terminal = guard(&out); let watched = out.clone(); @@ -347,6 +354,7 @@ fn a_guard_moved_to_a_render_thread_follows_its_user() { #[test] fn a_panic_on_the_thread_that_built_a_guard_it_gave_away_leaves_it_alone() { + let _one = one_at_a_time(); let out = Shared::default(); let mut terminal = guard(&out); let terminal = std::thread::spawn(move || { @@ -364,3 +372,19 @@ fn a_panic_on_the_thread_that_built_a_guard_it_gave_away_leaves_it_alone() { 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); } + +#[test] +fn a_second_guard_is_refused_while_one_is_live() { + let _one = one_at_a_time(); + let (first_out, second_out) = (Shared::default(), Shared::default()); + let first = guard(&first_out); + let refused = Terminal::start(second_out.clone(), false).err().expect("a second guard while one is live"); + assert_eq!(refused.kind(), io::ErrorKind::AlreadyExists); + assert!(second_out.bytes().is_empty(), "the refused guard wrote nothing"); + // The first is untouched, and the refusal left no trace that blocks the next guard once it drops. + assert!(first_out.bytes().windows(LEAVE.len()).all(|w| w != LEAVE.as_bytes())); + drop(first); + assert_eq!(count(&first_out.bytes(), LEAVE), 1); + drop(Terminal::start(second_out.clone(), false).expect("a guard after the last one dropped")); + assert_eq!(count(&second_out.bytes(), LEAVE), 1); +}