From 91a466192da432058b1781d08aa55829e0e31aa7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 01:41:25 +0100 Subject: [PATCH 01/19] thing-tui: live terminal host (cut 8b): Terminal guard and writer, translate, reference host example Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 173 +++++++++++++++++++++ crates/thing-tui/Cargo.toml | 5 +- crates/thing-tui/examples/fixture.rs | 98 ++++++++++++ crates/thing-tui/src/input.rs | 96 ++++++++++++ crates/thing-tui/src/lib.rs | 14 +- crates/thing-tui/src/terminal.rs | 170 +++++++++++++++++++++ crates/thing-tui/tests/input.rs | 217 +++++++++++++++++++++++++++ crates/thing-tui/tests/pipeline.rs | 127 ++++++++++++++++ crates/thing-tui/tests/terminal.rs | 168 +++++++++++++++++++++ 9 files changed, 1063 insertions(+), 5 deletions(-) create mode 100644 crates/thing-tui/examples/fixture.rs create mode 100644 crates/thing-tui/src/input.rs create mode 100644 crates/thing-tui/src/terminal.rs create mode 100644 crates/thing-tui/tests/input.rs create mode 100644 crates/thing-tui/tests/pipeline.rs create mode 100644 crates/thing-tui/tests/terminal.rs diff --git a/Cargo.lock b/Cargo.lock index 322564d..8fdf809 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,6 +32,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + [[package]] name = "block-buffer" version = "0.10.4" @@ -92,6 +98,32 @@ dependencies = [ "libc", ] +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags", + "crossterm_winapi", + "document-features", + "mio", + "parking_lot", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -143,6 +175,25 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -251,6 +302,27 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -263,6 +335,18 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -287,6 +371,29 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -336,6 +443,15 @@ dependencies = [ "libc", ] +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + [[package]] name = "rmp" version = "0.8.15" @@ -361,12 +477,31 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "serde" version = "1.0.229" @@ -448,6 +583,37 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "slab" version = "0.4.12" @@ -568,6 +734,7 @@ dependencies = [ name = "thing-tui" version = "0.1.0" dependencies = [ + "crossterm", "thing-contract", "thing-core", "thing-testkit", @@ -620,6 +787,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasm-bindgen" version = "0.2.129" diff --git a/crates/thing-tui/Cargo.toml b/crates/thing-tui/Cargo.toml index 62a20e4..53de017 100644 --- a/crates/thing-tui/Cargo.toml +++ b/crates/thing-tui/Cargo.toml @@ -9,10 +9,13 @@ publish = false # unicode-segmentation or unicode-linebreak. Every width this crate advances by arrives in a # `CellText` from thing-core, and layout is thing-core's. (thing-core links those crates, so they # are in this crate's full tree; the rule is checked on `cargo tree -e normal --depth 1`.) -# No terminal I/O either: paint and diff are pure, and the live writer is a later cut. +# Terminal I/O is crossterm's alone, in `terminal` and `input`; paint and diff stay pure. crossterm +# is pinned exactly, without its default features: no derive-more and no async event stream, because +# core never awaits. [dependencies] thing-contract = { path = "../thing-contract" } thing-core = { path = "../thing-core" } +crossterm = { version = "=0.29.0", default-features = false, features = ["events", "windows", "bracketed-paste"] } [dev-dependencies] thing-testkit = { path = "../thing-testkit" } diff --git a/crates/thing-tui/examples/fixture.rs b/crates/thing-tui/examples/fixture.rs new file mode 100644 index 0000000..c7a2445 --- /dev/null +++ b/crates/thing-tui/examples/fixture.rs @@ -0,0 +1,98 @@ +//! The reference host: one fixture surface drawn live in the terminal. +//! +//! cargo run -p thing-tui --example fixture -- f01-swarm-dashboard +//! +//! Quit with q or Ctrl+C. The loop is the host's, and so is the clock: the host reads the time, +//! the terminal size and the terminal's events, lends core its state port and ids, and draws what +//! core hands back through `paint`, `diff` and `Terminal`. Core awaits nothing and reads no clock. +//! Core does not route input yet, so a click or a scroll reaches `frame` and changes nothing; a +//! resize is read as the next frame's viewport. + +use std::io; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crossterm::event; +use thing_contract::RecordKey; +use thing_core::input::{InputEvent, Key}; +use thing_core::layout::Metrics; +use thing_core::text::CellMeasure; +use thing_core::time::Timestamp; +use thing_core::{Config, Core, FrameInput, Ports}; +use thing_testkit::fixture::Fixture; +use thing_testkit::ids::SeqIds; +use thing_testkit::mem_state::MemState; +use thing_testkit::state; +use thing_tui::{Screen, Terminal, diff, paint, translate}; + +fn stem(fixture: Fixture) -> String { + fixture.file_name().trim_end_matches(".surface.cc").to_string() +} + +fn now() -> Timestamp { + let since = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); + Timestamp(i64::try_from(since.as_millis()).unwrap_or(i64::MAX)) +} + +/// The host's own key for leaving; core has no notion of quitting. +fn quits(events: &[InputEvent]) -> bool { + events.iter().any(|event| match event { + InputEvent::Key { key: Key::Char('c'), modifiers, .. } => modifiers.ctrl, + InputEvent::Key { key: Key::Char('q'), modifiers, .. } => !modifiers.ctrl && !modifiers.alt, + _ => false, + }) +} + +fn main() -> io::Result<()> { + let name = std::env::args().nth(1).unwrap_or_else(|| "f01-swarm-dashboard".to_string()); + let Some(fixture) = Fixture::ALL.into_iter().find(|fixture| stem(*fixture) == name) else { + let known: Vec = Fixture::ALL.into_iter().map(stem).collect(); + eprintln!("unknown fixture {name:?}; one of: {}", known.join(", ")); + std::process::exit(2); + }; + let set = fixture.load(); + let Some(surface) = set.surfaces.first() else { + eprintln!("{name} holds no surface"); + std::process::exit(2); + }; + let mut mem = MemState::from_fixture(fixture); + state::script(fixture, &mut mem); + let mut ids = SeqIds::new(); + + let mut core = Core::new(Config::new(Metrics::Cells, "renderer.tui"), Box::new(CellMeasure)); + core.show(surface.provider_id.clone(), RecordKey::new(surface.record_key())); + + let mut terminal = Terminal::stdout()?; + let mut prev = Screen::new(0, 0); + let mut events: Vec = Vec::new(); + let mut next_wake: Option = None; + let mut first = true; + loop { + if !first { + // Sleep until the next terminal event or core's wake time, whichever is first. + let timeout = next_wake.map(|at| Duration::from_millis(u64::try_from((at.0 - now().0).max(0)).unwrap_or(0))); + let mut ready = match timeout { + Some(timeout) => event::poll(timeout)?, + None => true, + }; + while ready { + events.extend(translate(&event::read()?)); + ready = event::poll(Duration::ZERO)?; + } + if quits(&events) { + return Ok(()); + } + } + first = false; + + let (cols, rows) = crossterm::terminal::size()?; + let output = core.frame( + FrameInput { now: now(), viewport: (f32::from(cols), f32::from(rows)), scale: 1.0, events: std::mem::take(&mut events) }, + Ports { state: &mut mem, ids: &mut ids }, + ); + let mut next = Screen::new(usize::from(cols), usize::from(rows)); + paint(&output.commands, &mut next); + terminal.draw(&diff(&prev, &next))?; + prev = next; + next_wake = output.next_wake; + } +} diff --git a/crates/thing-tui/src/input.rs b/crates/thing-tui/src/input.rs new file mode 100644 index 0000000..7786631 --- /dev/null +++ b/crates/thing-tui/src/input.rs @@ -0,0 +1,96 @@ +//! crossterm events into core's closed `InputEvent`: pure, one event in, zero or more out. The +//! mapping decides nothing about focus, hit-testing or activation; those are core's. + +use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; +use thing_core::input::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; + +/// The `InputEvent`s one terminal event stands for, in the order core must see them. An event with +/// none (a key release, a resize, a key core has no name for) gives an empty list: a resize is not +/// input, the host reads the terminal size into the next `FrameInput::viewport`. `Compose` and +/// `PointerCancel` are never produced: a terminal composes in the emulator and sends committed text. +pub fn translate(event: &Event) -> Vec { + match event { + Event::Key(key) => key_events(key), + Event::Mouse(mouse) => vec![mouse_event(mouse)], + Event::FocusGained => vec![InputEvent::Focus(true)], + Event::FocusLost => vec![InputEvent::Focus(false)], + Event::Paste(text) => vec![InputEvent::Text(text.clone())], + Event::Resize(..) => Vec::new(), + } +} + +fn modifiers(held: KeyModifiers) -> Modifiers { + Modifiers { + shift: held.contains(KeyModifiers::SHIFT), + ctrl: held.contains(KeyModifiers::CONTROL), + alt: held.contains(KeyModifiers::ALT), + meta: held.intersects(KeyModifiers::SUPER | KeyModifiers::META), + } +} + +fn key_events(event: &KeyEvent) -> Vec { + // crossterm reports releases on Windows; a release never reaches core. + let repeat = match event.kind { + KeyEventKind::Press => false, + KeyEventKind::Repeat => true, + KeyEventKind::Release => return Vec::new(), + }; + let mut modifiers = modifiers(event.modifiers); + let key = match event.code { + KeyCode::Char(c) => Key::Char(c), + KeyCode::Enter => Key::Enter, + KeyCode::Tab => Key::Tab, + // The terminal's Shift+Tab: core has Tab with shift. + KeyCode::BackTab => { + modifiers.shift = true; + Key::Tab + } + KeyCode::Backspace => Key::Backspace, + KeyCode::Delete => Key::Delete, + KeyCode::Esc => Key::Escape, + KeyCode::Left => Key::Left, + KeyCode::Right => Key::Right, + KeyCode::Up => Key::Up, + KeyCode::Down => Key::Down, + KeyCode::Home => Key::Home, + KeyCode::End => Key::End, + KeyCode::PageUp => Key::PageUp, + KeyCode::PageDown => Key::PageDown, + KeyCode::Insert => Key::Insert, + KeyCode::F(n) => Key::F(n), + _ => return Vec::new(), + }; + let mut out = vec![InputEvent::Key { key, modifiers, repeat }]; + // A typing key is the key, then the text it typed; a Ctrl or Alt chord is the key alone. + if let KeyCode::Char(c) = event.code + && !modifiers.ctrl + && !modifiers.alt + { + out.push(InputEvent::Text(c.to_string())); + } + out +} + +fn button(button: MouseButton) -> PointerButton { + match button { + MouseButton::Left => PointerButton::Primary, + MouseButton::Right => PointerButton::Secondary, + MouseButton::Middle => PointerButton::Middle, + } +} + +fn mouse_event(event: &MouseEvent) -> InputEvent { + // A terminal cell (col, row) is the point at its centre, the point paint covers a cell by. + let at = (f32::from(event.column) + 0.5, f32::from(event.row) + 0.5); + let modifiers = modifiers(event.modifiers); + let wheel = |delta| InputEvent::Wheel { at, delta, unit: WheelUnit::Lines, modifiers }; + match event.kind { + MouseEventKind::Down(b) => InputEvent::PointerDown { at, button: button(b), modifiers }, + MouseEventKind::Up(b) => InputEvent::PointerUp { at, button: button(b), modifiers }, + MouseEventKind::Drag(_) | MouseEventKind::Moved => InputEvent::PointerMove { at, modifiers }, + MouseEventKind::ScrollDown => wheel((0.0, 1.0)), + MouseEventKind::ScrollUp => wheel((0.0, -1.0)), + MouseEventKind::ScrollRight => wheel((1.0, 0.0)), + MouseEventKind::ScrollLeft => wheel((-1.0, 0.0)), + } +} diff --git a/crates/thing-tui/src/lib.rs b/crates/thing-tui/src/lib.rs index 3763786..10216b3 100644 --- a/crates/thing-tui/src/lib.rs +++ b/crates/thing-tui/src/lib.rs @@ -1,12 +1,18 @@ -//! The pure half of the terminal backend: render commands become a headless cell `Screen`, and two -//! screens become the minimal terminal operations between them. Nothing here touches a terminal, -//! measures a width or breaks a line: every width arrives in a `CellText`, and the layout the -//! commands were made from is thing-core's. +//! The terminal backend. The pure half: render commands become a headless cell `Screen`, and two +//! screens become the minimal terminal operations between them. The live half: `Terminal` owns the +//! terminal's mode and bytes, and `translate` maps terminal events to core's `InputEvent`. Neither +//! half measures a width, breaks a line or composes a pipeline stage, and there is no run loop +//! here: the host owns the loop and the clock (`examples/fixture.rs` is the reference host), and +//! the layout the commands were made from is thing-core's. mod diff; +mod input; mod paint; mod screen; +mod terminal; pub use diff::{Op, diff}; +pub use input::translate; pub use paint::{Painted, Representation, paint, representation}; pub use screen::{Cell, Screen}; +pub use terminal::{Terminal, write_enter, write_restore}; diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs new file mode 100644 index 0000000..cbb0a97 --- /dev/null +++ b/crates/thing-tui/src/terminal.rs @@ -0,0 +1,170 @@ +//! The terminal's mode and bytes. `Terminal` is the guard (raw mode, alternate screen, hidden +//! cursor, mouse, focus and paste reporting, all undone when it drops, and by a panic hook chained +//! ahead of the previous one) and the writer that serializes `diff`'s operations as one +//! synchronized update per frame. It decides nothing about what is drawn. + +use std::io::{self, Write}; + +use crossterm::cursor::{Hide, MoveTo, Show}; +use crossterm::event::{ + DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste, EnableFocusChange, EnableMouseCapture, +}; +use crossterm::queue; +use crossterm::style::{Attribute, Color, Print, SetAttribute, SetBackgroundColor, SetForegroundColor}; +use crossterm::terminal::{ + BeginSynchronizedUpdate, EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode, +}; +use thing_contract::Rgba; + +use crate::diff::Op; + +pub struct Terminal { + out: W, + /// Set once the modes are entered; `Drop` undoes them only then. + entered: bool, + raw: bool, +} + +impl Terminal> { + /// Take the terminal over: raw mode, alternate screen, hidden cursor, mouse capture, focus and + /// paste reporting, and a panic hook that gives it back before the previous hook speaks. Stdout + /// is buffered so a frame reaches the terminal in as few writes as it holds. + pub fn stdout() -> io::Result { + let terminal = Self::enter(io::BufWriter::with_capacity(1 << 16, io::stdout()))?; + install_panic_hook(); + Ok(terminal) + } +} + +impl Terminal { + /// Enter the terminal modes on `out`, raw mode included. + pub fn enter(out: W) -> io::Result { + Self::start(out, true) + } + + /// The same without raw mode, for a writer that is not a terminal (a test, a pipe): the byte + /// stream is identical and nothing global is touched. + pub fn enter_without_raw_mode(out: W) -> io::Result { + Self::start(out, false) + } + + fn start(out: W, raw: bool) -> io::Result { + // Built before anything is entered, so a failure part-way still restores on drop. + let mut terminal = Self { out, entered: true, raw: false }; + if raw { + enable_raw_mode()?; + terminal.raw = true; + } + write_enter(&mut terminal.out)?; + terminal.out.flush()?; + Ok(terminal) + } + + /// Serialize `ops` as one synchronized update and flush once. + pub fn draw(&mut self, ops: &[Op]) -> io::Result<()> { + queue!(self.out, BeginSynchronizedUpdate)?; + for op in ops { + match op { + Op::MoveTo(col, row) => queue!(self.out, MoveTo(clamp(*col), clamp(*row)))?, + Op::Style(fg, bg, style) => queue!( + self.out, + SetForegroundColor(color(fg)), + SetBackgroundColor(color(bg)), + SetAttribute(if style.bold { Attribute::Bold } else { Attribute::NormalIntensity }), + SetAttribute(if style.italic { Attribute::Italic } else { Attribute::NoItalic }), + SetAttribute(if style.underline { Attribute::Underlined } else { Attribute::NoUnderline }), + )?, + Op::Print(text) => queue!(self.out, Print(text))?, + } + } + queue!(self.out, EndSynchronizedUpdate)?; + self.out.flush() + } +} + +impl Drop for Terminal { + fn drop(&mut self) { + if !std::mem::take(&mut self.entered) { + return; + } + let _ = write_restore(&mut self.out).and_then(|()| self.out.flush()); + if std::mem::take(&mut self.raw) { + let _ = disable_raw_mode(); + } + } +} + +fn clamp(n: usize) -> u16 { + u16::try_from(n).unwrap_or(u16::MAX) +} + +/// Paint already composited alpha; `None` is the terminal's own colour. +fn color(c: &Option) -> Color { + match c { + Some(c) => Color::Rgb { r: c.r, g: c.g, b: c.b }, + None => Color::Reset, + } +} + +/// crossterm 0.29 refuses bracketed paste on the legacy Windows console API; there a paste +/// arrives as key events, so the refusal is not a failure. +fn tolerate(result: io::Result<()>) -> io::Result<()> { + match result { + Err(error) if error.kind() == io::ErrorKind::Unsupported => Ok(()), + other => other, + } +} + +/// The bytes that enter the modes (raw mode is not a byte sequence and is set apart). +pub fn write_enter(out: &mut W) -> io::Result<()> { + queue!(out, EnterAlternateScreen, Hide, EnableMouseCapture, EnableFocusChange)?; + tolerate(queue!(out, EnableBracketedPaste)) +} + +/// The bytes that undo `write_enter`, every one attempted even when an earlier one failed. +pub fn write_restore(out: &mut W) -> io::Result<()> { + let paste = tolerate(queue!(out, DisableBracketedPaste)); + let rest = queue!(out, DisableFocusChange, DisableMouseCapture, Show, LeaveAlternateScreen); + paste.and(rest) +} + +/// Chain a hook ahead of the current one that gives the terminal back before the panic message +/// is printed, so the message lands on the user's screen and not the alternate one. +fn install_panic_hook() { + chain_panic_hook(|| { + let _ = disable_raw_mode(); + let mut out = io::stdout(); + let _ = write_restore(&mut out); + let _ = out.flush(); + }); +} + +/// Run `first` at every panic, then whatever hook was installed before. +fn chain_panic_hook(first: impl Fn() + Send + Sync + 'static) { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + first(); + previous(info); + })); +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::chain_panic_hook; + + static ORDER: Mutex> = Mutex::new(Vec::new()); + + /// The only test in this binary that panics, so the global hook is its own. + #[test] + fn the_restore_runs_before_the_previous_hook() { + let original = std::panic::take_hook(); + std::panic::set_hook(Box::new(|_| ORDER.lock().unwrap().push("previous"))); + chain_panic_hook(|| ORDER.lock().unwrap().push("restore")); + let caught = std::panic::catch_unwind(|| panic!("forced")); + std::panic::set_hook(original); + assert!(caught.is_err()); + assert_eq!(*ORDER.lock().unwrap(), ["restore", "previous"]); + } +} diff --git a/crates/thing-tui/tests/input.rs b/crates/thing-tui/tests/input.rs new file mode 100644 index 0000000..b0ff239 --- /dev/null +++ b/crates/thing-tui/tests/input.rs @@ -0,0 +1,217 @@ +//! `translate`: every crossterm event kind and key kind, with what core is told. Order is part of +//! the contract: a typing key is the key, then its text. + +use crossterm::event::{ + Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MediaKeyCode, ModifierKeyCode, MouseButton, MouseEvent, MouseEventKind, +}; +use thing_core::input::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; +use thing_tui::translate; + +const NONE: Modifiers = Modifiers { shift: false, ctrl: false, alt: false, meta: false }; + +fn key(code: KeyCode, modifiers: KeyModifiers, kind: KeyEventKind) -> Event { + Event::Key(KeyEvent::new_with_kind(code, modifiers, kind)) +} + +fn press(code: KeyCode) -> Event { + key(code, KeyModifiers::NONE, KeyEventKind::Press) +} + +fn mouse(kind: MouseEventKind, column: u16, row: u16, modifiers: KeyModifiers) -> Event { + Event::Mouse(MouseEvent { kind, column, row, modifiers }) +} + +fn only_key(key: Key) -> Vec { + vec![InputEvent::Key { key, modifiers: NONE, repeat: false }] +} + +#[test] +fn every_named_key_maps_and_types_no_text() { + let table = [ + (KeyCode::Enter, Key::Enter), + (KeyCode::Tab, Key::Tab), + (KeyCode::Backspace, Key::Backspace), + (KeyCode::Delete, Key::Delete), + (KeyCode::Esc, Key::Escape), + (KeyCode::Left, Key::Left), + (KeyCode::Right, Key::Right), + (KeyCode::Up, Key::Up), + (KeyCode::Down, Key::Down), + (KeyCode::Home, Key::Home), + (KeyCode::End, Key::End), + (KeyCode::PageUp, Key::PageUp), + (KeyCode::PageDown, Key::PageDown), + (KeyCode::Insert, Key::Insert), + (KeyCode::F(1), Key::F(1)), + (KeyCode::F(12), Key::F(12)), + ]; + for (code, expected) in table { + assert_eq!(translate(&press(code)), only_key(expected), "{code:?}"); + } +} + +#[test] +fn keys_core_has_no_name_for_map_to_nothing() { + let unnamed = [ + KeyCode::Null, + KeyCode::CapsLock, + KeyCode::ScrollLock, + KeyCode::NumLock, + KeyCode::PrintScreen, + KeyCode::Pause, + KeyCode::Menu, + KeyCode::KeypadBegin, + KeyCode::Media(MediaKeyCode::Play), + KeyCode::Modifier(ModifierKeyCode::LeftShift), + ]; + for code in unnamed { + assert_eq!(translate(&press(code)), Vec::new(), "{code:?}"); + } +} + +#[test] +fn press_and_repeat_map_and_release_returns_nothing() { + let a = KeyCode::Left; + assert_eq!(translate(&key(a, KeyModifiers::NONE, KeyEventKind::Press)), only_key(Key::Left)); + assert_eq!( + translate(&key(a, KeyModifiers::NONE, KeyEventKind::Repeat)), + vec![InputEvent::Key { key: Key::Left, modifiers: NONE, repeat: true }] + ); + assert_eq!(translate(&key(a, KeyModifiers::NONE, KeyEventKind::Release)), Vec::new()); + // A released typing key types nothing either. + assert_eq!(translate(&key(KeyCode::Char('a'), KeyModifiers::NONE, KeyEventKind::Release)), Vec::new()); +} + +#[test] +fn a_typing_key_is_the_key_then_its_text() { + let events = translate(&press(KeyCode::Char('a'))); + assert_eq!(events, vec![InputEvent::Key { key: Key::Char('a'), modifiers: NONE, repeat: false }, InputEvent::Text("a".into())]); + // A repeat types again, and says it repeats. + let events = translate(&key(KeyCode::Char('a'), KeyModifiers::NONE, KeyEventKind::Repeat)); + assert_eq!(events[0], InputEvent::Key { key: Key::Char('a'), modifiers: NONE, repeat: true }); + assert_eq!(events[1], InputEvent::Text("a".into())); + // Shift+a: the layout's character, shift carried. + let events = translate(&key(KeyCode::Char('A'), KeyModifiers::SHIFT, KeyEventKind::Press)); + assert_eq!( + events, + vec![InputEvent::Key { key: Key::Char('A'), modifiers: Modifiers { shift: true, ..NONE }, repeat: false }, InputEvent::Text("A".into())] + ); + // A character outside the BMP is one Text. + let events = translate(&press(KeyCode::Char('\u{1F600}'))); + assert_eq!(events[1], InputEvent::Text("\u{1F600}".into())); +} + +#[test] +fn a_ctrl_or_alt_chord_is_the_key_alone() { + let ctrl = translate(&key(KeyCode::Char('c'), KeyModifiers::CONTROL, KeyEventKind::Press)); + assert_eq!(ctrl, vec![InputEvent::Key { key: Key::Char('c'), modifiers: Modifiers { ctrl: true, ..NONE }, repeat: false }]); + let alt = translate(&key(KeyCode::Char('x'), KeyModifiers::ALT, KeyEventKind::Press)); + assert_eq!(alt, vec![InputEvent::Key { key: Key::Char('x'), modifiers: Modifiers { alt: true, ..NONE }, repeat: false }]); + // Super alone does not stop the text: only Ctrl and Alt make a chord. + let meta = translate(&key(KeyCode::Char('m'), KeyModifiers::SUPER, KeyEventKind::Press)); + assert_eq!(meta.len(), 2); +} + +#[test] +fn modifiers_are_carried_each_on_its_own() { + let held = KeyModifiers::SHIFT | KeyModifiers::CONTROL; + let events = translate(&key(KeyCode::Up, held, KeyEventKind::Press)); + assert_eq!(events, vec![InputEvent::Key { key: Key::Up, modifiers: Modifiers { shift: true, ctrl: true, ..NONE }, repeat: false }]); + for (flag, expected) in [ + (KeyModifiers::SHIFT, Modifiers { shift: true, ..NONE }), + (KeyModifiers::CONTROL, Modifiers { ctrl: true, ..NONE }), + (KeyModifiers::ALT, Modifiers { alt: true, ..NONE }), + (KeyModifiers::SUPER, Modifiers { meta: true, ..NONE }), + (KeyModifiers::META, Modifiers { meta: true, ..NONE }), + (KeyModifiers::HYPER, NONE), + ] { + let events = translate(&key(KeyCode::Down, flag, KeyEventKind::Press)); + assert_eq!(events, vec![InputEvent::Key { key: Key::Down, modifiers: expected, repeat: false }], "{flag:?}"); + } +} + +#[test] +fn back_tab_is_tab_with_shift() { + let events = translate(&press(KeyCode::BackTab)); + assert_eq!(events, vec![InputEvent::Key { key: Key::Tab, modifiers: Modifiers { shift: true, ..NONE }, repeat: false }]); + // Shift already held stays shift, and is not doubled into anything else. + let events = translate(&key(KeyCode::BackTab, KeyModifiers::SHIFT, KeyEventKind::Press)); + assert_eq!(events, vec![InputEvent::Key { key: Key::Tab, modifiers: Modifiers { shift: true, ..NONE }, repeat: false }]); +} + +#[test] +fn a_click_lands_on_its_cells_centre() { + let at = (3.5, 4.5); + let down = translate(&mouse(MouseEventKind::Down(MouseButton::Left), 3, 4, KeyModifiers::NONE)); + assert_eq!(down, vec![InputEvent::PointerDown { at, button: PointerButton::Primary, modifiers: NONE }]); + let up = translate(&mouse(MouseEventKind::Up(MouseButton::Right), 3, 4, KeyModifiers::CONTROL)); + assert_eq!(up, vec![InputEvent::PointerUp { at, button: PointerButton::Secondary, modifiers: Modifiers { ctrl: true, ..NONE } }]); + let middle = translate(&mouse(MouseEventKind::Down(MouseButton::Middle), 0, 0, KeyModifiers::NONE)); + assert_eq!(middle, vec![InputEvent::PointerDown { at: (0.5, 0.5), button: PointerButton::Middle, modifiers: NONE }]); +} + +#[test] +fn drag_and_move_are_pointer_moves() { + let at = (10.5, 2.5); + for kind in [MouseEventKind::Drag(MouseButton::Left), MouseEventKind::Drag(MouseButton::Right), MouseEventKind::Moved] { + let events = translate(&mouse(kind, 10, 2, KeyModifiers::SHIFT)); + assert_eq!(events, vec![InputEvent::PointerMove { at, modifiers: Modifiers { shift: true, ..NONE } }], "{kind:?}"); + } +} + +#[test] +fn the_wheel_is_lines_with_the_dom_sign() { + let at = (5.5, 6.5); + for (kind, delta) in [ + (MouseEventKind::ScrollDown, (0.0, 1.0)), + (MouseEventKind::ScrollUp, (0.0, -1.0)), + (MouseEventKind::ScrollRight, (1.0, 0.0)), + (MouseEventKind::ScrollLeft, (-1.0, 0.0)), + ] { + let events = translate(&mouse(kind, 5, 6, KeyModifiers::ALT)); + assert_eq!(events, vec![InputEvent::Wheel { at, delta, unit: WheelUnit::Lines, modifiers: Modifiers { alt: true, ..NONE } }], "{kind:?}"); + } +} + +#[test] +fn focus_paste_and_resize() { + assert_eq!(translate(&Event::FocusGained), vec![InputEvent::Focus(true)]); + assert_eq!(translate(&Event::FocusLost), vec![InputEvent::Focus(false)]); + assert_eq!(translate(&Event::Paste("two\nlines".into())), vec![InputEvent::Text("two\nlines".into())]); + assert_eq!(translate(&Event::Resize(80, 24)), Vec::new()); +} + +#[test] +fn a_terminal_never_composes_or_cancels() { + let everything = [ + press(KeyCode::Char('a')), + mouse(MouseEventKind::Moved, 1, 1, KeyModifiers::NONE), + Event::FocusLost, + Event::Paste("p".into()), + Event::Resize(1, 1), + ]; + for event in &everything { + for produced in translate(event) { + assert!(!matches!(produced, InputEvent::Compose { .. } | InputEvent::PointerCancel), "{event:?} gave {produced:?}"); + } + } +} + +/// A burst in the order the terminal sent it comes out in that order, with a resize between two +/// keys leaving no trace, so the host's drain keeps the user's order and loses only the resize. +#[test] +fn a_burst_keeps_its_order() { + let burst = [ + press(KeyCode::Char('a')), + Event::Resize(90, 30), + mouse(MouseEventKind::Down(MouseButton::Left), 1, 1, KeyModifiers::NONE), + key(KeyCode::Char('a'), KeyModifiers::NONE, KeyEventKind::Release), + press(KeyCode::Enter), + ]; + let events: Vec = burst.iter().flat_map(translate).collect(); + assert_eq!(events.len(), 4); + assert!(matches!(events[0], InputEvent::Key { key: Key::Char('a'), .. })); + assert_eq!(events[1], InputEvent::Text("a".into())); + assert!(matches!(events[2], InputEvent::PointerDown { .. })); + assert!(matches!(events[3], InputEvent::Key { key: Key::Enter, .. })); +} diff --git a/crates/thing-tui/tests/pipeline.rs b/crates/thing-tui/tests/pipeline.rs new file mode 100644 index 0000000..5bb5f62 --- /dev/null +++ b/crates/thing-tui/tests/pipeline.rs @@ -0,0 +1,127 @@ +//! The live path with the writer replaced: f01 through `Core::frame`, `paint` and `diff`, the same +//! three calls the reference host makes each frame. The screen it reaches is cut 8a's golden. + +use std::path::PathBuf; + +use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers}; +use thing_contract::RecordKey; +use thing_core::input::InputEvent; +use thing_core::layout::Metrics; +use thing_core::text::CellMeasure; +use thing_core::time::Timestamp; +use thing_core::{Config, Core, FrameInput, Ports}; +use thing_testkit::fixture::Fixture; +use thing_testkit::golden; +use thing_testkit::ids::SeqIds; +use thing_testkit::mem_state::MemState; +use thing_testkit::state; +use thing_tui::{Op, Screen, Terminal, diff, paint, translate}; + +struct Host { + core: Core, + state: MemState, + ids: SeqIds, + shown: Screen, + key: String, +} + +impl Host { + fn new(fixture: Fixture) -> Self { + let set = fixture.load(); + let surface = &set.surfaces[0]; + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let mut core = Core::new(Config::new(Metrics::Cells, "renderer.tui"), Box::new(CellMeasure)); + let key = surface.record_key(); + core.show(surface.provider_id.clone(), RecordKey::new(key.clone())); + Self { core, state, ids: SeqIds::new(), shown: Screen::new(0, 0), key } + } + + /// One frame as the host runs it: the ops that take the terminal from what it shows to the frame. + fn frame(&mut self, now: i64, size: (usize, usize), events: Vec) -> Vec { + let output = self.core.frame( + FrameInput { now: Timestamp(now), viewport: (size.0 as f32, size.1 as f32), scale: 1.0, events }, + Ports { state: &mut self.state, ids: &mut self.ids }, + ); + let mut next = Screen::new(size.0, size.1); + paint(&output.commands, &mut next); + let ops = diff(&self.shown, &next); + self.shown = next; + ops + } + + fn text(&self) -> String { + format!("surface {} {}x{}\n{}", self.key, self.shown.cols, self.shown.rows, self.shown.dump()) + } +} + +fn goldens() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens") +} + +#[test] +fn f01_through_the_frame_is_cut_8as_screen_golden() { + let mut host = Host::new(Fixture::F01SwarmDashboard); + let ops = host.frame(1_000, (100, 37), Vec::new()); + assert!(!ops.is_empty(), "the first frame paints"); + let golden = golden::read(&goldens(), "screen-f01-swarm-dashboard-cells.txt"); + assert_eq!(host.text().as_bytes(), golden.as_slice()); +} + +#[test] +fn a_second_frame_with_nothing_new_draws_nothing() { + let mut host = Host::new(Fixture::F01SwarmDashboard); + host.frame(1_000, (100, 37), Vec::new()); + assert_eq!(host.frame(1_016, (100, 37), Vec::new()), Vec::new()); +} + +#[test] +fn the_first_frames_ops_replay_to_the_same_bytes_as_a_full_repaint() { + let mut host = Host::new(Fixture::F01SwarmDashboard); + let ops = host.frame(1_000, (100, 37), Vec::new()); + assert_eq!(ops, diff(&Screen::new(0, 0), &host.shown)); + // The writer takes exactly those ops: one synchronized update, flushed once. + let mut out = Vec::new(); + let mut terminal = Terminal::enter_without_raw_mode(&mut out).unwrap(); + terminal.draw(&ops).unwrap(); + drop(terminal); + assert!(out.windows(8).any(|w| w == b"\x1b[?2026h")); +} + +/// The size read at a frame is that frame's viewport: after a resize the screen is the one a host +/// that started at the new size draws, and the diff repaints rather than patches. +#[test] +fn a_resize_is_the_next_frames_viewport() { + let mut host = Host::new(Fixture::F01SwarmDashboard); + host.frame(1_000, (100, 37), Vec::new()); + let ops = host.frame(1_016, (80, 24), Vec::new()); + assert_eq!((host.shown.cols, host.shown.rows), (80, 24)); + assert!(!ops.is_empty()); + + let mut fresh = Host::new(Fixture::F01SwarmDashboard); + fresh.frame(1_000, (80, 24), Vec::new()); + assert_eq!(host.text(), fresh.text()); + + // And back: the viewport is read each frame, never kept from the last. + host.frame(1_032, (100, 37), Vec::new()); + let golden = golden::read(&goldens(), "screen-f01-swarm-dashboard-cells.txt"); + assert_eq!(host.text().as_bytes(), golden.as_slice()); +} + +/// Events drained from the terminal reach `frame` in the order they came, translated by the same +/// function the host calls; a resize in the burst is not an event, and a frame holding them +/// draws the same screen it would have drawn without. +#[test] +fn drained_events_feed_the_frame_in_order() { + let burst = [ + Event::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)), + Event::Resize(100, 37), + Event::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)), + ]; + let events: Vec = burst.iter().flat_map(translate).collect(); + assert_eq!(events.len(), 3); + let mut host = Host::new(Fixture::F01SwarmDashboard); + host.frame(1_000, (100, 37), events); + let golden = golden::read(&goldens(), "screen-f01-swarm-dashboard-cells.txt"); + assert_eq!(host.text().as_bytes(), golden.as_slice()); +} diff --git a/crates/thing-tui/tests/terminal.rs b/crates/thing-tui/tests/terminal.rs new file mode 100644 index 0000000..79aa4b8 --- /dev/null +++ b/crates/thing-tui/tests/terminal.rs @@ -0,0 +1,168 @@ +//! The writer's bytes and the guard's restore sequence, on a writer that is a `Vec` behind a +//! handle: nothing here touches a terminal. + +use std::io::{self, Write}; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::{Arc, Mutex}; + +use thing_contract::Rgba; +use thing_core::layout::CellStyle; +use thing_tui::{Op, Screen, Terminal, diff, write_enter, write_restore}; + +/// A writer the test keeps a handle on after the terminal that owns it is gone. +#[derive(Clone, Default)] +struct Shared(Arc>>); + +impl Shared { + fn bytes(&self) -> Vec { + self.0.lock().unwrap().clone() + } +} + +impl Write for Shared { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +fn has(bytes: &[u8], needle: &str) -> bool { + bytes.windows(needle.len()).any(|w| w == needle.as_bytes()) +} + +fn count(bytes: &[u8], needle: &str) -> usize { + bytes.windows(needle.len()).filter(|w| *w == needle.as_bytes()).count() +} + +/// The bytes one `draw` writes, after the guard's own entering sequence. +fn drawn(ops: &[Op]) -> Vec { + let out = Shared::default(); + let mut terminal = Terminal::enter_without_raw_mode(out.clone()).unwrap(); + let before = out.bytes().len(); + terminal.draw(ops).unwrap(); + out.bytes()[before..].to_vec() +} + +fn rgb(r: u8, g: u8, b: u8) -> Option { + Some(Rgba { r, g, b, a: 255 }) +} + +#[test] +fn a_one_cell_diff_is_one_synchronized_update_with_one_move() { + let old = Screen::new(4, 2); + let mut new = old.clone(); + new.cells[4 + 2].glyph = "x".into(); + let ops = diff(&old, &new); + let bytes = drawn(&ops); + assert!(bytes.starts_with(b"\x1b[?2026h"), "{bytes:?}"); + assert!(bytes.ends_with(b"\x1b[?2026l"), "{bytes:?}"); + // One cursor move, to row 2 column 3 (1-based), and the glyph itself. + assert_eq!(count(&bytes, "H"), 1, "{bytes:?}"); + assert!(has(&bytes, "\x1b[2;3H"), "{bytes:?}"); + assert!(has(&bytes, "x")); +} + +#[test] +fn no_ops_still_wrap_in_a_synchronized_update_and_say_nothing_else() { + assert_eq!(drawn(&[]), b"\x1b[?2026h\x1b[?2026l"); +} + +#[test] +fn a_move_beyond_the_terminal_addressing_saturates() { + let bytes = drawn(&[Op::MoveTo(70_000, 1)]); + assert!(has(&bytes, "\x1b[2;65536H"), "{bytes:?}"); +} + +#[test] +fn style_none_resets_the_colour_and_some_is_truecolor() { + 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:?}"); + let colour = drawn(&[Op::Style(rgb(1, 2, 3), rgb(4, 5, 6), CellStyle::default())]); + assert!(has(&colour, "\x1b[38;2;1;2;3m"), "{colour:?}"); + assert!(has(&colour, "\x1b[48;2;4;5;6m"), "{colour:?}"); + // Foreground and background are not swapped. + let text = String::from_utf8(colour).unwrap(); + assert!(text.find("38;2;1;2;3").unwrap() < text.find("48;2;4;5;6").unwrap()); +} + +#[test] +fn each_attribute_is_set_and_each_absent_one_is_cleared() { + 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:?}"); + } + let on = drawn(&[Op::Style(None, None, CellStyle { bold: true, italic: true, underline: true })]); + for set in ["\x1b[1m", "\x1b[3m", "\x1b[4m"] { + assert!(has(&on, set), "{set:?} missing in {on:?}"); + } + for cleared in ["\x1b[22m", "\x1b[23m", "\x1b[24m"] { + assert!(!has(&on, cleared), "{cleared:?} present in {on:?}"); + } + // One attribute at a time: the other two stay cleared. + let bold = drawn(&[Op::Style(None, None, CellStyle { bold: true, ..CellStyle::default() })]); + assert!(has(&bold, "\x1b[1m") && has(&bold, "\x1b[23m") && has(&bold, "\x1b[24m") && !has(&bold, "\x1b[22m")); + let italic = drawn(&[Op::Style(None, None, CellStyle { italic: true, ..CellStyle::default() })]); + assert!(has(&italic, "\x1b[3m") && has(&italic, "\x1b[22m") && has(&italic, "\x1b[24m") && !has(&italic, "\x1b[23m")); + let underline = drawn(&[Op::Style(None, None, CellStyle { underline: true, ..CellStyle::default() })]); + assert!(has(&underline, "\x1b[4m") && has(&underline, "\x1b[22m") && has(&underline, "\x1b[23m") && !has(&underline, "\x1b[24m")); +} + +#[test] +fn print_writes_the_text_in_place() { + let bytes = drawn(&[Op::MoveTo(0, 0), Op::Print("h\u{e9}llo".into())]); + assert!(has(&bytes, "\x1b[1;1Hh\u{e9}llo"), "{bytes:?}"); +} + +const ENTER: [&str; 5] = ["\x1b[?1049h", "\x1b[?25l", "\x1b[?1000h", "\x1b[?1004h", "\x1b[?2004h"]; +const RESTORE: [&str; 5] = ["\x1b[?2004l", "\x1b[?1004l", "\x1b[?1000l", "\x1b[?25h", "\x1b[?1049l"]; + +#[test] +fn entering_writes_every_mode_and_restoring_undoes_each() { + let mut entered = Vec::new(); + write_enter(&mut entered).unwrap(); + for sequence in ENTER { + assert!(has(&entered, sequence), "{sequence:?} missing from enter {entered:?}"); + } + let mut restored = Vec::new(); + write_restore(&mut restored).unwrap(); + for sequence in RESTORE { + assert!(has(&restored, sequence), "{sequence:?} missing from restore {restored:?}"); + } + // The alternate screen is left last, so the user's screen returns after the modes are off. + assert!(restored.ends_with(b"\x1b[?1049l")); +} + +#[test] +fn dropping_the_guard_restores_once() { + let out = Shared::default(); + let terminal = Terminal::enter_without_raw_mode(out.clone()).unwrap(); + for sequence in ENTER { + assert!(has(&out.bytes(), sequence), "{sequence:?}"); + } + assert!(!has(&out.bytes(), "\x1b[?1049l"), "left before the guard dropped"); + drop(terminal); + let bytes = out.bytes(); + for sequence in RESTORE { + assert!(has(&bytes, sequence), "{sequence:?} missing after drop"); + } + assert_eq!(count(&bytes, "\x1b[?1049l"), 1); +} + +#[test] +fn a_panic_unwinding_through_the_guard_restores_the_terminal() { + let out = Shared::default(); + let inner = out.clone(); + let caught = catch_unwind(AssertUnwindSafe(move || { + let _terminal = Terminal::enter_without_raw_mode(inner).unwrap(); + panic!("forced"); + })); + assert!(caught.is_err()); + let bytes = out.bytes(); + for sequence in RESTORE { + assert!(has(&bytes, sequence), "{sequence:?} missing after the panic"); + } +} -- 2.47.3 From 2ca326293cfbb9166aa0ee850278ad4ab524569d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 01:41:53 +0100 Subject: [PATCH 02/19] thing-tui: clamp a cursor move below crossterm's overflow Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index cbb0a97..b675183 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -94,8 +94,9 @@ impl Drop for Terminal { } } +/// crossterm adds one to a coordinate to make it 1-based, so the last it can write is `u16::MAX - 1`. fn clamp(n: usize) -> u16 { - u16::try_from(n).unwrap_or(u16::MAX) + u16::try_from(n).unwrap_or(u16::MAX).min(u16::MAX - 1) } /// Paint already composited alpha; `None` is the terminal's own colour. -- 2.47.3 From 4bdc125697c95ebca5eb77da12ad35feb8bd6d23 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 01:45:20 +0100 Subject: [PATCH 03/19] thing-tui: saturated move expectation Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/tests/terminal.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/thing-tui/tests/terminal.rs b/crates/thing-tui/tests/terminal.rs index 79aa4b8..81b43d3 100644 --- a/crates/thing-tui/tests/terminal.rs +++ b/crates/thing-tui/tests/terminal.rs @@ -73,7 +73,7 @@ fn no_ops_still_wrap_in_a_synchronized_update_and_say_nothing_else() { #[test] fn a_move_beyond_the_terminal_addressing_saturates() { let bytes = drawn(&[Op::MoveTo(70_000, 1)]); - assert!(has(&bytes, "\x1b[2;65536H"), "{bytes:?}"); + assert!(has(&bytes, "\x1b[2;65535H"), "{bytes:?}"); } #[test] -- 2.47.3 From 336fb892dff9f21cab2807cb26daceec51d390af Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 01:51:15 +0100 Subject: [PATCH 04/19] thing-tui: mouse capture is not a byte sequence on Windows Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/tests/terminal.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/thing-tui/tests/terminal.rs b/crates/thing-tui/tests/terminal.rs index 81b43d3..891852f 100644 --- a/crates/thing-tui/tests/terminal.rs +++ b/crates/thing-tui/tests/terminal.rs @@ -117,19 +117,26 @@ fn print_writes_the_text_in_place() { assert!(has(&bytes, "\x1b[1;1Hh\u{e9}llo"), "{bytes:?}"); } -const ENTER: [&str; 5] = ["\x1b[?1049h", "\x1b[?25l", "\x1b[?1000h", "\x1b[?1004h", "\x1b[?2004h"]; -const RESTORE: [&str; 5] = ["\x1b[?2004l", "\x1b[?1004l", "\x1b[?1000l", "\x1b[?25h", "\x1b[?1049l"]; +/// What crossterm writes as bytes. On Windows, mouse capture is a console-mode call, not an escape +/// sequence, so it is not in the stream there. +const MOUSE: bool = cfg!(not(windows)); +const ENTER: [(&str, bool); 5] = [("\x1b[?1049h", true), ("\x1b[?25l", true), ("\x1b[?1000h", MOUSE), ("\x1b[?1004h", true), ("\x1b[?2004h", true)]; +const RESTORE: [(&str, bool); 5] = [("\x1b[?2004l", true), ("\x1b[?1004l", true), ("\x1b[?1000l", MOUSE), ("\x1b[?25h", true), ("\x1b[?1049l", true)]; + +fn modes(table: [(&'static str, bool); 5]) -> impl Iterator { + table.into_iter().filter(|(_, bytes)| *bytes).map(|(sequence, _)| sequence) +} #[test] fn entering_writes_every_mode_and_restoring_undoes_each() { let mut entered = Vec::new(); write_enter(&mut entered).unwrap(); - for sequence in ENTER { + for sequence in modes(ENTER) { assert!(has(&entered, sequence), "{sequence:?} missing from enter {entered:?}"); } let mut restored = Vec::new(); write_restore(&mut restored).unwrap(); - for sequence in RESTORE { + for sequence in modes(RESTORE) { assert!(has(&restored, sequence), "{sequence:?} missing from restore {restored:?}"); } // The alternate screen is left last, so the user's screen returns after the modes are off. @@ -140,13 +147,13 @@ fn entering_writes_every_mode_and_restoring_undoes_each() { fn dropping_the_guard_restores_once() { let out = Shared::default(); let terminal = Terminal::enter_without_raw_mode(out.clone()).unwrap(); - for sequence in ENTER { + for sequence in modes(ENTER) { assert!(has(&out.bytes(), sequence), "{sequence:?}"); } assert!(!has(&out.bytes(), "\x1b[?1049l"), "left before the guard dropped"); drop(terminal); let bytes = out.bytes(); - for sequence in RESTORE { + for sequence in modes(RESTORE) { assert!(has(&bytes, sequence), "{sequence:?} missing after drop"); } assert_eq!(count(&bytes, "\x1b[?1049l"), 1); @@ -162,7 +169,7 @@ fn a_panic_unwinding_through_the_guard_restores_the_terminal() { })); assert!(caught.is_err()); let bytes = out.bytes(); - for sequence in RESTORE { + for sequence in modes(RESTORE) { assert!(has(&bytes, sequence), "{sequence:?} missing after the panic"); } } -- 2.47.3 From f1c5978d77d1effff69a1632da31fee36a3e33a6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 01:52:25 +0100 Subject: [PATCH 05/19] thing-tui: a draw of no ops writes nothing Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 5 ++++- crates/thing-tui/tests/terminal.rs | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index b675183..5fbdb25 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -60,8 +60,11 @@ impl Terminal { Ok(terminal) } - /// Serialize `ops` as one synchronized update and flush once. + /// Serialize `ops` as one synchronized update and flush once. No ops write nothing. pub fn draw(&mut self, ops: &[Op]) -> io::Result<()> { + if ops.is_empty() { + return Ok(()); + } queue!(self.out, BeginSynchronizedUpdate)?; for op in ops { match op { diff --git a/crates/thing-tui/tests/terminal.rs b/crates/thing-tui/tests/terminal.rs index 891852f..28372d4 100644 --- a/crates/thing-tui/tests/terminal.rs +++ b/crates/thing-tui/tests/terminal.rs @@ -66,8 +66,8 @@ fn a_one_cell_diff_is_one_synchronized_update_with_one_move() { } #[test] -fn no_ops_still_wrap_in_a_synchronized_update_and_say_nothing_else() { - assert_eq!(drawn(&[]), b"\x1b[?2026h\x1b[?2026l"); +fn no_ops_write_nothing() { + assert_eq!(drawn(&[]), Vec::::new()); } #[test] -- 2.47.3 From 482fdd42cfb6f70d7afb68b22a81796bc5fa087c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 01:56:14 +0100 Subject: [PATCH 06/19] thing-tui: pin tolerate and the meta modifiers Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 12 +++++++++++- crates/thing-tui/tests/input.rs | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 5fbdb25..17dfc9e 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -156,7 +156,9 @@ fn chain_panic_hook(first: impl Fn() + Send + Sync + 'static) { mod tests { use std::sync::Mutex; - use super::chain_panic_hook; + use std::io; + + use super::{chain_panic_hook, tolerate}; static ORDER: Mutex> = Mutex::new(Vec::new()); @@ -171,4 +173,12 @@ mod tests { assert!(caught.is_err()); assert_eq!(*ORDER.lock().unwrap(), ["restore", "previous"]); } + + #[test] + fn only_an_unsupported_mode_is_tolerated() { + assert!(tolerate(Ok(())).is_ok()); + assert!(tolerate(Err(io::Error::from(io::ErrorKind::Unsupported))).is_ok()); + let other = tolerate(Err(io::Error::from(io::ErrorKind::BrokenPipe))).unwrap_err(); + assert_eq!(other.kind(), io::ErrorKind::BrokenPipe); + } } diff --git a/crates/thing-tui/tests/input.rs b/crates/thing-tui/tests/input.rs index b0ff239..b5938c0 100644 --- a/crates/thing-tui/tests/input.rs +++ b/crates/thing-tui/tests/input.rs @@ -123,6 +123,7 @@ fn modifiers_are_carried_each_on_its_own() { (KeyModifiers::ALT, Modifiers { alt: true, ..NONE }), (KeyModifiers::SUPER, Modifiers { meta: true, ..NONE }), (KeyModifiers::META, Modifiers { meta: true, ..NONE }), + (KeyModifiers::SUPER | KeyModifiers::META, Modifiers { meta: true, ..NONE }), (KeyModifiers::HYPER, NONE), ] { let events = translate(&key(KeyCode::Down, flag, KeyEventKind::Press)); -- 2.47.3 From 945ec1a30ddef2f1809bf8d32ded476e0e61818a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:09:38 +0100 Subject: [PATCH 07/19] thing-tui: the panic hook restores only a live guard, on the thread that owns it A guard registers when entered and unregisters on drop; the hook restores through the registered guard's own writer, claims the restore once so unwinding does not repeat it, and leaves a panic on any other thread, or after the drop, to the previous hook. Every constructor that enters installs the hook. Per the steward's decision on thing2:finding:cut-tui-host.s1.panic-hook-owner-blind. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 163 +++++++++++-------- crates/thing-tui/src/terminal/guard_tests.rs | 120 ++++++++++++++ crates/thing-tui/tests/pipeline.rs | 15 +- 3 files changed, 216 insertions(+), 82 deletions(-) create mode 100644 crates/thing-tui/src/terminal/guard_tests.rs diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 17dfc9e..56b68e0 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -1,9 +1,12 @@ //! The terminal's mode and bytes. `Terminal` is the guard (raw mode, alternate screen, hidden -//! cursor, mouse, focus and paste reporting, all undone when it drops, and by a panic hook chained -//! ahead of the previous one) and the writer that serializes `diff`'s operations as one -//! synchronized update per frame. It decides nothing about what is drawn. +//! cursor, mouse, focus and paste reporting, all undone when it drops, or by a panic on the thread +//! that owns it) and the writer that serializes `diff`'s operations as one synchronized update per +//! frame. It decides nothing about what is drawn. use std::io::{self, Write}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, Once, PoisonError, TryLockError}; +use std::thread::{self, ThreadId}; use crossterm::cursor::{Hide, MoveTo, Show}; use crossterm::event::{ @@ -18,82 +21,124 @@ use thing_contract::Rgba; use crate::diff::Op; -pub struct Terminal { - out: W, - /// Set once the modes are entered; `Drop` undoes them only then. - entered: bool, +/// What a guard holds, shared with the panic hook through `GUARDS`. `entered` is claimed by whichever +/// restores first (the hook on a panic, `Drop` otherwise), so the restore is written once. +struct Shared { + out: Mutex, + entered: AtomicBool, raw: bool, } -impl Terminal> { - /// Take the terminal over: raw mode, alternate screen, hidden cursor, mouse capture, focus and - /// paste reporting, and a panic hook that gives it back before the previous hook speaks. Stdout - /// is buffered so a frame reaches the terminal in as few writes as it holds. - pub fn stdout() -> io::Result { - let terminal = Self::enter(io::BufWriter::with_capacity(1 << 16, io::stdout()))?; - install_panic_hook(); - Ok(terminal) +trait Restore: Send + Sync { + fn restore(&self); +} + +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. Leave that restore to `Drop`, which runs once the unwinding has released it. + let mut out = match self.out.try_lock() { + Ok(out) => out, + Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), + Err(TryLockError::WouldBlock) => return, + }; + if !self.entered.swap(false, Ordering::SeqCst) { + return; + } + let _ = write_restore(&mut *out).and_then(|()| out.flush()); + if self.raw { + let _ = disable_raw_mode(); + } } } -impl Terminal { - /// Enter the terminal modes on `out`, raw mode included. +/// 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 HOOK: Once = Once::new(); + +fn guards() -> MutexGuard<'static, Vec<(ThreadId, Arc)>> { + GUARDS.lock().unwrap_or_else(PoisonError::into_inner) +} + +pub struct Terminal { + shared: Arc>, +} + +impl Terminal> { + /// Take the terminal over on stdout, buffered so a frame reaches the terminal in as few writes + /// as it holds. See `enter` for what that does. + pub fn stdout() -> io::Result { + Self::enter(io::BufWriter::with_capacity(1 << 16, io::stdout())) + } +} + +impl Terminal { + /// Enter the terminal modes on `out`: raw mode, alternate screen, hidden cursor, mouse capture, + /// focus and paste reporting. Until the guard drops, a panic on this thread gives the 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. pub fn enter(out: W) -> io::Result { Self::start(out, true) } - /// The same without raw mode, for a writer that is not a terminal (a test, a pipe): the byte - /// stream is identical and nothing global is touched. + /// The same without raw mode, for a writer that is not a terminal (a test, a pipe). pub fn enter_without_raw_mode(out: W) -> io::Result { Self::start(out, false) } fn start(out: W, raw: bool) -> io::Result { - // Built before anything is entered, so a failure part-way still restores on drop. - let mut terminal = Self { out, entered: true, raw: false }; + HOOK.call_once(install_panic_hook); if raw { enable_raw_mode()?; - terminal.raw = true; } - write_enter(&mut terminal.out)?; - terminal.out.flush()?; + // 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 terminal = Self { shared }; + { + let mut out = terminal.out(); + write_enter(&mut *out)?; + out.flush()?; + } Ok(terminal) } + fn out(&self) -> MutexGuard<'_, W> { + self.shared.out.lock().unwrap_or_else(PoisonError::into_inner) + } + /// Serialize `ops` as one synchronized update and flush once. No ops write nothing. pub fn draw(&mut self, ops: &[Op]) -> io::Result<()> { if ops.is_empty() { return Ok(()); } - queue!(self.out, BeginSynchronizedUpdate)?; + let mut out = self.out(); + queue!(out, BeginSynchronizedUpdate)?; for op in ops { match op { - Op::MoveTo(col, row) => queue!(self.out, MoveTo(clamp(*col), clamp(*row)))?, + Op::MoveTo(col, row) => queue!(out, MoveTo(clamp(*col), clamp(*row)))?, Op::Style(fg, bg, style) => queue!( - self.out, + out, SetForegroundColor(color(fg)), SetBackgroundColor(color(bg)), SetAttribute(if style.bold { Attribute::Bold } else { Attribute::NormalIntensity }), SetAttribute(if style.italic { Attribute::Italic } else { Attribute::NoItalic }), SetAttribute(if style.underline { Attribute::Underlined } else { Attribute::NoUnderline }), )?, - Op::Print(text) => queue!(self.out, Print(text))?, + Op::Print(text) => queue!(out, Print(text))?, } } - queue!(self.out, EndSynchronizedUpdate)?; - self.out.flush() + queue!(out, EndSynchronizedUpdate)?; + out.flush() } } -impl Drop for Terminal { +impl Drop for Terminal { fn drop(&mut self) { - if !std::mem::take(&mut self.entered) { - return; - } - let _ = write_restore(&mut self.out).and_then(|()| self.out.flush()); - if std::mem::take(&mut self.raw) { - let _ = disable_raw_mode(); - } + guards().retain(|(_, guard)| !std::ptr::addr_eq(Arc::as_ptr(guard), Arc::as_ptr(&self.shared))); + self.shared.restore(); } } @@ -132,47 +177,26 @@ pub fn write_restore(out: &mut W) -> io::Result<()> { paste.and(rest) } -/// Chain a hook ahead of the current one that gives the terminal back before the panic message -/// is printed, so the message lands on the user's screen and not the alternate one. +/// 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. fn install_panic_hook() { - chain_panic_hook(|| { - let _ = disable_raw_mode(); - let mut out = io::stdout(); - let _ = write_restore(&mut out); - let _ = out.flush(); - }); -} - -/// Run `first` at every panic, then whatever hook was installed before. -fn chain_panic_hook(first: impl Fn() + Send + Sync + 'static) { let previous = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { - first(); + let here = thread::current().id(); + let owned: Vec> = guards().iter().filter(|(owner, _)| *owner == here).map(|(_, guard)| guard.clone()).collect(); + for guard in owned { + guard.restore(); + } previous(info); })); } #[cfg(test)] mod tests { - use std::sync::Mutex; - use std::io; - use super::{chain_panic_hook, tolerate}; - - static ORDER: Mutex> = Mutex::new(Vec::new()); - - /// The only test in this binary that panics, so the global hook is its own. - #[test] - fn the_restore_runs_before_the_previous_hook() { - let original = std::panic::take_hook(); - std::panic::set_hook(Box::new(|_| ORDER.lock().unwrap().push("previous"))); - chain_panic_hook(|| ORDER.lock().unwrap().push("restore")); - let caught = std::panic::catch_unwind(|| panic!("forced")); - std::panic::set_hook(original); - assert!(caught.is_err()); - assert_eq!(*ORDER.lock().unwrap(), ["restore", "previous"]); - } + use super::tolerate; #[test] fn only_an_unsupported_mode_is_tolerated() { @@ -182,3 +206,6 @@ mod tests { assert_eq!(other.kind(), io::ErrorKind::BrokenPipe); } } + +#[cfg(test)] +mod guard_tests; diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs new file mode 100644 index 0000000..b3faca7 --- /dev/null +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -0,0 +1,120 @@ +//! The guard and its panic hook, on writers that are not terminals. The hook is process-global, so +//! these tests set a spy as the "previous hook" before any guard is built: it snapshots the watched +//! writer at the moment the chained hook hands over, which is how a test tells the hook's restore +//! from the one `Drop` makes later during unwinding. + +use std::cell::RefCell; +use std::io::{self, Write}; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::{Arc, Mutex, Once}; + +use super::Terminal; + +/// A writer the test keeps a handle on after the terminal that owns it is gone. +#[derive(Clone, Default)] +struct Shared(Arc>>); + +impl Shared { + fn bytes(&self) -> Vec { + self.0.lock().unwrap().clone() + } +} + +impl Write for Shared { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +thread_local! { + /// The writer of the guard this test thread watches, and what it held when the hook handed over. + static WATCH: RefCell> = const { RefCell::new(None) }; + static AT_HAND_OVER: RefCell>> = const { RefCell::new(None) }; +} + +static SPY: Once = Once::new(); + +/// 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() { + SPY.call_once(|| { + let original = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + WATCH.with(|watch| { + if let Some(out) = watch.borrow().as_ref() { + AT_HAND_OVER.with(|seen| *seen.borrow_mut() = Some(out.bytes())); + } + }); + original(info); + })); + }); +} + +fn guard(out: &Shared) -> Terminal { + spy(); + WATCH.with(|watch| *watch.borrow_mut() = Some(out.clone())); + AT_HAND_OVER.with(|seen| *seen.borrow_mut() = None); + Terminal::start(out.clone(), false).unwrap() +} + +fn count(bytes: &[u8], needle: &str) -> usize { + bytes.windows(needle.len()).filter(|w| *w == needle.as_bytes()).count() +} + +const LEAVE: &str = "\x1b[?1049l"; + +/// What the watched writer held when the previous hook was handed the panic, if one was. +fn at_hand_over() -> Option> { + AT_HAND_OVER.with(|seen| seen.borrow_mut().take()) +} + +/// A panic on the thread that owns a live guard: the chained hook has restored the terminal before +/// the previous hook is called, and the unwinding drop adds nothing. +fn owner_panics(out: &Shared) { + let caught = catch_unwind(AssertUnwindSafe(|| { + let _terminal = guard(out); + panic!("forced on the owner"); + })); + assert!(caught.is_err()); +} + +#[test] +fn a_panic_on_the_owning_thread_restores_exactly_once() { + let out = Shared::default(); + owner_panics(&out); + assert_eq!(count(&out.bytes(), LEAVE), 1); + assert_eq!(count(&out.bytes(), "\x1b[?25h"), 1); +} + +#[test] +fn a_panic_on_another_thread_leaves_the_guard_alone() { + let out = Shared::default(); + let terminal = guard(&out); + let worker = std::thread::spawn(|| panic!("forced on a worker")); + assert!(worker.join().is_err()); + assert_eq!(count(&out.bytes(), LEAVE), 0, "a worker's panic must not take the terminal from a live host"); + drop(terminal); + assert_eq!(count(&out.bytes(), LEAVE), 1); + // The owner's own panic still restores through the hook. + let again = Shared::default(); + owner_panics(&again); + assert_eq!(count(&at_hand_over().expect("hook ran"), LEAVE), 1); +} + +#[test] +fn a_panic_after_the_guard_dropped_writes_nothing() { + let out = Shared::default(); + drop(guard(&out)); + let after_drop = out.bytes(); + assert_eq!(count(&after_drop, LEAVE), 1); + let _ = catch_unwind(|| panic!("forced after the guard")); + assert_eq!(out.bytes(), after_drop); + // And a later guard on the same thread is still served by the hook. + let next = Shared::default(); + owner_panics(&next); + assert_eq!(count(&at_hand_over().expect("hook ran"), LEAVE), 1); +} diff --git a/crates/thing-tui/tests/pipeline.rs b/crates/thing-tui/tests/pipeline.rs index 5bb5f62..d023c0b 100644 --- a/crates/thing-tui/tests/pipeline.rs +++ b/crates/thing-tui/tests/pipeline.rs @@ -15,7 +15,7 @@ use thing_testkit::golden; use thing_testkit::ids::SeqIds; use thing_testkit::mem_state::MemState; use thing_testkit::state; -use thing_tui::{Op, Screen, Terminal, diff, paint, translate}; +use thing_tui::{Op, Screen, diff, paint, translate}; struct Host { core: Core, @@ -75,19 +75,6 @@ fn a_second_frame_with_nothing_new_draws_nothing() { assert_eq!(host.frame(1_016, (100, 37), Vec::new()), Vec::new()); } -#[test] -fn the_first_frames_ops_replay_to_the_same_bytes_as_a_full_repaint() { - let mut host = Host::new(Fixture::F01SwarmDashboard); - let ops = host.frame(1_000, (100, 37), Vec::new()); - assert_eq!(ops, diff(&Screen::new(0, 0), &host.shown)); - // The writer takes exactly those ops: one synchronized update, flushed once. - let mut out = Vec::new(); - let mut terminal = Terminal::enter_without_raw_mode(&mut out).unwrap(); - terminal.draw(&ops).unwrap(); - drop(terminal); - assert!(out.windows(8).any(|w| w == b"\x1b[?2026h")); -} - /// The size read at a frame is that frame's viewport: after a resize the screen is the one a host /// that started at the new size draws, and the diff repaints rather than patches. #[test] -- 2.47.3 From 9a1578e49ba9f1cb4f73fdcfd42c1fd33d11171a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:09:43 +0100 Subject: [PATCH 08/19] thing-tui: pin that building a guard installs the panic hook Per the steward's decision on thing2:finding:cut-tui-host.s1.panic-hook-install-untested. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal/guard_tests.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index b3faca7..65b1b0d 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -118,3 +118,11 @@ fn a_panic_after_the_guard_dropped_writes_nothing() { owner_panics(&next); assert_eq!(count(&at_hand_over().expect("hook ran"), LEAVE), 1); } +#[test] +fn building_a_guard_installs_the_hook() { + let out = Shared::default(); + owner_panics(&out); + let seen = at_hand_over().expect("the previous hook was reached"); + assert_eq!(count(&seen, LEAVE), 1, "restored before the previous hook, by the hook"); +} + -- 2.47.3 From 63a2f43c1ddb624ef03e0bb98408051fff83999f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:10:41 +0100 Subject: [PATCH 09/19] thing-tui: the guard's surface is stdout, enter and draw write_enter, write_restore and enter_without_raw_mode leave the public API; their tests are unit tests in the crate. Every constructor that enters (enter, stdout) installs the hook. The seams are pinned out of the API by compile_fail doctests. Per the steward's decision on thing2:finding:cut-tui-host.s1.public-api-test-seams. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/lib.rs | 2 +- crates/thing-tui/src/terminal.rs | 23 ++- crates/thing-tui/src/terminal/guard_tests.rs | 131 +++++++++++++- crates/thing-tui/tests/terminal.rs | 175 ------------------- 4 files changed, 147 insertions(+), 184 deletions(-) delete mode 100644 crates/thing-tui/tests/terminal.rs diff --git a/crates/thing-tui/src/lib.rs b/crates/thing-tui/src/lib.rs index 10216b3..b750340 100644 --- a/crates/thing-tui/src/lib.rs +++ b/crates/thing-tui/src/lib.rs @@ -15,4 +15,4 @@ pub use diff::{Op, diff}; pub use input::translate; pub use paint::{Painted, Representation, paint, representation}; pub use screen::{Cell, Screen}; -pub use terminal::{Terminal, write_enter, write_restore}; +pub use terminal::Terminal; diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 56b68e0..9af0d8e 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -61,6 +61,20 @@ fn guards() -> MutexGuard<'static, Vec<(ThreadId, Arc)>> { GUARDS.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 +/// raw mode are the crate's own, not a host's. +/// +/// ```compile_fail +/// let _ = thing_tui::write_enter::>; +/// ``` +/// +/// ```compile_fail +/// let _ = thing_tui::write_restore::>; +/// ``` +/// +/// ```compile_fail +/// let _ = thing_tui::Terminal::enter_without_raw_mode(Vec::::new()); +/// ``` pub struct Terminal { shared: Arc>, } @@ -83,11 +97,6 @@ impl Terminal { Self::start(out, true) } - /// The same without raw mode, for a writer that is not a terminal (a test, a pipe). - pub fn enter_without_raw_mode(out: W) -> io::Result { - Self::start(out, false) - } - fn start(out: W, raw: bool) -> io::Result { HOOK.call_once(install_panic_hook); if raw { @@ -165,13 +174,13 @@ fn tolerate(result: io::Result<()>) -> io::Result<()> { } /// The bytes that enter the modes (raw mode is not a byte sequence and is set apart). -pub fn write_enter(out: &mut W) -> io::Result<()> { +fn write_enter(out: &mut W) -> io::Result<()> { queue!(out, EnterAlternateScreen, Hide, EnableMouseCapture, EnableFocusChange)?; tolerate(queue!(out, EnableBracketedPaste)) } /// The bytes that undo `write_enter`, every one attempted even when an earlier one failed. -pub fn write_restore(out: &mut W) -> io::Result<()> { +fn write_restore(out: &mut W) -> io::Result<()> { let paste = tolerate(queue!(out, DisableBracketedPaste)); let rest = queue!(out, DisableFocusChange, DisableMouseCapture, Show, LeaveAlternateScreen); paste.and(rest) diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index 65b1b0d..fbe08b3 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -8,7 +8,11 @@ use std::io::{self, Write}; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::{Arc, Mutex, Once}; -use super::Terminal; +use thing_contract::Rgba; +use thing_core::layout::CellStyle; + +use super::{Terminal, 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. #[derive(Clone, Default)] @@ -126,3 +130,128 @@ fn building_a_guard_installs_the_hook() { assert_eq!(count(&seen, LEAVE), 1, "restored before the previous hook, by the hook"); } +fn has(bytes: &[u8], needle: &str) -> bool { + bytes.windows(needle.len()).any(|w| w == needle.as_bytes()) +} + +/// The bytes one `draw` writes, after the guard's own entering sequence. +fn drawn(ops: &[Op]) -> Vec { + let out = Shared::default(); + let mut terminal = guard(&out); + let before = out.bytes().len(); + terminal.draw(ops).unwrap(); + out.bytes()[before..].to_vec() +} + +fn rgb(r: u8, g: u8, b: u8) -> Option { + Some(Rgba { r, g, b, a: 255 }) +} + +#[test] +fn a_one_cell_diff_is_one_synchronized_update_with_one_move() { + let old = Screen::new(4, 2); + let mut new = old.clone(); + new.cells[4 + 2].glyph = "x".into(); + let ops = diff(&old, &new); + let bytes = drawn(&ops); + assert!(bytes.starts_with(b"\x1b[?2026h"), "{bytes:?}"); + assert!(bytes.ends_with(b"\x1b[?2026l"), "{bytes:?}"); + // One cursor move, to row 2 column 3 (1-based), and the glyph itself. + assert_eq!(count(&bytes, "H"), 1, "{bytes:?}"); + assert!(has(&bytes, "\x1b[2;3H"), "{bytes:?}"); + assert!(has(&bytes, "x")); +} + +#[test] +fn no_ops_write_nothing() { + assert_eq!(drawn(&[]), Vec::::new()); +} + +#[test] +fn a_move_beyond_the_terminal_addressing_saturates() { + 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 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:?}"); + let colour = drawn(&[Op::Style(rgb(1, 2, 3), rgb(4, 5, 6), CellStyle::default())]); + assert!(has(&colour, "\x1b[38;2;1;2;3m"), "{colour:?}"); + assert!(has(&colour, "\x1b[48;2;4;5;6m"), "{colour:?}"); + // Foreground and background are not swapped. + let text = String::from_utf8(colour).unwrap(); + assert!(text.find("38;2;1;2;3").unwrap() < text.find("48;2;4;5;6").unwrap()); +} + +#[test] +fn each_attribute_is_set_and_each_absent_one_is_cleared() { + 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:?}"); + } + let on = drawn(&[Op::Style(None, None, CellStyle { bold: true, italic: true, underline: true })]); + for set in ["\x1b[1m", "\x1b[3m", "\x1b[4m"] { + assert!(has(&on, set), "{set:?} missing in {on:?}"); + } + for cleared in ["\x1b[22m", "\x1b[23m", "\x1b[24m"] { + assert!(!has(&on, cleared), "{cleared:?} present in {on:?}"); + } + // One attribute at a time: the other two stay cleared. + let bold = drawn(&[Op::Style(None, None, CellStyle { bold: true, ..CellStyle::default() })]); + assert!(has(&bold, "\x1b[1m") && has(&bold, "\x1b[23m") && has(&bold, "\x1b[24m") && !has(&bold, "\x1b[22m")); + let italic = drawn(&[Op::Style(None, None, CellStyle { italic: true, ..CellStyle::default() })]); + assert!(has(&italic, "\x1b[3m") && has(&italic, "\x1b[22m") && has(&italic, "\x1b[24m") && !has(&italic, "\x1b[23m")); + let underline = drawn(&[Op::Style(None, None, CellStyle { underline: true, ..CellStyle::default() })]); + assert!(has(&underline, "\x1b[4m") && has(&underline, "\x1b[22m") && has(&underline, "\x1b[23m") && !has(&underline, "\x1b[24m")); +} + +#[test] +fn print_writes_the_text_in_place() { + let bytes = drawn(&[Op::MoveTo(0, 0), Op::Print("h\u{e9}llo".into())]); + assert!(has(&bytes, "\x1b[1;1Hh\u{e9}llo"), "{bytes:?}"); +} + +/// What crossterm writes as bytes. On Windows, mouse capture is a console-mode call, not an escape +/// sequence, so it is not in the stream there. +const MOUSE: bool = cfg!(not(windows)); +const ENTER: [(&str, bool); 5] = [("\x1b[?1049h", true), ("\x1b[?25l", true), ("\x1b[?1000h", MOUSE), ("\x1b[?1004h", true), ("\x1b[?2004h", true)]; +const RESTORE: [(&str, bool); 5] = [("\x1b[?2004l", true), ("\x1b[?1004l", true), ("\x1b[?1000l", MOUSE), ("\x1b[?25h", true), ("\x1b[?1049l", true)]; + +fn modes(table: [(&'static str, bool); 5]) -> impl Iterator { + table.into_iter().filter(|(_, bytes)| *bytes).map(|(sequence, _)| sequence) +} + +#[test] +fn entering_writes_every_mode_and_restoring_undoes_each() { + let mut entered = Vec::new(); + write_enter(&mut entered).unwrap(); + for sequence in modes(ENTER) { + assert!(has(&entered, sequence), "{sequence:?} missing from enter {entered:?}"); + } + let mut restored = Vec::new(); + write_restore(&mut restored).unwrap(); + for sequence in modes(RESTORE) { + assert!(has(&restored, sequence), "{sequence:?} missing from restore {restored:?}"); + } + // The alternate screen is left last, so the user's screen returns after the modes are off. + assert!(restored.ends_with(b"\x1b[?1049l")); +} + +#[test] +fn dropping_the_guard_restores_once() { + let out = Shared::default(); + let terminal = guard(&out); + for sequence in modes(ENTER) { + assert!(has(&out.bytes(), sequence), "{sequence:?}"); + } + assert!(!has(&out.bytes(), "\x1b[?1049l"), "left before the guard dropped"); + drop(terminal); + let bytes = out.bytes(); + for sequence in modes(RESTORE) { + assert!(has(&bytes, sequence), "{sequence:?} missing after drop"); + } + assert_eq!(count(&bytes, "\x1b[?1049l"), 1); +} diff --git a/crates/thing-tui/tests/terminal.rs b/crates/thing-tui/tests/terminal.rs deleted file mode 100644 index 28372d4..0000000 --- a/crates/thing-tui/tests/terminal.rs +++ /dev/null @@ -1,175 +0,0 @@ -//! The writer's bytes and the guard's restore sequence, on a writer that is a `Vec` behind a -//! handle: nothing here touches a terminal. - -use std::io::{self, Write}; -use std::panic::{AssertUnwindSafe, catch_unwind}; -use std::sync::{Arc, Mutex}; - -use thing_contract::Rgba; -use thing_core::layout::CellStyle; -use thing_tui::{Op, Screen, Terminal, diff, write_enter, write_restore}; - -/// A writer the test keeps a handle on after the terminal that owns it is gone. -#[derive(Clone, Default)] -struct Shared(Arc>>); - -impl Shared { - fn bytes(&self) -> Vec { - self.0.lock().unwrap().clone() - } -} - -impl Write for Shared { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.0.lock().unwrap().extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -fn has(bytes: &[u8], needle: &str) -> bool { - bytes.windows(needle.len()).any(|w| w == needle.as_bytes()) -} - -fn count(bytes: &[u8], needle: &str) -> usize { - bytes.windows(needle.len()).filter(|w| *w == needle.as_bytes()).count() -} - -/// The bytes one `draw` writes, after the guard's own entering sequence. -fn drawn(ops: &[Op]) -> Vec { - let out = Shared::default(); - let mut terminal = Terminal::enter_without_raw_mode(out.clone()).unwrap(); - let before = out.bytes().len(); - terminal.draw(ops).unwrap(); - out.bytes()[before..].to_vec() -} - -fn rgb(r: u8, g: u8, b: u8) -> Option { - Some(Rgba { r, g, b, a: 255 }) -} - -#[test] -fn a_one_cell_diff_is_one_synchronized_update_with_one_move() { - let old = Screen::new(4, 2); - let mut new = old.clone(); - new.cells[4 + 2].glyph = "x".into(); - let ops = diff(&old, &new); - let bytes = drawn(&ops); - assert!(bytes.starts_with(b"\x1b[?2026h"), "{bytes:?}"); - assert!(bytes.ends_with(b"\x1b[?2026l"), "{bytes:?}"); - // One cursor move, to row 2 column 3 (1-based), and the glyph itself. - assert_eq!(count(&bytes, "H"), 1, "{bytes:?}"); - assert!(has(&bytes, "\x1b[2;3H"), "{bytes:?}"); - assert!(has(&bytes, "x")); -} - -#[test] -fn no_ops_write_nothing() { - assert_eq!(drawn(&[]), Vec::::new()); -} - -#[test] -fn a_move_beyond_the_terminal_addressing_saturates() { - 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 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:?}"); - let colour = drawn(&[Op::Style(rgb(1, 2, 3), rgb(4, 5, 6), CellStyle::default())]); - assert!(has(&colour, "\x1b[38;2;1;2;3m"), "{colour:?}"); - assert!(has(&colour, "\x1b[48;2;4;5;6m"), "{colour:?}"); - // Foreground and background are not swapped. - let text = String::from_utf8(colour).unwrap(); - assert!(text.find("38;2;1;2;3").unwrap() < text.find("48;2;4;5;6").unwrap()); -} - -#[test] -fn each_attribute_is_set_and_each_absent_one_is_cleared() { - 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:?}"); - } - let on = drawn(&[Op::Style(None, None, CellStyle { bold: true, italic: true, underline: true })]); - for set in ["\x1b[1m", "\x1b[3m", "\x1b[4m"] { - assert!(has(&on, set), "{set:?} missing in {on:?}"); - } - for cleared in ["\x1b[22m", "\x1b[23m", "\x1b[24m"] { - assert!(!has(&on, cleared), "{cleared:?} present in {on:?}"); - } - // One attribute at a time: the other two stay cleared. - let bold = drawn(&[Op::Style(None, None, CellStyle { bold: true, ..CellStyle::default() })]); - assert!(has(&bold, "\x1b[1m") && has(&bold, "\x1b[23m") && has(&bold, "\x1b[24m") && !has(&bold, "\x1b[22m")); - let italic = drawn(&[Op::Style(None, None, CellStyle { italic: true, ..CellStyle::default() })]); - assert!(has(&italic, "\x1b[3m") && has(&italic, "\x1b[22m") && has(&italic, "\x1b[24m") && !has(&italic, "\x1b[23m")); - let underline = drawn(&[Op::Style(None, None, CellStyle { underline: true, ..CellStyle::default() })]); - assert!(has(&underline, "\x1b[4m") && has(&underline, "\x1b[22m") && has(&underline, "\x1b[23m") && !has(&underline, "\x1b[24m")); -} - -#[test] -fn print_writes_the_text_in_place() { - let bytes = drawn(&[Op::MoveTo(0, 0), Op::Print("h\u{e9}llo".into())]); - assert!(has(&bytes, "\x1b[1;1Hh\u{e9}llo"), "{bytes:?}"); -} - -/// What crossterm writes as bytes. On Windows, mouse capture is a console-mode call, not an escape -/// sequence, so it is not in the stream there. -const MOUSE: bool = cfg!(not(windows)); -const ENTER: [(&str, bool); 5] = [("\x1b[?1049h", true), ("\x1b[?25l", true), ("\x1b[?1000h", MOUSE), ("\x1b[?1004h", true), ("\x1b[?2004h", true)]; -const RESTORE: [(&str, bool); 5] = [("\x1b[?2004l", true), ("\x1b[?1004l", true), ("\x1b[?1000l", MOUSE), ("\x1b[?25h", true), ("\x1b[?1049l", true)]; - -fn modes(table: [(&'static str, bool); 5]) -> impl Iterator { - table.into_iter().filter(|(_, bytes)| *bytes).map(|(sequence, _)| sequence) -} - -#[test] -fn entering_writes_every_mode_and_restoring_undoes_each() { - let mut entered = Vec::new(); - write_enter(&mut entered).unwrap(); - for sequence in modes(ENTER) { - assert!(has(&entered, sequence), "{sequence:?} missing from enter {entered:?}"); - } - let mut restored = Vec::new(); - write_restore(&mut restored).unwrap(); - for sequence in modes(RESTORE) { - assert!(has(&restored, sequence), "{sequence:?} missing from restore {restored:?}"); - } - // The alternate screen is left last, so the user's screen returns after the modes are off. - assert!(restored.ends_with(b"\x1b[?1049l")); -} - -#[test] -fn dropping_the_guard_restores_once() { - let out = Shared::default(); - let terminal = Terminal::enter_without_raw_mode(out.clone()).unwrap(); - for sequence in modes(ENTER) { - assert!(has(&out.bytes(), sequence), "{sequence:?}"); - } - assert!(!has(&out.bytes(), "\x1b[?1049l"), "left before the guard dropped"); - drop(terminal); - let bytes = out.bytes(); - for sequence in modes(RESTORE) { - assert!(has(&bytes, sequence), "{sequence:?} missing after drop"); - } - assert_eq!(count(&bytes, "\x1b[?1049l"), 1); -} - -#[test] -fn a_panic_unwinding_through_the_guard_restores_the_terminal() { - let out = Shared::default(); - let inner = out.clone(); - let caught = catch_unwind(AssertUnwindSafe(move || { - let _terminal = Terminal::enter_without_raw_mode(inner).unwrap(); - panic!("forced"); - })); - assert!(caught.is_err()); - let bytes = out.bytes(); - for sequence in modes(RESTORE) { - assert!(has(&bytes, sequence), "{sequence:?} missing after the panic"); - } -} -- 2.47.3 From fb2716f1e52a33111995478b5aa6ec5c27648641 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:11:29 +0100 Subject: [PATCH 10/19] thing-tui: restore closes a synchronized update a failed frame left open Per the steward's decision on thing2:finding:cut-tui-host.s1.restore-leaves-sync-update-open. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 7 +++- crates/thing-tui/src/terminal/guard_tests.rs | 41 ++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 9af0d8e..6111f81 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -179,11 +179,14 @@ fn write_enter(out: &mut W) -> io::Result<()> { tolerate(queue!(out, EnableBracketedPaste)) } -/// The bytes that undo `write_enter`, every one attempted even when an earlier one failed. +/// The bytes that undo `write_enter`, every one attempted even when an earlier one failed. A frame +/// that failed part-way left its synchronized update open, so that is closed first: a terminal +/// that holds the display until the update ends would not paint the screen restored after it. fn write_restore(out: &mut W) -> io::Result<()> { + let update = queue!(out, EndSynchronizedUpdate); let paste = tolerate(queue!(out, DisableBracketedPaste)); let rest = queue!(out, DisableFocusChange, DisableMouseCapture, Show, LeaveAlternateScreen); - paste.and(rest) + update.and(paste).and(rest) } /// Chain a hook ahead of the current one: a panic on a thread that owns an entered guard gives that diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index fbe08b3..c85d312 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -255,3 +255,44 @@ fn dropping_the_guard_restores_once() { } assert_eq!(count(&bytes, "\x1b[?1049l"), 1); } + +/// A writer whose next write after `arm` more succeeds fails once, then the writer is sound again. +struct Flaky { + out: Shared, + left: Arc, +} + +impl Write for Flaky { + fn write(&mut self, buf: &[u8]) -> io::Result { + use std::sync::atomic::Ordering::SeqCst; + match self.left.load(SeqCst) { + 0 => { + self.left.store(-1, SeqCst); + return Err(io::Error::other("forced write failure")); + } + n if n > 0 => self.left.store(n - 1, SeqCst), + _ => {} + } + self.out.write(buf) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn an_error_mid_draw_does_not_leave_the_synchronized_update_open() { + spy(); + let out = Shared::default(); + let left = Arc::new(std::sync::atomic::AtomicIsize::new(-1)); + let mut terminal = Terminal::start(Flaky { out: out.clone(), left: left.clone() }, false).unwrap(); + // The begin goes through; the cursor move after it fails. + left.store(1, std::sync::atomic::Ordering::SeqCst); + assert!(terminal.draw(&[Op::MoveTo(0, 0), Op::Print("x".into())]).is_err()); + assert_eq!(count(&out.bytes(), "\x1b[?2026h"), 1); + assert_eq!(count(&out.bytes(), "\x1b[?2026l"), 0, "the frame never reached its end"); + drop(terminal); + let bytes = String::from_utf8(out.bytes()).unwrap(); + let end = bytes.rfind("\x1b[?2026l").expect("the restore closes the open update"); + assert!(end < bytes.rfind(LEAVE).unwrap(), "closed before the alternate screen is left"); +} -- 2.47.3 From 6f884075d72bca6929ed214097612df6df170bfb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:11:39 +0100 Subject: [PATCH 11/19] thing-tui: the pipeline events test says what it observes Per the steward's decision on thing2:finding:cut-tui-host.s1.report-overclaims-and-misses-estimate; the estimate is explained in the report. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/tests/pipeline.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/thing-tui/tests/pipeline.rs b/crates/thing-tui/tests/pipeline.rs index d023c0b..ad9b61d 100644 --- a/crates/thing-tui/tests/pipeline.rs +++ b/crates/thing-tui/tests/pipeline.rs @@ -95,18 +95,17 @@ fn a_resize_is_the_next_frames_viewport() { assert_eq!(host.text().as_bytes(), golden.as_slice()); } -/// Events drained from the terminal reach `frame` in the order they came, translated by the same -/// function the host calls; a resize in the burst is not an event, and a frame holding them -/// draws the same screen it would have drawn without. +/// What it can observe today: a frame handed translated events draws the screen it draws without +/// them, because `Core::frame` routes no input yet. The order translate gives is pinned in +/// tests/input.rs, and what core does with it will be observable when it routes. #[test] -fn drained_events_feed_the_frame_in_order() { +fn a_frame_carrying_events_draws_the_same_screen_while_core_routes_none() { let burst = [ Event::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)), Event::Resize(100, 37), Event::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)), ]; let events: Vec = burst.iter().flat_map(translate).collect(); - assert_eq!(events.len(), 3); let mut host = Host::new(Fixture::F01SwarmDashboard); host.frame(1_000, (100, 37), events); let golden = golden::read(&goldens(), "screen-f01-swarm-dashboard-cells.txt"); -- 2.47.3 From e333cb8f9cdbb0928ad9eaa6e9b0d4d446e52052 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:16:16 +0100 Subject: [PATCH 12/19] thing-tui: pin that a drop unregisters only its own guard Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal/guard_tests.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index c85d312..7e6e9b3 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -296,3 +296,17 @@ fn an_error_mid_draw_does_not_leave_the_synchronized_update_open() { let end = bytes.rfind("\x1b[?2026l").expect("the restore closes the open update"); 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"); +} -- 2.47.3 From 82e9cc18ea8f216733254e2b123bf46964f7b1f1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:28:07 +0100 Subject: [PATCH 13/19] thing-tui: under panic=abort the hook restores for a panic on any thread Nothing unwinds to Drop there, so the owner-only rule left a worker's panic to abort the process with the terminal still raw. Unwind builds keep the owner-thread rule. Per the steward's decision on thing2:finding:cut-tui-host.s2.abort-profile-worker-panic-leaves-raw. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 10 +++++++++- crates/thing-tui/src/terminal/guard_tests.rs | 14 +++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) 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)); +} -- 2.47.3 From ed91a6364bf391d0c6523904264175bb25539455 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:28:14 +0100 Subject: [PATCH 14/19] thing-tui: a restore that finds the writer held still gives back raw mode Per the steward's decision on thing2:finding:cut-tui-host.s2.restore-skipped-under-lock-leaves-raw; the double-panic case is run in a pty (red before this commit, green after). Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 1750d02..16bce9e 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -36,11 +36,18 @@ trait Restore: Send + Sync { 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. Leave that restore to `Drop`, which runs once the unwinding has released it. + // 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). let mut out = match self.out.try_lock() { Ok(out) => out, Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), - Err(TryLockError::WouldBlock) => return, + Err(TryLockError::WouldBlock) => { + if self.raw { + let _ = disable_raw_mode(); + } + return; + } }; if !self.entered.swap(false, Ordering::SeqCst) { return; -- 2.47.3 From 0b58fd729c3ef6372349dbb788e85337f324c61a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:29:08 +0100 Subject: [PATCH 15/19] thing-tui: the guard's owner is the thread that last entered or drew through it A guard moved to a render thread follows its user: that thread's panic restores before its message, and a panic on the thread that gave it away leaves it to the owner. Per the steward's decision on thing2:finding:cut-tui-host.s2.guard-owner-is-the-constructing-thread. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 21 +++++++--- crates/thing-tui/src/terminal/guard_tests.rs | 42 ++++++++++++++++++++ 2 files changed, 57 insertions(+), 6 deletions(-) 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); +} -- 2.47.3 From 997ac1b2c31913ad1fffe4949f0467c850970a21 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:30:29 +0100 Subject: [PATCH 16/19] thing-tui: one live terminal guard per process A second enter or stdout() while one is alive fails with AlreadyExists, so nested and cross-thread guards are impossible and no guard can take the terminal from another. The registry becomes one slot; the several-guards unregistering and its test go. The refusal is pinned in their place, and every test that builds a guard takes a lock so the suite's threads do not collide. Per the steward's decision on thing2:finding:cut-tui-host.s2.guards-share-global-modes. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 37 ++++++++------ crates/thing-tui/src/terminal/guard_tests.rs | 52 ++++++++++++++------ 2 files changed, 61 insertions(+), 28 deletions(-) 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); +} -- 2.47.3 From cdea686dae7738cf22c9c3260f637b3f65f8abeb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:43:38 +0100 Subject: [PATCH 17/19] thing-tui: a panic on the main thread restores a guard whatever thread owns it A main-thread panic ends the process without running a guard held by a render thread, so the owner-only rule left the terminal raw. restores_here takes is_main as well as abort, owner and here. Per thing2:ruling:tui-panic-restore-rule and thing2:finding:cut-tui-host.s3.main-panic-with-guard-on-worker-leaves-raw. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 15 ++++++++------- crates/thing-tui/src/terminal/guard_tests.rs | 16 +++++++++------- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 50de37c..4d11024 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -214,12 +214,13 @@ 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 +/// Whether a panic on `here` gives back the terminal a guard owned by `owner` holds. The panic that +/// ends the process always does: any thread where panics abort, and the main thread (whose panic +/// exits the process without running a guard that lives on another thread). A panic on the owner +/// restores so its message does not print on the alternate screen. Any other worker's panic unwinds +/// without touching the UI, and the owner's `Drop` runs in due course. +fn restores_here(abort: bool, is_main: bool, owner: ThreadId, here: ThreadId) -> bool { + abort || is_main || owner == here } /// Chain a hook ahead of the current one: a panic that `restores_here` gives the live guard's terminal @@ -229,7 +230,7 @@ fn install_panic_hook() { std::panic::set_hook(Box::new(move |info| { let live = active().clone(); if let Some(guard) = live - && restores_here(cfg!(panic = "abort"), guard.owner(), thread::current().id()) + && restores_here(cfg!(panic = "abort"), thread::current().name() == Some("main"), guard.owner(), thread::current().id()) { guard.restore(); } diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index 6c2cbff..e4093c7 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -318,15 +318,17 @@ fn an_error_mid_draw_does_not_leave_the_synchronized_update_open() { } #[test] -fn a_panic_restores_on_the_owners_thread_and_on_any_thread_when_nothing_unwinds() { +fn a_panic_restores_on_the_owners_thread_the_main_thread_and_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)); + // Unwinding: the owner's panic restores; so does the main thread's, which ends the process + // without running a guard that lives on another thread; another worker's panic leaves the guard. + assert!(restores_here(false, false, here, here)); + assert!(restores_here(false, true, here, elsewhere)); + assert!(!restores_here(false, false, here, elsewhere)); + // Aborting: no Drop follows a panic anywhere, so every panic restores. + assert!(restores_here(true, false, here, elsewhere)); + assert!(restores_here(true, true, here, elsewhere)); } #[test] -- 2.47.3 From 5e1a436221fdfb662471615eba2ed39ee8204e6c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:44:07 +0100 Subject: [PATCH 18/19] 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 --- crates/thing-tui/src/terminal.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) 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; } -- 2.47.3 From f25ac958c1e10dc59c10775889fdfd8428c165d6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:44:58 +0100 Subject: [PATCH 19/19] thing-tui: Drop restores first, then frees the one-guard slot An enter racing a drop is refused until the terminal is given back. The race is forced with a barrier inside the old guard's restore write, not a timing assumption. Per thing2:ruling:tui-panic-restore-rule and thing2:finding:cut-tui-host.s3.drop-unregisters-before-restoring. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/terminal.rs | 4 +- crates/thing-tui/src/terminal/guard_tests.rs | 46 ++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 01f882c..9be10bc 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -175,8 +175,10 @@ impl Terminal { impl Drop for Terminal { fn drop(&mut self) { - *active() = None; + // Restore first, then free the slot: an enter that races this drop is refused until the + // terminal is given back, so the restore never runs over a new guard. self.shared.restore(); + *active() = None; } } diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index e4093c7..8363e41 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -390,3 +390,49 @@ fn a_second_guard_is_refused_while_one_is_live() { drop(Terminal::start(second_out.clone(), false).expect("a guard after the last one dropped")); assert_eq!(count(&second_out.bytes(), LEAVE), 1); } + +/// A writer that, once armed, stops inside its next write until the test lets it go: the drop is held +/// mid-restore at a point the test chooses, with no sleep and no timing assumption. +struct Gated { + out: Shared, + armed: Arc, + inside: Arc, + release: Arc, +} + +impl Write for Gated { + fn write(&mut self, buf: &[u8]) -> io::Result { + if self.armed.swap(false, std::sync::atomic::Ordering::SeqCst) { + self.inside.wait(); + self.release.wait(); + } + self.out.write(buf) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn an_enter_racing_a_drop_is_refused_until_the_restore_is_done() { + let _one = one_at_a_time(); + spy(); + let out = Shared::default(); + let armed = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let inside = Arc::new(std::sync::Barrier::new(2)); + let release = Arc::new(std::sync::Barrier::new(2)); + let gated = Gated { out: out.clone(), armed: armed.clone(), inside: inside.clone(), release: release.clone() }; + let terminal = Terminal::start(gated, false).unwrap(); + armed.store(true, std::sync::atomic::Ordering::SeqCst); + let dropping = std::thread::spawn(move || drop(terminal)); + // The drop is now inside its restore, holding the terminal. An enter on this thread must not get it. + inside.wait(); + let racing = Terminal::start(Shared::default(), false); + let refused = racing.as_ref().err().map(io::Error::kind); + release.wait(); + dropping.join().unwrap(); + drop(racing); + assert_eq!(refused, Some(io::ErrorKind::AlreadyExists), "a guard entered while the old one was still giving the terminal back"); + assert_eq!(count(&out.bytes(), LEAVE), 1); + drop(Terminal::start(Shared::default(), false).expect("the slot is free once the restore is done")); +} -- 2.47.3