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 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-29 02:10:41 +01:00
commit 63a2f43c1d
4 changed files with 147 additions and 184 deletions

View file

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

View file

@ -61,6 +61,20 @@ fn guards() -> MutexGuard<'static, Vec<(ThreadId, Arc<dyn Restore>)>> {
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::<Vec<u8>>;
/// ```
///
/// ```compile_fail
/// let _ = thing_tui::write_restore::<Vec<u8>>;
/// ```
///
/// ```compile_fail
/// let _ = thing_tui::Terminal::enter_without_raw_mode(Vec::<u8>::new());
/// ```
pub struct Terminal<W: Write + Send + 'static> {
shared: Arc<Shared<W>>,
}
@ -83,11 +97,6 @@ impl<W: Write + Send + 'static> Terminal<W> {
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> {
Self::start(out, false)
}
fn start(out: W, raw: bool) -> io::Result<Self> {
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<W: Write>(out: &mut W) -> io::Result<()> {
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<()> {
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)

View file

@ -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<u8> {
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<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_write_nothing() {
assert_eq!(drawn(&[]), Vec::<u8>::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<Item = &'static str> {
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);
}

View file

@ -1,175 +0,0 @@
//! 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_write_nothing() {
assert_eq!(drawn(&[]), Vec::<u8>::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<Item = &'static str> {
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");
}
}