From f532f6bb6ad4e2f67c499c9bfc893e3d81c47a48 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sun, 29 Nov 2026 01:54:20 +0000 Subject: [PATCH] thing-tui: live terminal host (cut 8b) (#26) --- 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 | 263 +++++++++++ crates/thing-tui/src/terminal/guard_tests.rs | 438 +++++++++++++++++++ crates/thing-tui/tests/input.rs | 218 +++++++++ crates/thing-tui/tests/pipeline.rs | 113 +++++ 9 files changed, 1413 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/src/terminal/guard_tests.rs create mode 100644 crates/thing-tui/tests/input.rs create mode 100644 crates/thing-tui/tests/pipeline.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..b750340 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; diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs new file mode 100644 index 0000000..9be10bc --- /dev/null +++ b/crates/thing-tui/src/terminal.rs @@ -0,0 +1,263 @@ +//! 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, 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::{ + 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; + +/// 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, + 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, 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.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; + } + }; + if !self.entered.swap(false, Ordering::SeqCst) { + return; + } + let _ = write_restore(&mut *out).and_then(|()| out.flush()); + if self.raw { + let _ = disable_raw_mode(); + } + } +} + +/// 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 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 +/// 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>, +} + +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. + /// + /// 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()) }); + *slot = Some(shared.clone()); + drop(slot); + 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<()> { + *self.shared.owner.lock().unwrap_or_else(PoisonError::into_inner) = thread::current().id(); + if ops.is_empty() { + return Ok(()); + } + let mut out = self.out(); + queue!(out, BeginSynchronizedUpdate)?; + for op in ops { + match op { + Op::MoveTo(col, row) => queue!(out, MoveTo(clamp(*col), clamp(*row)))?, + Op::Style(fg, bg, style) => queue!( + 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!(out, Print(text))?, + } + } + queue!(out, EndSynchronizedUpdate)?; + out.flush() + } +} + +impl Drop for Terminal { + fn drop(&mut self) { + // 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; + } +} + +/// 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).min(u16::MAX - 1) +} + +/// 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). +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. 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); + update.and(paste).and(rest) +} + +/// 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 +/// 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 live = active().clone(); + if let Some(guard) = live + && restores_here(cfg!(panic = "abort"), thread::current().name() == Some("main"), guard.owner(), thread::current().id()) + { + guard.restore(); + } + previous(info); + })); +} + +#[cfg(test)] +mod tests { + use std::io; + + use super::tolerate; + + #[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); + } +} + +#[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..8363e41 --- /dev/null +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -0,0 +1,438 @@ +//! 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 thing_contract::Rgba; +use thing_core::layout::CellStyle; + +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. +#[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(); + +/// 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() { + 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 _one = one_at_a_time(); + 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 _one = one_at_a_time(); + 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 _one = one_at_a_time(); + 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); +} +#[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"); + 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 _one = one_at_a_time(); + 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() { + 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:?}"); + 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 _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:?}"); + } + 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 _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:?}"); +} + +/// 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 _one = one_at_a_time(); + 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); +} + +/// 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() { + let _one = one_at_a_time(); + 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"); +} + +#[test] +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; 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] +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(); + 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 _one = one_at_a_time(); + 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); +} + +#[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); +} + +/// 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")); +} diff --git a/crates/thing-tui/tests/input.rs b/crates/thing-tui/tests/input.rs new file mode 100644 index 0000000..b5938c0 --- /dev/null +++ b/crates/thing-tui/tests/input.rs @@ -0,0 +1,218 @@ +//! `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::SUPER | 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..ad9b61d --- /dev/null +++ b/crates/thing-tui/tests/pipeline.rs @@ -0,0 +1,113 @@ +//! 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, 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()); +} + +/// 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()); +} + +/// 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 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(); + 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()); +}