Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,41 @@ reads that marker.
`xterm-256color`, and a recording with no frame takes the terminal's
size at `record` rather than 80x24. A test that bounded `timestamp` by
the export should bound it by the call to `record`. (#850)
- A kitty control block that repeats a key is read with the key's last
value, as kitty reads it: `a=t,…,a=T` transmits and places,
`a=T,c=3,…,c=5` covers five columns, `a=q,…,a=T` is a transmission and
not a query, and `a=q,i=31,…,i=32` is answered `i=32`. Each reader took
the first value, and the query test took any `a=q` in the block, so an
application that appends overrides to a set of defaults was read with
the defaults. A test that relied on the first of two values should
expect the last. (#843)
- A kitty graphics escape that kitty 0.49's parser refuses is no command:
an unknown key (`W=`, or `e=`, the feature query kitty 0.50 added), a
flag value outside its set (`o=x`), a value with no digits (`X=-1`) or
past `u32`, anything but `,` or `;` after a value, and a `,` right
before the `;`. Its bytes are counted, but no image is captured or
placed, the cursor does not move, an upload in progress goes on, and a
query is not answered: a malformed or feature query got `OK`. A
transmission or query declaring more than 10000 pixels a side (`s=`,
`v=`) is refused as kitty refuses it, and the query is answered with
kitty's `EINVAL` error. `m=` is read as kitty reads it, any nonzero
value meaning more chunks follow, where only `m=1` did. A test that
expected an image or an `OK` from such an escape should expect none.
(#841)
- `wait_until` (and the waits built on it: `snapshot_after`,
`resize_and_wait`, the regex waits) spaces its evaluations by their own
cost: after one that took d, the next waits until d has passed, then
looks at the screen as it is by then. An evaluation snapshots the grid
under the lock the reader needs for every read, so on a large grid the
reader got one read of at most 8 KiB in per snapshot, and one paint of
a 1000x1000 grid took 8 to 14 s to wait through, past the default 5 s
timeout; it now takes 1.7 s in release and 3.3 s in debug. On an
ordinary screen d is microseconds and nothing changes. The
`TerminalBuilder::size` table is measured again: a 1000x1000 snapshot
costs about 90 ms in release and 620 ms in debug, not the 10 ms and
297 ms it claimed. A predicate that counted its evaluations, or that
held only on a screen lasting less than one evaluation on a large grid,
should wait on the last thing painted instead. (#854)

### Fixed

Expand Down Expand Up @@ -290,6 +325,16 @@ reads that marker.
PTY nobody held. The session's other groups are now hung up and killed
with the child's. macOS and the other Unixes still stop the child's
group only, as `docs/LIMITATIONS.md` says. (#835)
- A snapshot shares the retained history with the emulator and with the
snapshots before it, rather than collecting an index of every row, so a
wait evaluation and a recorded frame no longer cost O(history). The
history is kept in sealed chunks of 256 rows: a snapshot with no row
scrolled since the last is one refcount, and one after a scroll a
pointer per chunk. On an 80x24 terminal with 32,000 rows of history,
one snapshot took 606 µs and now takes 128 µs, as at 1,000 rows, and a
recording of 1,000 frames grew the process by 591 MiB and now by
102 MiB. The `scrollback_styles` and `record_budget` docs say what a
snapshot and a frame now hold. (#856)

## [0.11.11] - 2026-11-25

Expand Down
329 changes: 248 additions & 81 deletions crates/termlens/src/emu/seq.rs

Large diffs are not rendered by default.

217 changes: 201 additions & 16 deletions crates/termlens/src/emu/vt100.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::graphics::{
kitty_cells, GraphicsAction, GraphicsPayload, GraphicsProtocol, GraphicsSeen, Placement,
HISTORY,
};
use crate::screen::{Cell, Color, MouseMode, Screen, Style, TermState};
use crate::screen::{Cell, Color, MouseMode, RowLog, Screen, Style, TermState};
use crate::Graphics;

pub(crate) struct Vt100Emulator {
Expand All @@ -37,13 +37,14 @@ pub(crate) struct Vt100Emulator {
///
/// Materialized here — once per read that scrolled — rather than in
/// `snapshot`, which runs far more often (every wait evaluation on a
/// chatty stream). A snapshot then costs one `Arc` clone per row
/// instead of rebuilding the whole history.
history: VecDeque<Arc<str>>,
/// chatty stream). Kept in sealed chunks, so a snapshot shares it
/// rather than copying an index of it: one refcount until the history
/// next changes, one per chunk once it has (#856).
history: RowLog<Arc<str>>,
/// The same rows as cells, when the terminal was built to retain
/// styles in history (#146); `None` otherwise, so a suite that never
/// asks pays nothing. Kept in lockstep with `history`, one entry each.
history_cells: Option<VecDeque<Arc<[Cell]>>>,
history_cells: Option<RowLog<Arc<[Cell]>>>,
/// Rows of vt100's own scrollback already copied into `history`, so a
/// read that scrolled nothing costs one length check.
captured: usize,
Expand Down Expand Up @@ -139,11 +140,11 @@ impl Vt100Emulator {
// of history onto the grid, and the shadow's grid has to get the
// same rows back to stay in lockstep.
shadow: AttrShadow::new(rows, cols, scrollback_len),
history_cells: styled_history.then(VecDeque::new),
history_cells: styled_history.then(RowLog::default),
colors: ColorNormalizer::new(),
scrollback_len,
frame_started: None,
history: VecDeque::new(),
history: RowLog::default(),
captured: 0,
history_reset: false,
graphics: Arc::new(Vec::new()),
Expand Down Expand Up @@ -1313,11 +1314,8 @@ impl Emulator for Vt100Emulator {
graphics: GraphicsSeen::new(self.tracker.graphics(), Arc::clone(&self.graphics)),
// Filled in by the terminal, which owns the frame count.
repaints: 0,
scrollback: self.history.iter().cloned().collect(),
scrollback_cells: self
.history_cells
.as_ref()
.map(|cells| cells.iter().cloned().collect()),
scrollback: self.history.shared(),
scrollback_cells: self.history_cells.as_ref().map(RowLog::shared),
// The backend's own record of a soft wrap, per row (#265).
wrapped: (0..rows).map(|row| screen.row_wrapped(row)).collect(),
insert_mode: self.tracker.insert_mode(),
Expand Down Expand Up @@ -3864,6 +3862,150 @@ mod tests {
}
}

/// [`graphics_emu`] fed one byte at a time, and [`observed`] of both
/// feeds checked equal: no kitty escape may read differently for where
/// the PTY split it.
fn graphics_emu_bytewise(
support: Graphics,
rows: u16,
cols: u16,
bytes: &[u8],
) -> Vt100Emulator {
let whole = graphics_emu(support, rows, cols, bytes);
let mut bytewise =
Vt100Emulator::new(rows, cols, 100, crate::graphics::DEFAULT_CAPTURE, false);
bytewise.declare_graphics(support, Some((10, 20)));
for &byte in bytes {
feed_all(&mut bytewise, &[byte]);
}
assert_eq!(
observed(&whole),
observed(&bytewise),
"{}",
String::from_utf8_lossy(bytes)
);
assert_eq!(
whole.snapshot().graphics().total(),
bytewise.snapshot().graphics().total()
);
whole
}

/// A control block that repeats a key is read with the key's last
/// value, as kitty's `parse_graphics_code` stores each value over the
/// last (#843): the action, the size in cells, and whether the escape is
/// a query at all. The first value was read.
#[test]
fn a_repeated_kitty_key_takes_its_last_value() {
for (control, images, x) in [
("a=t,f=24,s=1,v=1,c=3,r=2,a=T", 1, (1, 3)),
("a=T,f=24,s=1,v=1,c=3,r=2,c=5", 1, (1, 5)),
("a=q,i=31,f=24,s=1,v=1,c=3,r=2,a=T", 1, (1, 3)),
("a=T,f=24,s=1,v=1,c=3,r=2,a=q,i=31", 0, (0, 0)),
("a=T,f=24,s=1,v=1,c=3,r=2,C=0,C=1", 1, (0, 0)),
] {
let wire = format!("\x1b_G{control};AAAA\x1b\\X");
let emu = graphics_emu_bytewise(Graphics::Kitty, 5, 20, wire.as_bytes());
assert_eq!(x_at(&emu), Some(x), "{control}");
assert_eq!(emu.snapshot().graphics().total(), images, "{control}");
}
}

/// An escape kitty's parser refuses is no command (#841): no image,
/// and the cursor stays, whole or a byte at a time. Each was placed.
#[test]
fn a_kitty_escape_kittys_parser_refuses_moves_nothing() {
for control in [
"a=T,f=24,s=1,v=1,c=3,r=2,",
"a=T,f=24,s=1,v=1,c=3,r=2,W=5",
"a=T,f=24,s=1,v=1,c=3,r=2,o=x",
"a=T,f=24,s=1,v=1,c=3,r=2,X=-1",
"a=T,f=24,s=1,v=1,c=3,r=2,i=4294967296",
"a=T,f=24,s=20000,v=1,c=3,r=2",
"a=T,f=24,s=1,v=1,c=3,r=2,e=T",
] {
let wire = format!("\x1b_G{control};AAAA\x1b\\X");
let emu = graphics_emu_bytewise(Graphics::Kitty, 5, 20, wire.as_bytes());
assert_eq!(x_at(&emu), Some((0, 0)), "{control}");
assert_eq!(emu.snapshot().graphics().total(), 0, "{control}");
}
}

/// A bounded random check of kitty control blocks, valid and not, mixed
/// with text, CR/LF and SGR: every stream reads the same whole as a
/// byte at a time (#841, #843). Ignored for its run time; run it with
/// `--ignored` after a change to the kitty parsing.
#[test]
#[ignore = "a random-stream sweep, run by hand"]
fn kitty_control_blocks_read_the_same_whole_and_bytewise() {
const PIECES: &[&str] = &[
"a=T",
"a=t",
"a=q",
"a=p",
"a=d",
"a=x",
"a=",
"i=1",
"i=31",
"i=4294967296",
"I=7",
"f=24",
"f=32",
"s=1",
"v=1",
"s=20000",
"c=3",
"r=2",
"c=",
"C=1",
"X=-1",
"z=-1",
"m=1",
"m=0",
"q=1",
"q=2",
"e=T",
"W=5",
"o=z",
"o=x",
"t=d",
"t=f",
"d=I",
"d=b",
"p=1",
"U=1",
];
const FILLER: &[&str] = &["X", "ab", "\r\n", "\n", "\x1b[1m", "\x1b[0m", "\x1b[31;4m"];
let mut state: u64 = 0x2545_f491_4f6c_dd1d;
let mut next = |bound: usize| {
// xorshift64*: deterministic, so a failure reproduces.
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
(state.wrapping_mul(0x2545_f491_4f6c_dd1d) >> 33) as usize % bound
};
for _ in 0..4000 {
let mut wire = String::new();
for _ in 0..1 + next(4) {
wire.push_str(FILLER[next(FILLER.len())]);
let keys: Vec<&str> = (0..next(6)).map(|_| PIECES[next(PIECES.len())]).collect();
let mut control = keys.join(",");
if next(5) == 0 {
control.push(',');
}
wire.push_str("\x1b_G");
wire.push_str(&control);
if next(4) != 0 {
wire.push_str(";AAAA");
}
wire.push_str("\x1b\\");
}
wire.push('X');
graphics_emu_bytewise(Graphics::Kitty, 5, 20, wire.as_bytes());
}
}

#[test]
fn a_kitty_placement_wraps_and_scrolls_as_kitty_does() {
// Past the right edge: the start of the next row.
Expand Down Expand Up @@ -4341,17 +4483,60 @@ mod tests {
// the cursor wraps: the last row's start.
("s=1,v=1,c=4294967295", (5, 0)),
("s=1,v=1,r=4294967295", (5, 0)),
// 429496730 columns, one row: wraps to the next row.
("s=4294967295,v=1,X=5", (1, 0)),
// One column, 214748366 rows: to the bottom, one column on.
("s=1,v=4294967295,Y=7", (5, 1)),
// The largest image kitty loads, 10000 pixels a side (#841):
// 1001 columns, one row, wraps to the next row.
("s=10000,v=1,X=5", (1, 0)),
// One column, 501 rows: to the bottom, one column on.
("s=1,v=10000,Y=7", (5, 1)),
// Past it, kitty refuses the image, which then moves nothing.
("s=4294967295,v=1,X=5", (0, 0)),
("s=1,v=4294967295,Y=7", (0, 0)),
] {
let wire = format!("\x1b_Ga=T,f=24,{keys};AAAA\x1b\\X");
let emu = graphics_emu(Graphics::Kitty, 6, 10, wire.as_bytes());
assert_eq!(x_at(&emu), Some(at), "{keys}");
}
}

/// A snapshot shares the retained history rather than copying an index
/// of it (#856): two snapshots with no row scrolled between them hold
/// it in one place, so the thousand frames of a recording over 32,000
/// rows of history hold one copy, not a thousand. Every snapshot
/// collected its own, so each wait and each frame cost O(history).
#[test]
fn snapshots_share_the_history_rather_than_copy_it() {
use std::fmt::Write as _;
let mut emu = Vt100Emulator::new(24, 80, 32_000, crate::graphics::DEFAULT_CAPTURE, false);
let mut text = String::new();
for row in 0..32_030 {
write!(text, "history row {row:08}\r\n").unwrap();
}
feed_all(&mut emu, text.as_bytes());
let first = emu.snapshot();
assert_eq!(first.scrollback_rows(), 32_000);
for frame in 0..1000 {
let wire = format!("\x1b[?2026h\x1b[1;1Hframe {frame:08}\x1b[?2026l");
feed_all(&mut emu, wire.as_bytes());
let screen = emu.snapshot();
assert!(screen.contains(&format!("frame {frame:08}")));
for row in [0, 31_999] {
assert!(
std::ptr::eq(first.history_slot(row), screen.history_slot(row)),
"frame {frame}, history row {row}"
);
}
}
// A row scrolled in between: a history of its own, sharing every
// row it has in common with the last.
feed_all(&mut emu, b"\x1b[24;1H\r\nscrolled");
let after = emu.snapshot();
assert_eq!(after.scrollback_rows(), 32_000);
assert!(std::ptr::eq(
first.history_slot(1000),
after.history_slot(999)
));
}

#[test]
fn history_rows_keep_the_width_they_were_captured_at() {
// Documented decision (`Terminal::resize`): history is not reflowed
Expand Down
Loading
Loading