diff --git a/crates/thing-tui/src/terminal.rs b/crates/thing-tui/src/terminal.rs index 9af0d8e..6111f81 100644 --- a/crates/thing-tui/src/terminal.rs +++ b/crates/thing-tui/src/terminal.rs @@ -179,11 +179,14 @@ fn write_enter(out: &mut W) -> io::Result<()> { tolerate(queue!(out, EnableBracketedPaste)) } -/// The bytes that undo `write_enter`, every one attempted even when an earlier one failed. +/// The bytes that undo `write_enter`, every one attempted even when an earlier one failed. A frame +/// that failed part-way left its synchronized update open, so that is closed first: a terminal +/// that holds the display until the update ends would not paint the screen restored after it. fn write_restore(out: &mut W) -> io::Result<()> { + let update = queue!(out, EndSynchronizedUpdate); let paste = tolerate(queue!(out, DisableBracketedPaste)); let rest = queue!(out, DisableFocusChange, DisableMouseCapture, Show, LeaveAlternateScreen); - paste.and(rest) + update.and(paste).and(rest) } /// Chain a hook ahead of the current one: a panic on a thread that owns an entered guard gives that diff --git a/crates/thing-tui/src/terminal/guard_tests.rs b/crates/thing-tui/src/terminal/guard_tests.rs index fbe08b3..c85d312 100644 --- a/crates/thing-tui/src/terminal/guard_tests.rs +++ b/crates/thing-tui/src/terminal/guard_tests.rs @@ -255,3 +255,44 @@ fn dropping_the_guard_restores_once() { } assert_eq!(count(&bytes, "\x1b[?1049l"), 1); } + +/// A writer whose next write after `arm` more succeeds fails once, then the writer is sound again. +struct Flaky { + out: Shared, + left: Arc, +} + +impl Write for Flaky { + fn write(&mut self, buf: &[u8]) -> io::Result { + use std::sync::atomic::Ordering::SeqCst; + match self.left.load(SeqCst) { + 0 => { + self.left.store(-1, SeqCst); + return Err(io::Error::other("forced write failure")); + } + n if n > 0 => self.left.store(n - 1, SeqCst), + _ => {} + } + self.out.write(buf) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn an_error_mid_draw_does_not_leave_the_synchronized_update_open() { + spy(); + let out = Shared::default(); + let left = Arc::new(std::sync::atomic::AtomicIsize::new(-1)); + let mut terminal = Terminal::start(Flaky { out: out.clone(), left: left.clone() }, false).unwrap(); + // The begin goes through; the cursor move after it fails. + left.store(1, std::sync::atomic::Ordering::SeqCst); + assert!(terminal.draw(&[Op::MoveTo(0, 0), Op::Print("x".into())]).is_err()); + assert_eq!(count(&out.bytes(), "\x1b[?2026h"), 1); + assert_eq!(count(&out.bytes(), "\x1b[?2026l"), 0, "the frame never reached its end"); + drop(terminal); + let bytes = String::from_utf8(out.bytes()).unwrap(); + let end = bytes.rfind("\x1b[?2026l").expect("the restore closes the open update"); + assert!(end < bytes.rfind(LEAVE).unwrap(), "closed before the alternate screen is left"); +}