thing-tui: live terminal host (cut 8b): Terminal guard and writer, translate, reference host example

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-29 01:41:25 +01:00
commit 91a466192d
9 changed files with 1063 additions and 5 deletions

173
Cargo.lock generated
View file

@ -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"

View file

@ -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" }

View file

@ -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<String> = 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<InputEvent> = Vec::new();
let mut next_wake: Option<Timestamp> = 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;
}
}

View file

@ -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<InputEvent> {
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<InputEvent> {
// 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)),
}
}

View file

@ -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};

View file

@ -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<W: Write> {
out: W,
/// Set once the modes are entered; `Drop` undoes them only then.
entered: bool,
raw: bool,
}
impl Terminal<io::BufWriter<io::Stdout>> {
/// 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<Self> {
let terminal = Self::enter(io::BufWriter::with_capacity(1 << 16, io::stdout()))?;
install_panic_hook();
Ok(terminal)
}
}
impl<W: Write> Terminal<W> {
/// Enter the terminal modes on `out`, raw mode included.
pub fn enter(out: W) -> io::Result<Self> {
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> {
Self::start(out, false)
}
fn start(out: W, raw: bool) -> io::Result<Self> {
// 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<W: Write> Drop for Terminal<W> {
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<Rgba>) -> 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<W: Write>(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<W: Write>(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<Vec<&'static str>> = 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"]);
}
}

View file

@ -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<InputEvent> {
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<InputEvent> = 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, .. }));
}

View file

@ -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<InputEvent>) -> Vec<Op> {
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<InputEvent> = 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());
}

View file

@ -0,0 +1,168 @@
//! The writer's bytes and the guard's restore sequence, on a writer that is a `Vec<u8>` 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<Mutex<Vec<u8>>>);
impl Shared {
fn bytes(&self) -> Vec<u8> {
self.0.lock().unwrap().clone()
}
}
impl Write for Shared {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
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<u8> {
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<Rgba> {
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");
}
}