From 63a2f43c1ddb624ef03e0bb98408051fff83999f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 02:10:41 +0100 Subject: [PATCH] thing-tui: the guard's surface is stdout, enter and draw write_enter, write_restore and enter_without_raw_mode leave the public API; their tests are unit tests in the crate. Every constructor that enters (enter, stdout) installs the hook. The seams are pinned out of the API by compile_fail doctests. Per the steward's decision on thing2:finding:cut-tui-host.s1.public-api-test-seams. Co-Authored-By: Claude Opus 5.5 --- crates/thing-tui/src/lib.rs | 2 +- crates/thing-tui/src/terminal.rs | 23 ++- crates/thing-tui/src/terminal/guard_tests.rs | 131 +++++++++++++- crates/thing-tui/tests/terminal.rs | 175 ------------------- 4 files changed, 147 insertions(+), 184 deletions(-) delete mode 100644 crates/thing-tui/tests/terminal.rs diff --git a/crates/thing-tui/src/lib.rs b/crates/thing-tui/src/lib.rs index 10216b3..b750340 100644 --- a/crates/thing-tui/src/lib.rs +++ b/crates/thing-tui/src/lib.rs @@ -15,4 +15,4 @@ pub use diff::{Op, diff}; pub use input::translate; pub use paint::{Painted, Representation, paint, representation}; pub use screen::{Cell, Screen}; -pub use terminal::{Terminal, write_enter, write_restore}; +pub use terminal::Terminal; diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 56b68e0..9af0d8e 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -61,6 +61,20 @@ fn guards() -> MutexGuard<'static, Vec<(ThreadId, Arc)>> { GUARDS.lock().unwrap_or_else(PoisonError::into_inner) } +/// The guard's surface is `stdout`, `enter` and `draw`: the byte helpers and a way to enter without +/// raw mode are the crate's own, not a host's. +/// +/// ```compile_fail +/// let _ = thing_tui::write_enter::>; +/// ``` +/// +/// ```compile_fail +/// let _ = thing_tui::write_restore::>; +/// ``` +/// +/// ```compile_fail +/// let _ = thing_tui::Terminal::enter_without_raw_mode(Vec::::new()); +/// ``` pub struct Terminal { shared: Arc>, } @@ -83,11 +97,6 @@ impl Terminal { Self::start(out, true) } - /// The same without raw mode, for a writer that is not a terminal (a test, a pipe). - pub fn enter_without_raw_mode(out: W) -> io::Result { - Self::start(out, false) - } - fn start(out: W, raw: bool) -> io::Result { HOOK.call_once(install_panic_hook); if raw { @@ -165,13 +174,13 @@ fn tolerate(result: io::Result<()>) -> io::Result<()> { } /// The bytes that enter the modes (raw mode is not a byte sequence and is set apart). -pub fn write_enter(out: &mut W) -> io::Result<()> { +fn write_enter(out: &mut W) -> io::Result<()> { queue!(out, EnterAlternateScreen, Hide, EnableMouseCapture, EnableFocusChange)?; tolerate(queue!(out, EnableBracketedPaste)) } /// The bytes that undo `write_enter`, every one attempted even when an earlier one failed. -pub fn write_restore(out: &mut W) -> io::Result<()> { +fn write_restore(out: &mut W) -> io::Result<()> { let paste = tolerate(queue!(out, DisableBracketedPaste)); let rest = queue!(out, DisableFocusChange, DisableMouseCapture, Show, LeaveAlternateScreen); paste.and(rest) diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index 65b1b0d..fbe08b3 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -8,7 +8,11 @@ use std::io::{self, Write}; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::{Arc, Mutex, Once}; -use super::Terminal; +use thing_contract::Rgba; +use thing_core::layout::CellStyle; + +use super::{Terminal, write_enter, write_restore}; +use crate::{Op, Screen, diff}; /// A writer the test keeps a handle on after the terminal that owns it is gone. #[derive(Clone, Default)] @@ -126,3 +130,128 @@ fn building_a_guard_installs_the_hook() { assert_eq!(count(&seen, LEAVE), 1, "restored before the previous hook, by the hook"); } +fn has(bytes: &[u8], needle: &str) -> bool { + bytes.windows(needle.len()).any(|w| w == needle.as_bytes()) +} + +/// The bytes one `draw` writes, after the guard's own entering sequence. +fn drawn(ops: &[Op]) -> Vec { + let out = Shared::default(); + let mut terminal = guard(&out); + let before = out.bytes().len(); + terminal.draw(ops).unwrap(); + out.bytes()[before..].to_vec() +} + +fn rgb(r: u8, g: u8, b: u8) -> Option { + Some(Rgba { r, g, b, a: 255 }) +} + +#[test] +fn a_one_cell_diff_is_one_synchronized_update_with_one_move() { + let old = Screen::new(4, 2); + let mut new = old.clone(); + new.cells[4 + 2].glyph = "x".into(); + let ops = diff(&old, &new); + let bytes = drawn(&ops); + assert!(bytes.starts_with(b"\x1b[?2026h"), "{bytes:?}"); + assert!(bytes.ends_with(b"\x1b[?2026l"), "{bytes:?}"); + // One cursor move, to row 2 column 3 (1-based), and the glyph itself. + assert_eq!(count(&bytes, "H"), 1, "{bytes:?}"); + assert!(has(&bytes, "\x1b[2;3H"), "{bytes:?}"); + assert!(has(&bytes, "x")); +} + +#[test] +fn no_ops_write_nothing() { + assert_eq!(drawn(&[]), Vec::::new()); +} + +#[test] +fn a_move_beyond_the_terminal_addressing_saturates() { + let bytes = drawn(&[Op::MoveTo(70_000, 1)]); + assert!(has(&bytes, "\x1b[2;65535H"), "{bytes:?}"); +} + +#[test] +fn style_none_resets_the_colour_and_some_is_truecolor() { + let plain = drawn(&[Op::Style(None, None, CellStyle::default())]); + assert!(has(&plain, "\x1b[39m") && has(&plain, "\x1b[49m"), "{plain:?}"); + assert!(!has(&plain, "38;2") && !has(&plain, "48;2"), "{plain:?}"); + let colour = drawn(&[Op::Style(rgb(1, 2, 3), rgb(4, 5, 6), CellStyle::default())]); + assert!(has(&colour, "\x1b[38;2;1;2;3m"), "{colour:?}"); + assert!(has(&colour, "\x1b[48;2;4;5;6m"), "{colour:?}"); + // Foreground and background are not swapped. + let text = String::from_utf8(colour).unwrap(); + assert!(text.find("38;2;1;2;3").unwrap() < text.find("48;2;4;5;6").unwrap()); +} + +#[test] +fn each_attribute_is_set_and_each_absent_one_is_cleared() { + let off = drawn(&[Op::Style(None, None, CellStyle::default())]); + for cleared in ["\x1b[22m", "\x1b[23m", "\x1b[24m"] { + assert!(has(&off, cleared), "{cleared:?} missing in {off:?}"); + } + let on = drawn(&[Op::Style(None, None, CellStyle { bold: true, italic: true, underline: true })]); + for set in ["\x1b[1m", "\x1b[3m", "\x1b[4m"] { + assert!(has(&on, set), "{set:?} missing in {on:?}"); + } + for cleared in ["\x1b[22m", "\x1b[23m", "\x1b[24m"] { + assert!(!has(&on, cleared), "{cleared:?} present in {on:?}"); + } + // One attribute at a time: the other two stay cleared. + let bold = drawn(&[Op::Style(None, None, CellStyle { bold: true, ..CellStyle::default() })]); + assert!(has(&bold, "\x1b[1m") && has(&bold, "\x1b[23m") && has(&bold, "\x1b[24m") && !has(&bold, "\x1b[22m")); + let italic = drawn(&[Op::Style(None, None, CellStyle { italic: true, ..CellStyle::default() })]); + assert!(has(&italic, "\x1b[3m") && has(&italic, "\x1b[22m") && has(&italic, "\x1b[24m") && !has(&italic, "\x1b[23m")); + let underline = drawn(&[Op::Style(None, None, CellStyle { underline: true, ..CellStyle::default() })]); + assert!(has(&underline, "\x1b[4m") && has(&underline, "\x1b[22m") && has(&underline, "\x1b[23m") && !has(&underline, "\x1b[24m")); +} + +#[test] +fn print_writes_the_text_in_place() { + let bytes = drawn(&[Op::MoveTo(0, 0), Op::Print("h\u{e9}llo".into())]); + assert!(has(&bytes, "\x1b[1;1Hh\u{e9}llo"), "{bytes:?}"); +} + +/// What crossterm writes as bytes. On Windows, mouse capture is a console-mode call, not an escape +/// sequence, so it is not in the stream there. +const MOUSE: bool = cfg!(not(windows)); +const ENTER: [(&str, bool); 5] = [("\x1b[?1049h", true), ("\x1b[?25l", true), ("\x1b[?1000h", MOUSE), ("\x1b[?1004h", true), ("\x1b[?2004h", true)]; +const RESTORE: [(&str, bool); 5] = [("\x1b[?2004l", true), ("\x1b[?1004l", true), ("\x1b[?1000l", MOUSE), ("\x1b[?25h", true), ("\x1b[?1049l", true)]; + +fn modes(table: [(&'static str, bool); 5]) -> impl Iterator { + table.into_iter().filter(|(_, bytes)| *bytes).map(|(sequence, _)| sequence) +} + +#[test] +fn entering_writes_every_mode_and_restoring_undoes_each() { + let mut entered = Vec::new(); + write_enter(&mut entered).unwrap(); + for sequence in modes(ENTER) { + assert!(has(&entered, sequence), "{sequence:?} missing from enter {entered:?}"); + } + let mut restored = Vec::new(); + write_restore(&mut restored).unwrap(); + for sequence in modes(RESTORE) { + assert!(has(&restored, sequence), "{sequence:?} missing from restore {restored:?}"); + } + // The alternate screen is left last, so the user's screen returns after the modes are off. + assert!(restored.ends_with(b"\x1b[?1049l")); +} + +#[test] +fn dropping_the_guard_restores_once() { + let out = Shared::default(); + let terminal = guard(&out); + for sequence in modes(ENTER) { + assert!(has(&out.bytes(), sequence), "{sequence:?}"); + } + assert!(!has(&out.bytes(), "\x1b[?1049l"), "left before the guard dropped"); + drop(terminal); + let bytes = out.bytes(); + for sequence in modes(RESTORE) { + assert!(has(&bytes, sequence), "{sequence:?} missing after drop"); + } + assert_eq!(count(&bytes, "\x1b[?1049l"), 1); +} diff --git a/crates/thing-tui/tests/terminal.rs b/crates/thing-tui/tests/terminal.rs deleted file mode 100644 index 28372d4..0000000 --- a/crates/thing-tui/tests/terminal.rs +++ /dev/null @@ -1,175 +0,0 @@ -//! The writer's bytes and the guard's restore sequence, on a writer that is a `Vec` behind a -//! handle: nothing here touches a terminal. - -use std::io::{self, Write}; -use std::panic::{AssertUnwindSafe, catch_unwind}; -use std::sync::{Arc, Mutex}; - -use thing_contract::Rgba; -use thing_core::layout::CellStyle; -use thing_tui::{Op, Screen, Terminal, diff, write_enter, write_restore}; - -/// A writer the test keeps a handle on after the terminal that owns it is gone. -#[derive(Clone, Default)] -struct Shared(Arc>>); - -impl Shared { - fn bytes(&self) -> Vec { - self.0.lock().unwrap().clone() - } -} - -impl Write for Shared { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.0.lock().unwrap().extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -fn has(bytes: &[u8], needle: &str) -> bool { - bytes.windows(needle.len()).any(|w| w == needle.as_bytes()) -} - -fn count(bytes: &[u8], needle: &str) -> usize { - bytes.windows(needle.len()).filter(|w| *w == needle.as_bytes()).count() -} - -/// The bytes one `draw` writes, after the guard's own entering sequence. -fn drawn(ops: &[Op]) -> Vec { - let out = Shared::default(); - let mut terminal = Terminal::enter_without_raw_mode(out.clone()).unwrap(); - let before = out.bytes().len(); - terminal.draw(ops).unwrap(); - out.bytes()[before..].to_vec() -} - -fn rgb(r: u8, g: u8, b: u8) -> Option { - Some(Rgba { r, g, b, a: 255 }) -} - -#[test] -fn a_one_cell_diff_is_one_synchronized_update_with_one_move() { - let old = Screen::new(4, 2); - let mut new = old.clone(); - new.cells[4 + 2].glyph = "x".into(); - let ops = diff(&old, &new); - let bytes = drawn(&ops); - assert!(bytes.starts_with(b"\x1b[?2026h"), "{bytes:?}"); - assert!(bytes.ends_with(b"\x1b[?2026l"), "{bytes:?}"); - // One cursor move, to row 2 column 3 (1-based), and the glyph itself. - assert_eq!(count(&bytes, "H"), 1, "{bytes:?}"); - assert!(has(&bytes, "\x1b[2;3H"), "{bytes:?}"); - assert!(has(&bytes, "x")); -} - -#[test] -fn no_ops_write_nothing() { - assert_eq!(drawn(&[]), Vec::::new()); -} - -#[test] -fn a_move_beyond_the_terminal_addressing_saturates() { - let bytes = drawn(&[Op::MoveTo(70_000, 1)]); - assert!(has(&bytes, "\x1b[2;65535H"), "{bytes:?}"); -} - -#[test] -fn style_none_resets_the_colour_and_some_is_truecolor() { - let plain = drawn(&[Op::Style(None, None, CellStyle::default())]); - assert!(has(&plain, "\x1b[39m") && has(&plain, "\x1b[49m"), "{plain:?}"); - assert!(!has(&plain, "38;2") && !has(&plain, "48;2"), "{plain:?}"); - let colour = drawn(&[Op::Style(rgb(1, 2, 3), rgb(4, 5, 6), CellStyle::default())]); - assert!(has(&colour, "\x1b[38;2;1;2;3m"), "{colour:?}"); - assert!(has(&colour, "\x1b[48;2;4;5;6m"), "{colour:?}"); - // Foreground and background are not swapped. - let text = String::from_utf8(colour).unwrap(); - assert!(text.find("38;2;1;2;3").unwrap() < text.find("48;2;4;5;6").unwrap()); -} - -#[test] -fn each_attribute_is_set_and_each_absent_one_is_cleared() { - let off = drawn(&[Op::Style(None, None, CellStyle::default())]); - for cleared in ["\x1b[22m", "\x1b[23m", "\x1b[24m"] { - assert!(has(&off, cleared), "{cleared:?} missing in {off:?}"); - } - let on = drawn(&[Op::Style(None, None, CellStyle { bold: true, italic: true, underline: true })]); - for set in ["\x1b[1m", "\x1b[3m", "\x1b[4m"] { - assert!(has(&on, set), "{set:?} missing in {on:?}"); - } - for cleared in ["\x1b[22m", "\x1b[23m", "\x1b[24m"] { - assert!(!has(&on, cleared), "{cleared:?} present in {on:?}"); - } - // One attribute at a time: the other two stay cleared. - let bold = drawn(&[Op::Style(None, None, CellStyle { bold: true, ..CellStyle::default() })]); - assert!(has(&bold, "\x1b[1m") && has(&bold, "\x1b[23m") && has(&bold, "\x1b[24m") && !has(&bold, "\x1b[22m")); - let italic = drawn(&[Op::Style(None, None, CellStyle { italic: true, ..CellStyle::default() })]); - assert!(has(&italic, "\x1b[3m") && has(&italic, "\x1b[22m") && has(&italic, "\x1b[24m") && !has(&italic, "\x1b[23m")); - let underline = drawn(&[Op::Style(None, None, CellStyle { underline: true, ..CellStyle::default() })]); - assert!(has(&underline, "\x1b[4m") && has(&underline, "\x1b[22m") && has(&underline, "\x1b[23m") && !has(&underline, "\x1b[24m")); -} - -#[test] -fn print_writes_the_text_in_place() { - let bytes = drawn(&[Op::MoveTo(0, 0), Op::Print("h\u{e9}llo".into())]); - assert!(has(&bytes, "\x1b[1;1Hh\u{e9}llo"), "{bytes:?}"); -} - -/// What crossterm writes as bytes. On Windows, mouse capture is a console-mode call, not an escape -/// sequence, so it is not in the stream there. -const MOUSE: bool = cfg!(not(windows)); -const ENTER: [(&str, bool); 5] = [("\x1b[?1049h", true), ("\x1b[?25l", true), ("\x1b[?1000h", MOUSE), ("\x1b[?1004h", true), ("\x1b[?2004h", true)]; -const RESTORE: [(&str, bool); 5] = [("\x1b[?2004l", true), ("\x1b[?1004l", true), ("\x1b[?1000l", MOUSE), ("\x1b[?25h", true), ("\x1b[?1049l", true)]; - -fn modes(table: [(&'static str, bool); 5]) -> impl Iterator { - table.into_iter().filter(|(_, bytes)| *bytes).map(|(sequence, _)| sequence) -} - -#[test] -fn entering_writes_every_mode_and_restoring_undoes_each() { - let mut entered = Vec::new(); - write_enter(&mut entered).unwrap(); - for sequence in modes(ENTER) { - assert!(has(&entered, sequence), "{sequence:?} missing from enter {entered:?}"); - } - let mut restored = Vec::new(); - write_restore(&mut restored).unwrap(); - for sequence in modes(RESTORE) { - assert!(has(&restored, sequence), "{sequence:?} missing from restore {restored:?}"); - } - // The alternate screen is left last, so the user's screen returns after the modes are off. - assert!(restored.ends_with(b"\x1b[?1049l")); -} - -#[test] -fn dropping_the_guard_restores_once() { - let out = Shared::default(); - let terminal = Terminal::enter_without_raw_mode(out.clone()).unwrap(); - for sequence in modes(ENTER) { - assert!(has(&out.bytes(), sequence), "{sequence:?}"); - } - assert!(!has(&out.bytes(), "\x1b[?1049l"), "left before the guard dropped"); - drop(terminal); - let bytes = out.bytes(); - for sequence in modes(RESTORE) { - assert!(has(&bytes, sequence), "{sequence:?} missing after drop"); - } - assert_eq!(count(&bytes, "\x1b[?1049l"), 1); -} - -#[test] -fn a_panic_unwinding_through_the_guard_restores_the_terminal() { - let out = Shared::default(); - let inner = out.clone(); - let caught = catch_unwind(AssertUnwindSafe(move || { - let _terminal = Terminal::enter_without_raw_mode(inner).unwrap(); - panic!("forced"); - })); - assert!(caught.is_err()); - let bytes = out.bytes(); - for sequence in modes(RESTORE) { - assert!(has(&bytes, sequence), "{sequence:?} missing after the panic"); - } -}