diff --git a/CHANGELOG.md b/CHANGELOG.md index 470ee1b..37128b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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 diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index b2d885b..1718802 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -56,7 +56,9 @@ use std::sync::Arc; use super::MouseEncoding; -use crate::graphics::{GraphicsBuilder, GraphicsCounts, GraphicsPayload, Placement, SixelMeter}; +use crate::graphics::{ + GraphicsBuilder, GraphicsCounts, GraphicsPayload, KittyControl, Placement, SixelMeter, +}; use crate::screen::{Clipboard, Link, MouseMode, MouseModes}; /// OSC strings are captured whole (titles must not truncate), but bounded: @@ -603,16 +605,6 @@ pub(crate) enum Query { Unanswerable(String), } -/// The numeric value of `key` in a kitty control block (`i=3,a=q`), if it -/// carries one. Keys are comma-separated `name=value` pairs. -fn kitty_key(control: &[u8], key: &[u8]) -> Option { - control - .split(|&b| b == b',') - .find_map(|pair| pair.strip_prefix(key)) - .and_then(|digits| std::str::from_utf8(digits).ok()) - .and_then(|digits| digits.parse().ok()) -} - /// What kitty's loader made of a query's data, which decides whether kitty /// answers it, and with what (#672). /// @@ -632,6 +624,10 @@ pub(crate) enum KittyLoad { /// Sent to a load whose image kitty had already removed: kitty answers /// `EILSEQ` ("More payload loading refers to non-existent image"). Gone, + /// Started a load declaring more than 10000 pixels a side, which kitty + /// refuses before loading anything: it answers `EINVAL` ("Image too + /// large, width or height greater than 10000") (#841). + TooLarge, } /// What a kitty escape arriving in the middle of a chunked upload does to @@ -658,28 +654,43 @@ enum MidUpload { } impl MidUpload { - fn of(keys: &[u8]) -> Self { - let action = keys - .split(|&b| b == b',') - .find_map(|pair| pair.strip_prefix(b"a=")); - match action { - None | Some(b"t" | b"T" | b"f") => { - let direct = keys - .split(|&b| b == b',') - .find_map(|pair| pair.strip_prefix(b"t=")) - .is_none_or(|medium| medium == b"d"); + fn of(control: &KittyControl) -> Self { + match control.flag(b'a') { + None | Some(b't' | b'T' | b'f') => { + let direct = control.flag(b't').is_none_or(|medium| medium == b'd'); if direct { MidUpload::Continues } else { MidUpload::Aborts } } - Some(b"d") => MidUpload::Aborts, + Some(b'd') => MidUpload::Aborts, Some(_) => MidUpload::Beside, } } } +/// Whether another chunk of the load follows. kitty reads `m=` as a number +/// and any nonzero one as "more" (`if (!g->more)` in `graphics.c`), where +/// termlens took only `m=1`. +fn more(control: &KittyControl) -> bool { + control.number(b'm').is_some_and(|more| more != 0) +} + +/// kitty's `MAX_IMAGE_DIMENSION` (`graphics.c`, 0.49.2). +const KITTY_MAX_DIMENSION: u32 = 10_000; + +/// Whether a command starting a load declares an image kitty refuses +/// before loading anything: "Image too large, width or height greater than +/// 10000" (`handle_add_command`, `graphics.c:953`), checked only where it +/// starts a new image (`init_img`), never on the next chunk of a load in +/// progress (#841). +fn too_large(control: &KittyControl) -> bool { + b"sv" + .iter() + .any(|&key| control.number(key).unwrap_or(0) > KITTY_MAX_DIMENSION) +} + /// The reply kitty owes a transmission or a placement, which termlens does /// not send (#680). /// @@ -710,18 +721,15 @@ impl KittyAsk { /// What a transmission (`a=t`, `a=T`, no action) or a placement (`a=p`) /// asks for; `None` for any other action. Frames (`a=f`) and composes /// (`a=c`), which kitty answers too, are not covered. - fn of(keys: &[u8], shape: String) -> Option { - let action = keys - .split(|&b| b == b',') - .find_map(|pair| pair.strip_prefix(b"a=")); - if !matches!(action, None | Some(b"t" | b"T" | b"p")) { + fn of(control: &KittyControl, shape: String) -> Option { + if !matches!(control.flag(b'a'), None | Some(b't' | b'T' | b'p')) { return None; } - let nonzero = |name: &[u8]| kitty_key(keys, name).is_some_and(|value| value != 0); + let nonzero = |key: u8| control.number(key).is_some_and(|value| value != 0); Some(Self { - id: nonzero(b"i="), - number: nonzero(b"I="), - quiet: kitty_key(keys, b"q=").unwrap_or(0), + id: nonzero(b'i'), + number: nonzero(b'I'), + quiet: control.number(b'q').unwrap_or(0), shape, }) } @@ -758,15 +766,6 @@ fn kitty_completed( } } -/// Whether a kitty control block sets `key` to exactly `value`. -fn key_is(control: &[u8], key: &[u8], value: &[u8]) -> bool { - control.split(|&b| b == b',').any(|pair| { - pair.strip_prefix(key) - .and_then(|rest| rest.strip_prefix(b"=")) - == Some(value) - }) -} - /// Whether `CSI Ps ; Ps t` with `count` parameters, the first two `first` /// and `second`, is one of xterm's window reports: a question, whose /// reply the responder gives (`14`, `16` and `18`, alone) or names in a @@ -1093,6 +1092,11 @@ pub(crate) struct SeqTracker { /// introducer of an APC to its first `;`, or to a first byte other than /// `G`, which makes it no kitty escape at all. kitty_control_open: bool, + /// True once a `;` closed that control block, so that a payload, empty + /// or not, follows it: kitty reads that `;` as part of the block, and + /// refuses one ending `,;` where it accepts one ending on its `,` + /// (#841). + kitty_payload: bool, /// Every byte of the current DCS-class string, up to the capture bound — /// the image data itself, which the 128-byte head deliberately is not. /// Kept only while the bound allows; `dcs_body_full` says whether it is @@ -1192,6 +1196,7 @@ impl SeqTracker { dcs_head_len: 0, kitty_control: Vec::new(), kitty_control_open: false, + kitty_payload: false, dcs_body: Vec::new(), dcs_body_full: true, sixel_meter: SixelMeter::default(), @@ -1762,6 +1767,7 @@ impl SeqTracker { self.dcs_head_len = 0; self.kitty_control.clear(); self.kitty_control_open = introducer == b'_'; + self.kitty_payload = false; self.dcs_body.clear(); self.dcs_body_full = true; self.sixel_meter = SixelMeter::default(); @@ -2367,20 +2373,28 @@ impl SeqTracker { && self.dcs_data_len >= 2 && self.dcs_head[..usize::from(self.dcs_head_len)].first() == Some(&b'G') { - let control = self.kitty_control.clone(); - // The control block is `G` followed by the comma-separated keys. - let keys = control.strip_prefix(b"G").unwrap_or(&control); - let is_query = keys.split(|&b| b == b',').any(|pair| pair == b"a=q"); - if !is_query { + // The control block is `G` followed by the comma-separated keys, + // read once, so that every reader below, the query test with + // them, sees the value kitty acts on: a key's last (#843). + let keys = self.kitty_control.strip_prefix(b"G").unwrap_or(&[]); + let Some(keys) = KittyControl::parse(keys, self.kitty_payload) else { + // kitty's parser refuses it before the graphics manager + // sees it (#841): no image, no reply, no cursor move, and an + // upload in progress left as it was. Its bytes crossed the + // wire all the same. + self.counts.bytes += self.dcs_data_len; + return SeqEvent::None; + }; + if keys.flag(b'a') != Some(b'q') { let at = self.dcs_payload_start(); if self.orphaned_load { - match MidUpload::of(keys) { + match MidUpload::of(&keys) { // kitty's `handle_add_command` takes it as the next // chunk of the load, finds the image that load was // for gone, and refuses it (`EILSEQ`), clearing the // load: the escape is spent, and no image comes of // it (#672). Its bytes crossed the wire all the same. - MidUpload::Continues if !key_is(keys, b"a", b"f") => { + MidUpload::Continues if keys.flag(b'a') != Some(b'f') => { self.orphaned_load = false; self.counts.bytes += self.dcs_data_len; return SeqEvent::None; @@ -2395,7 +2409,7 @@ impl SeqTracker { } } if self.building.in_progress() { - match MidUpload::of(keys) { + match MidUpload::of(&keys) { MidUpload::Continues => {} // A delete is never an upload's last chunk: it // aborts the upload in progress and is then a @@ -2407,7 +2421,7 @@ impl SeqTracker { // (#636). It was taken as the upload's next chunk. MidUpload::Beside => { let mut beside = GraphicsBuilder::default(); - beside.kitty(keys); + beside.kitty(&keys); beside.chunk( self.dcs_data_len, &self.dcs_body[at..], @@ -2418,7 +2432,7 @@ impl SeqTracker { if let Some((payload, _)) = &completed { self.counts.record(payload); } - let unanswered = KittyAsk::of(keys, self.seq_printable()) + let unanswered = KittyAsk::of(&keys, self.seq_printable()) .filter(|ask| ask.refused() || ask.answered(0)) .map(|ask| ask.shape); return kitty_completed(completed, unanswered); @@ -2434,13 +2448,23 @@ impl SeqTracker { // chunk's holds at the last (#758). let mut unanswered = None; if !self.building.in_progress() { - let ask = KittyAsk::of(keys, self.seq_printable()); + let ask = KittyAsk::of(&keys, self.seq_printable()); if let Some(ask) = ask.as_ref().filter(|ask| ask.refused()) { unanswered = Some(ask.shape.clone()); } + // A transmission starting a load kitty refuses as too + // large is no image (#841). kitty's error goes to the + // command that started its *previous* load, since + // `start_command` is set only past the check, so what + // it says is not this escape's to name. The refusal of + // `i=` with `I=` comes first in kitty, and is named. + if matches!(keys.flag(b'a'), None | Some(b't' | b'T')) && too_large(&keys) { + self.counts.bytes += self.dcs_data_len; + return kitty_completed(None, unanswered); + } self.upload_ask = ask.filter(|ask| !ask.refused()); } else if let Some(ask) = self.upload_ask.as_mut() { - if let Some(quiet) = kitty_key(keys, b"q=").filter(|&quiet| quiet != 0) { + if let Some(quiet) = keys.number(b'q').filter(|&quiet| quiet != 0) { ask.quiet = quiet; } } @@ -2448,17 +2472,17 @@ impl SeqTracker { // another follows; the transmission is not an image until // one arrives without it, and counting each escape instead // reported a 4.9 KB chart as two pictures. - self.building.kitty(keys); + self.building.kitty(&keys); self.building.chunk( self.dcs_data_len, &self.dcs_body[at..], self.dcs_body_full, self.capture, ); - if key_is(keys, b"m", b"1") { + if more(&keys) { return kitty_completed(None, unanswered); } - let quiet = kitty_key(keys, b"q=").unwrap_or(0); + let quiet = keys.number(b'q').unwrap_or(0); if let Some(ask) = self.upload_ask.take().filter(|ask| ask.answered(quiet)) { unanswered = Some(ask.shape); } @@ -2468,7 +2492,7 @@ impl SeqTracker { } return kitty_completed(completed, unanswered); } - return self.kitty_query(keys); + return self.kitty_query(&keys); } // Sixel: `DCS q ST`, with no intermediate byte. The // intermediate is the whole distinction from the two DCS questions @@ -2575,15 +2599,15 @@ impl SeqTracker { /// /// A command naming both an image id and an image number is refused /// before anything else is looked at, and a query without an id right - /// after; neither reaches the loader. Nor does a feature query (`e=`): - /// kitty 0.49 rejects the key outright, and the development branch that - /// adds it says "A feature query transmits no image data, so it must not - /// interfere with any chunked load that is in progress". Every other - /// query hands its - /// data to `handle_add_command` as a transmission would, so: + /// after; neither reaches the loader. A feature query (`e=`) never gets + /// here: kitty 0.49 has no such key, so its parser refuses the escape + /// (#841). Every other query hands its data to `handle_add_command` as + /// a transmission would, so: /// /// - from a file or shared memory (`t=` other than `d`), it starts a /// load of its own, and the upload in progress is dropped; + /// - starting a load of its own, it is refused if it declares more than + /// 10000 pixels a side (`EINVAL`), and nothing is loaded; /// - with the data in the escape and an upload in progress, it *is* the /// upload's next chunk: its data is appended, and without `m=1` it is /// the last one, so the upload's image is complete — and placed, for @@ -2594,22 +2618,23 @@ impl SeqTracker { /// query's own. Nothing is answered, and the loader is left naming an /// image that is gone, so the next chunk is refused; /// - handed to a loader in that state, it is refused (`EILSEQ`). - fn kitty_query(&mut self, keys: &[u8]) -> SeqEvent { - let id = kitty_key(keys, b"i="); - let number = kitty_key(keys, b"I="); + fn kitty_query(&mut self, keys: &KittyControl) -> SeqEvent { + let id = keys.number(b'i'); + let number = keys.number(b'I'); let nonzero = |value: Option| value.is_some_and(|value| value != 0); - let feature_query = keys - .split(|&b| b == b',') - .any(|pair| pair.starts_with(b"e=")); let mut load = KittyLoad::Loaded; let mut completed = None; - if nonzero(id) && !nonzero(number) && !feature_query { - let direct = keys - .split(|&b| b == b',') - .find_map(|pair| pair.strip_prefix(b"t=")) - .is_none_or(|medium| medium == b"d"); - let more = key_is(keys, b"m", b"1"); - if !direct { + if nonzero(id) && !nonzero(number) { + let direct = keys.flag(b't').is_none_or(|medium| medium == b'd'); + let more = more(keys); + // `handle_add_command` drops any load and then refuses an image + // over 10000 pixels a side, where the query starts a load + // rather than joining one (#841). + let joins = direct && (self.orphaned_load || self.building.in_progress()); + if !joins && too_large(keys) { + self.abandon_upload(); + load = KittyLoad::TooLarge; + } else if !direct { self.abandon_upload(); } else if self.orphaned_load { self.orphaned_load = false; @@ -2637,8 +2662,8 @@ impl SeqTracker { let query = Query::KittyGraphics { id, number, - placement: kitty_key(keys, b"p="), - quiet: kitty_key(keys, b"q=").unwrap_or(0), + placement: keys.number(b'p'), + quiet: keys.number(b'q').unwrap_or(0), load, shape: self.seq_printable(), }; @@ -2680,6 +2705,7 @@ impl SeqTracker { return; } if b == b';' || (self.kitty_control.is_empty() && b != b'G') { + self.kitty_payload = b == b';' && !self.kitty_control.is_empty(); self.kitty_control_open = false; } else if self.kitty_control.len() < KITTY_CONTROL_MAX { self.kitty_control.push(b); @@ -3807,16 +3833,15 @@ mod tests { /// The queries that never reach kitty's loader leave an upload alone: /// one naming both an image id and an image number (refused before /// anything else, "Must not specify both image id and image number"), - /// one without an id ("Query graphics command without image id"), and a - /// feature query (`e=`), which kitty 0.49 rejects as a key it does not - /// know and later kitty keeps clear of any load in progress. + /// and one without an id ("Query graphics command without image id"). + /// A feature query (`e=`) is no query at all to kitty 0.49: see + /// `an_escape_kittys_parser_refuses_is_no_command`. #[test] fn a_kitty_query_that_never_reaches_the_loader_leaves_an_upload_alone() { for query in [ &b"\x1b_Ga=q,i=31,I=7;BBBB\x1b\\"[..], b"\x1b_Ga=q;BBBB\x1b\\", b"\x1b_Ga=q,i=0;BBBB\x1b\\", - b"\x1b_Ga=q,i=31,e=T;BBBB\x1b\\", ] { let wire = [UPLOAD_OF_5, query, b"\x1b_Gm=0;CCCC\x1b\\"].concat(); let (seen, queries, _) = kitty_events(&wire); @@ -3834,6 +3859,116 @@ mod tests { } } + /// An escape kitty's `parse_graphics_code` (0.49.2) refuses never + /// reaches its graphics manager (#841): no image, no query, nothing + /// named, and an upload in progress goes on as if it had not come. Its + /// bytes are counted, as every graphics escape's are. Each was read a + /// key at a time and went ahead. + #[test] + fn an_escape_kittys_parser_refuses_is_no_command() { + for control in [ + // A `,` before the `;`: kitty reads the `;` as a key. + &b"a=T,f=24,s=1,v=1,c=3,r=2,"[..], + // A key kitty does not have, `e` among them before 0.50. + b"a=T,f=24,s=1,v=1,c=3,r=2,W=5", + b"a=q,i=31,e=T,U=1,C=1", + // A flag value outside its set, and one of two bytes. + b"a=T,f=24,s=1,v=1,c=3,r=2,o=x", + b"a=TT,f=24,s=1,v=1", + b"a=T,d=b", + b"a=T,t=x", + // No digits, a sign on an unsigned key, and digits past `u32` + // or past ten. + b"a=T,f=24,s=1,v=1,c=3,r=2,X=-1", + b"a=T,f=24,s=1,v=1,c=", + b"a=T,i=4294967296", + b"a=T,i=00000000001", + b"a=T,z=-", + // No `=`, or no `,` after a value. + b"a=T,f", + b"aT", + b"a=T,f=24i=1", + b"a=q,i=31,s=1,v=1,f=24,", + ] { + let shown = String::from_utf8_lossy(control); + let escape = [b"\x1b_G", control, b";AAAA\x1b\\"].concat(); + let (seen, queries, tracker) = kitty_events(&escape); + assert!(seen.is_empty(), "{shown}: {seen:?}"); + assert!(queries.is_empty(), "{shown}: {queries:?}"); + assert_eq!(tracker.graphics().kitty, 0, "{shown}"); + assert_eq!(tracker.graphics().bytes, wire_cost(&[&escape]), "{shown}"); + // Mid-upload, it is not the upload's next chunk: the chunk after + // it is, and completes the image. + let wire = [UPLOAD_OF_5, &escape, b"\x1b_Gm=0;CCCC\x1b\\"].concat(); + let (seen, _, _) = kitty_events(&wire); + assert_eq!(seen.len(), 1, "{shown}: {seen:?}"); + assert_eq!(seen[0].data(), Some(&b"AAAACCCC"[..]), "{shown}"); + } + } + + /// What kitty's parser accepts goes ahead: a block with no keys, a + /// trailing `,` with no `;` after it, the largest value, the signed + /// keys, leading zeros, and the largest image kitty loads (#841). + #[test] + fn an_escape_kittys_parser_accepts_goes_ahead() { + for escape in [ + &b"\x1b_G;AAAA\x1b\\"[..], + b"\x1b_Ga=T,f=24,s=1,v=1,\x1b\\", + b"\x1b_Ga=T,f=24,s=1,v=1,i=4294967295,z=-2147483648,H=7,V=-0;AAAA\x1b\\", + b"\x1b_Ga=T,f=24,s=1,v=1,i=0000000009,o=z,t=d;AAAA\x1b\\", + b"\x1b_Ga=t,f=24,s=10000,v=10000;AAAA\x1b\\", + ] { + let shown = String::from_utf8_lossy(escape); + assert_eq!(fed(escape).graphics().kitty, 1, "{shown}"); + } + } + + /// kitty refuses a load declaring more than 10000 pixels a side before + /// it loads anything ("Image too large", `handle_add_command`), so the + /// transmission is no image and the query is answered with the error + /// (#841). On the next chunk of a load in progress the check is not + /// made. + #[test] + fn a_kitty_load_over_10000_pixels_a_side_is_refused() { + for keys in ["s=10001,v=1", "s=1,v=10001", "s=4294967295,v=4294967295"] { + let escape = format!("\x1b_Ga=T,f=24,{keys},c=3,r=2;AAAA\x1b\\"); + let (seen, queries, tracker) = kitty_events(escape.as_bytes()); + assert!(seen.is_empty() && queries.is_empty(), "{keys}: {seen:?}"); + assert_eq!(tracker.graphics().bytes, wire_cost(&[escape.as_bytes()])); + let query = format!("\x1b_Ga=q,i=31,f=24,{keys};AAAA\x1b\\"); + assert_eq!( + loads(&queries_of(query.as_bytes())), + [(Some(31), KittyLoad::TooLarge)], + "{keys}" + ); + // A query from a file starts a load of its own, mid-upload too, + // and drops the upload. + let file = format!("\x1b_Ga=q,i=31,t=f,{keys};L3RtcC94\x1b\\"); + let wire = [UPLOAD_OF_5, file.as_bytes(), b"\x1b_Gm=0;CCCC\x1b\\"].concat(); + let (seen, queries, _) = kitty_events(&wire); + assert_eq!(loads(&queries[..1]), [(Some(31), KittyLoad::TooLarge)]); + assert_ne!( + seen.first().and_then(GraphicsPayload::id), + Some(5), + "{seen:?}" + ); + } + // kitty refuses `i=` with `I=` before it looks at the size, and + // that refusal is named, as on any transmission (#680). + let both = b"\x1b_Ga=T,f=24,s=20000,v=1,i=3,I=4;AAAA\x1b\\"; + let (seen, queries, _) = kitty_events(both); + assert!(seen.is_empty(), "{seen:?}"); + assert!( + matches!(queries.as_slice(), [Query::Unanswerable(_)]), + "{queries:?}" + ); + // Mid-upload, a direct query is the load's next chunk. + let query: &[u8] = b"\x1b_Ga=q,i=31,s=20000;BBBB\x1b\\"; + let (seen, queries, _) = kitty_events(&[UPLOAD_OF_5, query].concat()); + assert_eq!(seen.len(), 1, "{seen:?}"); + assert_eq!(loads(&queries), [(Some(31), KittyLoad::Loaded)]); + } + /// With `m=1`, kitty loads the query's data and then, as after every /// query, trims each image whose data is not loaded yet /// (`remove_images(self, add_trim_predicate, 0)`) — the very image being @@ -5296,6 +5431,38 @@ mod tests { .collect() } + /// A query's reply echoes the id the query ended with, as kitty's + /// `parse_graphics_code` keeps a repeated key's last value (#843); the + /// first was echoed. And the last `a=` decides whether it is a query. + #[test] + fn a_repeated_kitty_key_is_read_with_its_last_value() { + let ids = |bytes: &[u8]| -> Vec> { + queries_of(bytes) + .into_iter() + .map(|query| match query { + Query::KittyGraphics { id, .. } => id, + other => panic!("not a kitty query: {other:?}"), + }) + .collect() + }; + assert_eq!( + ids(b"\x1b_Ga=q,i=31,s=1,v=1,f=24,i=32;AAAA\x1b\\"), + [Some(32)] + ); + assert_eq!(ids(b"\x1b_Ga=T,i=31,a=q;AAAA\x1b\\"), [Some(31)]); + assert!(queries_of(b"\x1b_Ga=q,i=31,s=1,v=1,f=24,a=T,q=2;AAAA\x1b\\").is_empty()); + let seen = payloads(b"\x1b_Ga=q,i=31,s=1,v=1,f=24,a=T,i=9,f=100;AAAA\x1b\\"); + assert_eq!(seen.len(), 1, "{seen:?}"); + assert_eq!( + (seen[0].action(), seen[0].id(), seen[0].format()), + ( + GraphicsAction::TransmitAndPlace, + Some(9), + GraphicsFormat::Png + ) + ); + } + /// The device attributes are taken by their first parameter, as xterm /// takes them (`GetParam(0) <= 0`, charproc.c 4098, 4224 and 4281): 0 /// or none, whatever follows. `CSI 0;1 c` and `CSI > 0;1 c` went diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index c17191a..573cd15 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -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 { @@ -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>, + /// 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>, /// 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>>, + history_cells: Option>>, /// Rows of vt100's own scrollback already copied into `history`, so a /// read that scrolled nothing costs one length check. captured: usize, @@ -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()), @@ -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(), @@ -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. @@ -4341,10 +4483,14 @@ 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()); @@ -4352,6 +4498,45 @@ mod tests { } } + /// 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 diff --git a/crates/termlens/src/graphics.rs b/crates/termlens/src/graphics.rs index d1e37c1..43e64ef 100644 --- a/crates/termlens/src/graphics.rs +++ b/crates/termlens/src/graphics.rs @@ -1302,55 +1302,53 @@ impl GraphicsBuilder { /// Take on the facts of a kitty control block. Only the first escape of /// a chunked transmission carries one; the continuations carry `m=` and /// nothing else, so nothing here overwrites what is already known. - pub(crate) fn kitty(&mut self, control: &[u8]) { + pub(crate) fn kitty(&mut self, control: &KittyControl) { if self.protocol.is_none() { self.protocol = Some(GraphicsProtocol::Kitty); - self.action = match key(control, b"a") { + self.action = match control.flag(b'a') { // `a=t`, transmit only, is the protocol's default: a // transmission that names no action shows nothing (#588). - Some(b"t") | None => GraphicsAction::Transmit, - Some(b"p") => GraphicsAction::Place, - Some(b"T") => GraphicsAction::TransmitAndPlace, - Some(b"d") => GraphicsAction::Delete, + Some(b't') | None => GraphicsAction::Transmit, + Some(b'p') => GraphicsAction::Place, + Some(b'T') => GraphicsAction::TransmitAndPlace, + Some(b'd') => GraphicsAction::Delete, Some(_) => GraphicsAction::Other, }; - self.format = match number(control, b"f") { + self.format = match control.number(b'f') { Some(24) => GraphicsFormat::Rgb, // 32 is the protocol's default. Some(32) | None => GraphicsFormat::Rgba, Some(100) => GraphicsFormat::Png, Some(other) => GraphicsFormat::Other(other), }; - self.compressed = key(control, b"o") == Some(b"z"); - self.transmission = key(control, b"t") - .and_then(|value| value.first().copied()) - .map(GraphicsTransmission::from_code); - self.id = number(control, b"i"); - self.size = match (number(control, b"s"), number(control, b"v")) { + self.compressed = control.flag(b'o') == Some(b'z'); + self.transmission = control.flag(b't').map(GraphicsTransmission::from_code); + self.id = control.number(b'i'); + self.size = match (control.number(b's'), control.number(b'v')) { (Some(width), Some(height)) => Some((width, height)), _ => None, }; - self.cells = match (number(control, b"c"), number(control, b"r")) { + self.cells = match (control.number(b'c'), control.number(b'r')) { (Some(cols), Some(rows)) => Some(( cols.min(u32::from(u16::MAX)) as u16, rows.min(u32::from(u16::MAX)) as u16, )), _ => None, }; - let value = |name: &[u8]| number(control, name).unwrap_or(0); + let value = |key: u8| control.number(key).unwrap_or(0); self.placement = Placement { - cols: value(b"c"), - rows: value(b"r"), - src_width: value(b"w"), - src_height: value(b"h"), - src_x: value(b"x"), - src_y: value(b"y"), - cell_x: value(b"X"), - cell_y: value(b"Y"), - moves: value(b"C") != 1 && value(b"U") == 0 && value(b"P") == 0, + cols: value(b'c'), + rows: value(b'r'), + src_width: value(b'w'), + src_height: value(b'h'), + src_x: value(b'x'), + src_y: value(b'y'), + cell_x: value(b'X'), + cell_y: value(b'Y'), + moves: value(b'C') != 1 && value(b'U') == 0 && value(b'P') == 0, height: 0, forgets: None, - number: value(b"I"), + number: value(b'I'), }; if self.action == GraphicsAction::Delete { self.placement.forgets = forgets(control); @@ -1358,6 +1356,12 @@ impl GraphicsBuilder { } } + /// [`kitty`](Self::kitty) on the keys of a control block, unparsed. + #[cfg(test)] + pub(crate) fn kitty_keys(&mut self, keys: &[u8]) { + self.kitty(&KittyControl::parse(keys, true).expect("a control block kitty reads")); + } + /// Take on the facts of a sixel header: the raster attributes are inside /// the data, so only the protocol is settled here. Nothing else is /// reset, so the builder must hold no kitty upload — the tracker @@ -1622,17 +1626,17 @@ impl SixelMeter { /// only if it was the last, and the deletes by position, number or frame /// free what is placed there — facts about placements, which termlens does /// not keep; `docs/LIMITATIONS.md` says so. -fn forgets(control: &[u8]) -> Option<(u32, u32)> { - let value = |name: &[u8]| number(control, name).unwrap_or(0); - if value(b"p") != 0 { +fn forgets(control: &KittyControl) -> Option<(u32, u32)> { + let value = |key: u8| control.number(key).unwrap_or(0); + if value(b'p') != 0 { return None; } - match key(control, b"d") { - Some(b"I") => Some((value(b"i"), value(b"i"))).filter(|&(id, _)| id != 0), + match control.flag(b'd') { + Some(b'I') => Some((value(b'i'), value(b'i'))).filter(|&(id, _)| id != 0), // An image without an id is in no range: kitty's filter asks for a // client id first. - Some(b"R") => { - Some((value(b"x").max(1), value(b"y"))).filter(|&(first, last)| first <= last) + Some(b'R') => { + Some((value(b'x').max(1), value(b'y'))).filter(|&(first, last)| first <= last) } _ => None, } @@ -1712,22 +1716,152 @@ pub(crate) fn kitty_cells( Some((saturate(out_cols), saturate(out_rows))) } -/// The raw value of `name` in a kitty control block (`a=T,i=3,f=32`). -fn key<'a>(control: &'a [u8], name: &[u8]) -> Option<&'a [u8]> { - control.split(|&b| b == b',').find_map(|pair| { - let (found, value) = split_once(pair, b'=')?; - (found == name).then_some(value) +/// A kitty control block (`a=T,i=3,f=32`), read once (#843), and only if +/// kitty would read it (#841). +/// +/// Each key keeps the *last* value the block gave it: kitty's +/// `parse_graphics_code` (`kitty/parse-graphics-command.h`, 0.49.2) stores +/// every value into its field as it reads it (`U(x) case x: g.x = code`), so +/// a later one replaces an earlier one. Every reader used to search the +/// block for itself and stop at the first pair naming its key, and the query +/// test took any `a=q` at all, so a client that appended overrides to a set +/// of defaults got the defaults here and the overrides in kitty. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct KittyControl { + /// The value of each key, by [`slot`]: a flag's byte, an unsigned + /// integer, or a signed one's two's-complement bits. + values: [Option; 52], +} + +impl Default for KittyControl { + fn default() -> Self { + Self { values: [None; 52] } + } +} + +/// Where a key's value lives in [`KittyControl`]: kitty's keys are single +/// ASCII letters, lower case first. +fn slot(key: u8) -> Option { + match key { + b'a'..=b'z' => Some(usize::from(key - b'a')), + b'A'..=b'Z' => Some(26 + usize::from(key - b'A')), + _ => None, + } +} + +/// What kind of value a kitty key takes, from the `enum KEYS` of kitty's +/// `parse_graphics_code` (0.49.2); `None` for a byte that is no key there. +/// `e` (`report_supported`) is one from kitty 0.50 only, so a feature query +/// is refused here as 0.49 refuses it. +#[derive(Clone, Copy)] +enum KittyValue { + /// One byte from the set kitty accepts for that key. + Flag(&'static [u8]), + /// 1 to 10 digits, within `u32`. + Unsigned, + /// The same, after an optional `-`. + Signed, +} + +fn kitty_value(key: u8) -> Option { + Some(match key { + b'a' => KittyValue::Flag(b"Tacdfpqt"), + b'd' => KittyValue::Flag(b"ACFINPQRXYZacfinpqrxyz"), + b't' => KittyValue::Flag(b"dfst"), + b'o' => KittyValue::Flag(b"z"), + b'z' | b'H' | b'V' => KittyValue::Signed, + b'f' | b'm' | b'i' | b'I' | b'p' | b'q' | b'w' | b'h' | b'x' | b'y' | b'v' | b's' + | b'S' | b'O' | b'c' | b'r' | b'X' | b'Y' | b'C' | b'U' | b'P' | b'Q' | b'N' => { + KittyValue::Unsigned + } + _ => return None, }) } -/// The numeric value of `name`, if it carries one. -fn number(control: &[u8], name: &[u8]) -> Option { - std::str::from_utf8(key(control, name)?).ok()?.parse().ok() +/// kitty's `READ_UINT`: up to ten digits, refused when there are none or +/// when they pass `UINT32_MAX`. An eleventh digit is left where it is, for +/// the separator test after it to refuse. +fn kitty_digits(bytes: &[u8]) -> Option<(u32, &[u8])> { + let count = bytes + .iter() + .take(10) + .take_while(|b| b.is_ascii_digit()) + .count(); + if count == 0 { + return None; + } + let value = bytes[..count] + .iter() + .fold(0u64, |value, &b| value * 10 + u64::from(b - b'0')); + Some((u32::try_from(value).ok()?, &bytes[count..])) } -fn split_once(bytes: &[u8], separator: u8) -> Option<(&[u8], &[u8])> { - let at = bytes.iter().position(|&b| b == separator)?; - Some((&bytes[..at], &bytes[at + 1..])) +impl KittyControl { + /// Read the keys of a control block, the bytes after its `G` and + /// before its `;`, as kitty's `parse_graphics_code` (0.49.2) reads + /// them; `payload` says whether a `;` ended them. + /// + /// `None` where kitty refuses the escape: a byte that is no key + /// (`REPORT_ERROR` at line 92 of `parse-graphics-command.h`), no `=` + /// after it, a flag value outside its set (140), a value with no digits + /// (159) or past `u32` (161), and anything but `,` or `;` after a value + /// (190) — a `,` before the `;` included, since kitty then reads the `;` + /// as a key. kitty's `REPORT_ERROR` only logs (`vt-parser.c:171`), and + /// the command never reaches `screen_handle_graphics_command`: nothing + /// is loaded, placed or answered (#841). Every such escape was read a + /// key at a time, and went ahead. + pub(crate) fn parse(keys: &[u8], payload: bool) -> Option { + let mut control = Self::default(); + let mut rest = keys; + // kitty's `if (parser_buf[pos] == ';') state = AFTER_VALUE`: a + // block with no keys is fine, `;` or not. One that ends on a `,` + // is too, unless a `;` follows it. + let mut after_comma = false; + while let [key, after @ ..] = rest { + let [b'=', after @ ..] = after else { + return None; + }; + let (value, after) = match kitty_value(*key)? { + KittyValue::Flag(set) => match after { + [value, after @ ..] if set.contains(value) => (u32::from(*value), after), + _ => return None, + }, + KittyValue::Unsigned => kitty_digits(after)?, + KittyValue::Signed => { + let (negative, after) = match after { + [b'-', after @ ..] => (true, after), + _ => (false, after), + }; + let (code, after) = kitty_digits(after)?; + // `0 - (int32_t)code`, kept as its bits. + (if negative { code.wrapping_neg() } else { code }, after) + } + }; + control.values[slot(*key)?] = Some(value); + match after { + [] => { + after_comma = false; + rest = after; + } + [b',', after @ ..] => { + after_comma = true; + rest = after; + } + _ => return None, + } + } + (!(after_comma && payload)).then_some(control) + } + + /// The byte a flag key (`a`, `d`, `t`, `o`) was set to. + pub(crate) fn flag(&self, key: u8) -> Option { + self.values[slot(key)?].and_then(|value| u8::try_from(value).ok()) + } + + /// The value of an unsigned key, if the block gave it one. + pub(crate) fn number(&self, key: u8) -> Option { + self.values[slot(key)?] + } } #[cfg(test)] @@ -1736,7 +1870,7 @@ mod tests { fn kitty_payload(control: &[u8], data: &[u8]) -> GraphicsPayload { let mut builder = GraphicsBuilder::default(); - builder.kitty(control); + builder.kitty_keys(control); builder.chunk(data.len() as u64, data, true, usize::MAX); builder.finish().expect("a payload") } @@ -1771,7 +1905,7 @@ mod tests { #[test] fn a_kitty_placement_records_its_size_source_and_whether_it_moves() { let mut builder = GraphicsBuilder::default(); - builder.kitty(b"a=T,f=24,s=8,v=4,c=3,w=6,h=2,x=1,y=1,X=4,Y=5,I=9"); + builder.kitty_keys(b"a=T,f=24,s=8,v=4,c=3,w=6,h=2,x=1,y=1,X=4,Y=5,I=9"); builder.chunk(4, b"AAAA", true, usize::MAX); let (_, placement) = builder.finish_placed().expect("a payload"); assert_eq!( @@ -1793,7 +1927,7 @@ mod tests { ); for control in [&b"a=T,C=1"[..], b"a=T,U=1", b"a=p,i=1,P=2"] { let mut builder = GraphicsBuilder::default(); - builder.kitty(control); + builder.kitty_keys(control); builder.chunk(0, b"", true, usize::MAX); let (_, placement) = builder.finish_placed().expect("a payload"); assert!(!placement.moves, "{}", String::from_utf8_lossy(control)); @@ -1807,7 +1941,7 @@ mod tests { fn p_and_u_decide_the_cursor_move_by_value() { let moves = |control: &[u8]| { let mut builder = GraphicsBuilder::default(); - builder.kitty(control); + builder.kitty_keys(control); builder.chunk(0, b"", true, usize::MAX); builder.finish_placed().expect("a payload").1.moves }; @@ -1824,7 +1958,7 @@ mod tests { fn a_kitty_delete_says_which_images_it_frees() { let forgotten = |control: &[u8]| { let mut builder = GraphicsBuilder::default(); - builder.kitty(control); + builder.kitty_keys(control); builder.chunk(0, b"", true, usize::MAX); builder.finish_placed().expect("a payload").1.forgets }; @@ -2070,9 +2204,62 @@ mod tests { assert!(!payload.action().carries_image()); } + /// kitty 0.49's flag sets, its signed keys and the value bounds, read + /// as its `parse_graphics_code` reads them (#841); and a key given + /// twice keeps its last value (#843). + #[test] + fn a_kitty_control_block_is_read_as_kittys_parser_reads_it() { + let parse = |keys: &[u8]| KittyControl::parse(keys, true); + for (key, set) in [ + (b'a', &b"Tacdfpqt"[..]), + (b'd', b"ACFINPQRXYZacfinpqrxyz"), + (b't', b"dfst"), + (b'o', b"z"), + ] { + for value in 0x21..0x7f_u8 { + let keys = [key, b'=', value]; + let read = parse(&keys).and_then(|control| control.flag(key)); + let expected = set.contains(&value).then_some(value); + assert_eq!(read, expected, "{}", String::from_utf8_lossy(&keys)); + } + } + let control = parse(b"z=-1,H=-2147483648,V=7,i=1,i=4294967295").unwrap(); + assert_eq!(control.number(b'z'), Some(u32::MAX), "-1 kept as its bits"); + assert_eq!(control.number(b'H'), Some(1 << 31)); + assert_eq!(control.number(b'V'), Some(7)); + assert_eq!(control.number(b'i'), Some(u32::MAX), "the last of two"); + // Every key of 0.49, and none besides. + let keys = b"adtofmiIpqwhxyvsSOcrXYzCUPQNHV"; + for key in (b'A'..=b'Z').chain(b'a'..=b'z') { + let value: &[u8] = match key { + b'a' => b"T", + b'd' => b"a", + b't' => b"d", + b'o' => b"z", + _ => b"1", + }; + let block = [&[key, b'='][..], value].concat(); + assert_eq!( + parse(&block).is_some(), + keys.contains(&key), + "{}", + key as char + ); + } + // The end of the block: a `,` is accepted only when no `;` follows. + assert!(KittyControl::parse(b"a=d,", false).is_some()); + assert!(KittyControl::parse(b"a=d,", true).is_none()); + assert!(KittyControl::parse(b"", true).is_some()); + assert!(KittyControl::parse(b"a=", false).is_none()); + assert!(KittyControl::parse(b"i", false).is_none()); + } + + /// An action termlens does not classify, here `a=a` (animate), is not + /// guessed to carry an image. One kitty does not know at all, such as + /// `a=z`, is no command (#841). #[test] fn an_unknown_action_is_not_guessed_to_carry_one() { - let payload = kitty_payload(b"a=z,i=1", b""); + let payload = kitty_payload(b"a=a,i=1", b""); assert_eq!(payload.action(), GraphicsAction::Other); assert!(!payload.action().carries_image()); } @@ -2080,7 +2267,7 @@ mod tests { #[test] fn chunks_join_into_one_payload() { let mut builder = GraphicsBuilder::default(); - builder.kitty(b"a=T,f=32,s=2,v=1,m=1"); + builder.kitty_keys(b"a=T,f=32,s=2,v=1,m=1"); builder.chunk(20, b"AAAA", true, usize::MAX); builder.chunk(10, b"BBBB", true, usize::MAX); let payload = builder.finish().expect("a payload"); @@ -2092,7 +2279,7 @@ mod tests { #[test] fn a_payload_past_the_bound_is_counted_and_not_kept() { let mut builder = GraphicsBuilder::default(); - builder.kitty(b"a=T,f=32,s=2,v=1"); + builder.kitty_keys(b"a=T,f=32,s=2,v=1"); builder.chunk(64, b"AAAABBBB", false, usize::MAX); let payload = builder.finish().expect("a payload"); assert_eq!(payload.bytes(), 64, "the cost is still known"); @@ -2298,10 +2485,10 @@ mod tests { // rest, each chunk its own base64, fed as the tracker feeds // the two escapes. let mut builder = GraphicsBuilder::default(); - builder.kitty(format!("{control},m=1").as_bytes()); + builder.kitty_keys(format!("{control},m=1").as_bytes()); let first = base64(&raw[..channels]); builder.chunk(first.len() as u64, first.as_bytes(), true, usize::MAX); - builder.kitty(b"m=0"); + builder.kitty_keys(b"m=0"); let rest = base64(&raw[channels..]); builder.chunk(rest.len() as u64, rest.as_bytes(), true, usize::MAX); let chunked = builder.finish().expect("a payload"); @@ -2425,10 +2612,10 @@ mod tests { assert_eq!(size <= limit, decodes, "{padding}: {size} bytes"); let whole = kitty_payload(control.as_bytes(), base64(&zlib).as_bytes()); let mut builder = GraphicsBuilder::default(); - builder.kitty(format!("{control},m=1").as_bytes()); + builder.kitty_keys(format!("{control},m=1").as_bytes()); let first = base64(&zlib[..size / 2]); builder.chunk(first.len() as u64, first.as_bytes(), true, usize::MAX); - builder.kitty(b"m=0"); + builder.kitty_keys(b"m=0"); let rest = base64(&zlib[size / 2..]); builder.chunk(rest.len() as u64, rest.as_bytes(), true, usize::MAX); let chunked = builder.finish().expect("a payload"); @@ -2492,7 +2679,7 @@ mod tests { assert!(matches!(sizeless.decode(), Err(DecodeError::Malformed(_)))); let mut builder = GraphicsBuilder::default(); - builder.kitty(b"a=T,f=32,s=2,v=1"); + builder.kitty_keys(b"a=T,f=32,s=2,v=1"); builder.chunk(64, b"AAAABBBB", false, usize::MAX); let dropped = builder.finish().expect("a payload"); assert_eq!(dropped.decode(), Err(DecodeError::NotCaptured)); diff --git a/crates/termlens/src/screen.rs b/crates/termlens/src/screen.rs index 9d99ca8..ef63cc2 100644 --- a/crates/termlens/src/screen.rs +++ b/crates/termlens/src/screen.rs @@ -11,8 +11,10 @@ use std::sync::Arc; use unicode_normalization::UnicodeNormalization; use crate::graphics::GraphicsSeen; +pub(crate) use history::{HistoryRows, RowLog}; mod diff; +mod history; mod parse; mod render; #[cfg(feature = "serde")] @@ -587,13 +589,14 @@ pub(crate) struct TermState { /// /// Text rather than cells, deliberately: a thousand rows of styled /// cells per snapshot would dominate the cost of every wait, and - /// history is asserted on for its content. The rows are shared, so a - /// snapshot pays one `Arc` clone each. + /// history is asserted on for its content. Shared with the emulator and + /// every other snapshot taken since the history last changed, and in + /// chunks with the ones before that (#856). #[cfg_attr( feature = "serde", serde(deserialize_with = "serde_impl::history_text") )] - pub(crate) scrollback: Arc<[Arc]>, + pub(crate) scrollback: HistoryRows>, /// The scrolled-off rows as cells, when the terminal retains styled /// history; `None` when it does not. In lockstep with `scrollback`. // `default` keeps what the derive did for a missing `Option` field, @@ -602,7 +605,7 @@ pub(crate) struct TermState { feature = "serde", serde(default, deserialize_with = "serde_impl::history_cells") )] - pub(crate) scrollback_cells: Option]>>, + pub(crate) scrollback_cells: Option>>, /// Per row, whether it ended in a soft wrap rather than a line end — /// the backend's own record, never asked for before #265. pub(crate) wrapped: Arc<[bool]>, @@ -633,7 +636,7 @@ impl Default for TermState { links: Arc::new(Vec::new()), graphics: GraphicsSeen::default(), repaints: 0, - scrollback: Arc::from([] as [Arc; 0]), + scrollback: HistoryRows::default(), scrollback_cells: None, wrapped: Arc::from([] as [bool; 0]), insert_mode: false, @@ -1393,6 +1396,13 @@ impl Screen { out } + /// Where history row `row` is stored, so a test can tell a history two + /// snapshots share from two equal copies (#856). + #[cfg(test)] + pub(crate) fn history_slot(&self, row: usize) -> *const Arc { + &self.state.scrollback[row] + } + /// How many rows have scrolled off the top and are still retained. /// /// Zero when nothing has scrolled — or when the terminal was built with @@ -3467,7 +3477,7 @@ mod tests { }]), graphics: GraphicsSeen::for_test(1, 1, 2, 160), repaints: 9, - scrollback: Arc::from([Arc::from("scrolled away")]), + scrollback: vec![Arc::from("scrolled away")].into(), ..TermState::default() }; let cells = vec![Cell::new("x".into(), Style::default(), false, false)]; diff --git a/crates/termlens/src/screen/history.rs b/crates/termlens/src/screen/history.rs new file mode 100644 index 0000000..e9d6276 --- /dev/null +++ b/crates/termlens/src/screen/history.rs @@ -0,0 +1,332 @@ +//! History rows, shared between snapshots a chunk at a time (#856). +//! +//! A snapshot used to collect the retained history into a slice of its own, +//! one refcount per row, so every wait evaluation and every recorded frame +//! cost O(history) in time, and each recorded frame held its own copy of +//! the history index, 16 bytes a row. The emulator now keeps its history as +//! [`RowLog`]: sealed chunks of [`CHUNK`] rows that never change again, and +//! an open tail. A snapshot takes [`RowLog::shared`], which is built once +//! after the history changes and then handed out as one refcount, so +//! snapshots between two changes share all of it, and snapshots either side +//! of a change share every sealed chunk. + +use std::cell::OnceCell; +use std::collections::VecDeque; +use std::fmt; +use std::sync::Arc; + +/// Rows a sealed chunk holds. Building a [`HistoryRows`] after a change +/// clones one pointer per chunk and the tail's rows, at most `CHUNK - 1`. +pub(crate) const CHUNK: usize = 256; + +/// The retained history as a [`Screen`](crate::Screen) holds it: the rows, +/// oldest first, read through the chunks they live in. One pointer wide, so +/// it costs a `Screen` less than the slice it replaces. +pub(crate) struct HistoryRows(Arc>); + +struct Chunks { + /// Every chunk but the last holds exactly [`CHUNK`] rows. + chunks: Box<[Arc<[T]>]>, + /// Rows dropped off the front of the first chunk, fewer than [`CHUNK`]. + skip: usize, + len: usize, +} + +impl HistoryRows { + pub(crate) fn len(&self) -> usize { + self.0.len + } + + pub(crate) fn get(&self, row: usize) -> Option<&T> { + if row >= self.0.len { + return None; + } + let at = row + self.0.skip; + self.0.chunks.get(at / CHUNK)?.get(at % CHUNK) + } + + pub(crate) fn iter(&self) -> impl Iterator + '_ { + self.0 + .chunks + .iter() + .flat_map(|chunk| chunk.iter()) + .skip(self.0.skip) + .take(self.0.len) + } + + /// Whether `self` and `other` are the one history, not merely equal. + #[cfg(test)] + pub(crate) fn ptr_eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + + /// Whether the two hold their first sealed chunk in one allocation. + #[cfg(test)] + pub(crate) fn shares_first_chunk(&self, other: &Self) -> bool { + match (self.0.chunks.first(), other.0.chunks.first()) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + _ => false, + } + } +} + +impl Clone for HistoryRows { + fn clone(&self) -> Self { + Self(Arc::clone(&self.0)) + } +} + +impl Default for HistoryRows { + fn default() -> Self { + Self(Arc::new(Chunks { + chunks: Box::new([]), + skip: 0, + len: 0, + })) + } +} + +impl FromIterator for HistoryRows { + fn from_iter>(rows: I) -> Self { + let mut log = RowLog::default(); + for row in rows { + log.push_back(row); + } + log.seal() + } +} + +impl From> for HistoryRows { + fn from(rows: Vec) -> Self { + rows.into_iter().collect() + } +} + +/// A row by index, panicking past the end as a slice does. +impl std::ops::Index for HistoryRows { + type Output = T; + + fn index(&self, row: usize) -> &T { + self.get(row) + .unwrap_or_else(|| panic!("history row {row} past the end of {}", self.len())) + } +} + +impl PartialEq for HistoryRows { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() && self.iter().eq(other.iter()) + } +} + +impl Eq for HistoryRows {} + +/// A list, as the slice it replaces printed. +impl fmt::Debug for HistoryRows { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +/// A sequence of rows, as the slice it replaces serialized. +#[cfg(feature = "serde")] +impl serde::Serialize for HistoryRows { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(self.iter()) + } +} + +/// The emulator's history: sealed chunks, an open tail, and the +/// [`HistoryRows`] last built from them, kept until they change. +pub(crate) struct RowLog { + sealed: VecDeque>, + tail: Vec, + /// Rows dropped off the front of `sealed[0]`; 0 while `sealed` is + /// empty. + skip: usize, + /// What [`shared`](Self::shared) hands out until the next change. A + /// `OnceCell` because a snapshot reads the emulator through `&self`; + /// the emulator is `Send` and never shared, so nothing here needs a + /// lock. + shared: OnceCell>, +} + +impl Default for RowLog { + fn default() -> Self { + Self { + sealed: VecDeque::new(), + tail: Vec::new(), + skip: 0, + shared: OnceCell::new(), + } + } +} + +impl RowLog { + pub(crate) fn len(&self) -> usize { + self.sealed.len() * CHUNK - self.skip + self.tail.len() + } + + /// Append the newest row. + pub(crate) fn push_back(&mut self, row: T) { + self.shared.take(); + self.tail.push(row); + if self.tail.len() == CHUNK { + self.sealed.push_back(std::mem::take(&mut self.tail).into()); + } + } + + /// Drop the oldest row, as a history at its bound does. + pub(crate) fn pop_front(&mut self) { + self.shared.take(); + if self.sealed.is_empty() { + if !self.tail.is_empty() { + self.tail.remove(0); + } + return; + } + self.skip += 1; + if self.skip == CHUNK { + self.sealed.pop_front(); + self.skip = 0; + } + } + + /// The everything-built [`HistoryRows`], with the tail sealed too. For + /// [`FromIterator`], which never appends again. + fn seal(mut self) -> HistoryRows { + let tail = std::mem::take(&mut self.tail); + let len = self.len() + tail.len(); + let mut chunks: Vec> = self.sealed.into(); + chunks.push(tail.into()); + HistoryRows(Arc::new(Chunks { + chunks: chunks.into(), + skip: self.skip, + len, + })) + } +} + +impl RowLog { + /// Drop the newest row, as rows a taller screen pulls back out of + /// history do. A sealed chunk is opened again to do it, which a resize + /// does at most once for each chunk it reaches. + pub(crate) fn pop_back(&mut self) { + self.shared.take(); + if self.tail.is_empty() { + let Some(last) = self.sealed.pop_back() else { + return; + }; + let from = if self.sealed.is_empty() { + std::mem::take(&mut self.skip) + } else { + 0 + }; + self.tail = last[from..].to_vec(); + } + self.tail.pop(); + } + + /// The history as a snapshot holds it: built after a change, one + /// pointer per sealed chunk and a copy of the tail, and the same + /// [`HistoryRows`] after that until the next change. + pub(crate) fn shared(&self) -> HistoryRows { + self.shared + .get_or_init(|| { + let chunks: Box<[Arc<[T]>]> = self + .sealed + .iter() + .cloned() + .chain(std::iter::once(Arc::from(self.tail.as_slice()))) + .collect(); + HistoryRows(Arc::new(Chunks { + chunks, + skip: self.skip, + len: self.len(), + })) + }) + .clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The log against a `VecDeque` doing the same thing, through every + /// chunk boundary: pushes, evictions from the front at a bound, and + /// rows pulled back off the end, read through `shared` after each step. + #[test] + fn a_row_log_reads_as_the_rows_it_was_given() { + let mut log = RowLog::default(); + let mut model = VecDeque::new(); + let mut state: u64 = 0x9e37_79b9_7f4a_7c15; + let mut next = |bound: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % bound + }; + let mut row = 0u32; + for _ in 0..20_000 { + match next(10) { + 0 => { + log.pop_back(); + model.pop_back(); + } + 1 | 2 => { + log.pop_front(); + model.pop_front(); + } + _ => { + row += 1; + log.push_back(row); + model.push_back(row); + // A bound, as the emulator keeps one. + while model.len() > 700 { + log.pop_front(); + model.pop_front(); + } + } + } + let shared = log.shared(); + assert_eq!(log.len(), model.len()); + assert_eq!(shared.len(), model.len()); + assert!(shared.iter().eq(model.iter())); + let probe = usize::try_from(next(model.len() as u64 + 2)).unwrap(); + assert_eq!(shared.get(probe), model.get(probe)); + } + } + + /// Two snapshots with no change between them are one history; either + /// side of a change they share every sealed chunk (#856). + #[test] + fn snapshots_share_the_history_they_have_in_common() { + let mut log: RowLog> = RowLog::default(); + for row in 0..1000 { + log.push_back(Arc::from(format!("row {row}"))); + } + let (a, b) = (log.shared(), log.shared()); + assert!(a.ptr_eq(&b)); + log.push_back(Arc::from("one more")); + let c = log.shared(); + assert!(!a.ptr_eq(&c)); + assert!(a.shares_first_chunk(&c)); + assert_eq!(c.len(), 1001); + assert_eq!(c.get(1000).map(|row| &**row), Some("one more")); + } + + #[test] + fn collected_rows_read_back_in_order() { + let rows: HistoryRows = (0..CHUNK * 2 + 3).collect(); + assert_eq!(rows.len(), CHUNK * 2 + 3); + assert!(rows.iter().copied().eq(0..CHUNK * 2 + 3)); + assert_eq!(rows.get(CHUNK * 2 + 2), Some(&(CHUNK * 2 + 2))); + assert_eq!(rows.get(CHUNK * 2 + 3), None); + let empty: HistoryRows = std::iter::empty().collect(); + assert_eq!(empty, HistoryRows::default()); + assert_eq!( + format!("{rows:?}").len(), + format!("{:?}", rows.iter().collect::>()).len() + ); + } +} diff --git a/crates/termlens/src/screen/serde_impl.rs b/crates/termlens/src/screen/serde_impl.rs index 8853339..e1ca6bf 100644 --- a/crates/termlens/src/screen/serde_impl.rs +++ b/crates/termlens/src/screen/serde_impl.rs @@ -34,7 +34,7 @@ use serde::de::{ }; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use super::{parse, Cell, Link, MouseModes, Screen, TermState}; +use super::{parse, Cell, HistoryRows, Link, MouseModes, Screen, TermState}; use crate::terminal::MAX_DIMENSION; /// The cursor as three named fields rather than a tuple, so the JSON reads. @@ -552,13 +552,13 @@ const LINKS: usize = 64; /// error. pub(super) fn history_text<'de, D: Deserializer<'de>>( deserializer: D, -) -> Result]>, D::Error> { +) -> Result>, D::Error> { let _spare = Spare::hold(); deserializer.deserialize_seq(HistoryText) } /// Styled history as a `Screen` holds it: shared rows of cells. -type StyledRows = Arc<[Arc<[Cell]>]>; +type StyledRows = HistoryRows>; /// `state.scrollback_cells`, held as [`history_text`] holds the text: each /// row at most [`MAX_DIMENSION`] cells of at most [`CELL_BYTES`], the empty @@ -653,6 +653,14 @@ impl Gather { ask_for_arc(std::mem::size_of_val(self.0.as_slice()))?; Ok(Arc::from(self.0)) } + + /// The gathered rows as the history a [`Screen`] holds, in chunks + /// that together take the room one shared slice would, asked for + /// first as [`into_shared`](Self::into_shared) asks (#856). + fn into_history(self) -> Result, TryReserveError> { + ask_for_arc(std::mem::size_of_val(self.0.as_slice()))?; + Ok(self.0.into_iter().collect()) + } } /// Ask the allocator for the room an `Arc` of `bytes` takes, the two counts @@ -745,7 +753,7 @@ impl Visitor<'_> for Contents { struct HistoryText; impl<'de> Visitor<'de> for HistoryText { - type Value = Arc<[Arc]>; + type Value = HistoryRows>; fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("a sequence of rows") @@ -766,7 +774,7 @@ impl<'de> Visitor<'de> for HistoryText { })?; } let count = rows.0.len(); - rows.into_shared() + rows.into_history() .map_err(|_| refused(format_args!("{} of history", Count(count, "row")))) } } @@ -864,7 +872,7 @@ impl<'de> Visitor<'de> for HistoryCells { })?; } let count = rows.0.len(); - rows.into_shared() + rows.into_history() .map_err(|_| refused(format_args!("{} of styled history", Count(count, "row")))) } } diff --git a/crates/termlens/src/terminal.rs b/crates/termlens/src/terminal.rs index ee48743..34c0b6c 100644 --- a/crates/termlens/src/terminal.rs +++ b/crates/termlens/src/terminal.rs @@ -30,7 +30,9 @@ use crate::keys::{mouse_legacy, mouse_sgr, mouse_urxvt, mouse_utf8}; use crate::screen::{MouseMode, Screen}; use crate::spawn::{spawn_child, PtyChild}; use crate::utf8::Utf8Sanitizer; -use crate::wait::{deadline_after, next_backoff, Expired, Monitor, INITIAL_BACKOFF, POLL_CAP}; +use crate::wait::{ + deadline_after, next_backoff, Check, Expired, Monitor, INITIAL_BACKOFF, POLL_CAP, +}; /// How long `wait_exit` keeps draining PTY output after the child has been /// reaped, so the final screen is complete. Best effort: a grandchild @@ -534,7 +536,8 @@ pub enum Graphics { /// Kitty graphics: the `a=q` capability probe is answered as kitty /// answers it — `OK` echoing its `i=`, kitty's error where kitty refuses /// it, and not at all when it names no image id, asks for quiet with - /// `q=`, or joins an upload still waiting for chunks. + /// `q=`, joins an upload still waiting for chunks, or is an escape + /// kitty 0.49's parser refuses, such as a feature query (`e=`). Kitty, } @@ -1698,6 +1701,17 @@ impl EmuState { ) .into_bytes() } + // kitty's `handle_add_command` refuses an image over + // 10000 pixels a side before it loads anything (#841). + (Some(id), KittyLoad::TooLarge) => { + if *quiet >= 2 { + return None; + } + format!( + "\x1b_Gi={id};EINVAL:Image too large, width or height greater than 10000\x1b\\" + ) + .into_bytes() + } // No data loaded yet and no error: kitty says nothing // (`finish_command_response` returns no reply), and a // load the query joined never answers it later. Named @@ -2019,17 +2033,25 @@ impl TerminalBuilder { /// A snapshot holds one entry per cell and is taken afresh on every /// state change, so the cost is O(cells) — the same for `1000x100` as /// for `100x1000`. Repeat reads of an unchanged screen are served from - /// a cache and are free. Measured, first snapshot after a change: - /// - /// | size | cells | release | debug | - /// |---|---|---|---| - /// | 80x24 | 1.9k | 47µs | 0.8ms | - /// | 200x60 | 12k | 0.3ms | 4.7ms | - /// | 500x500 | 250k | 3.7ms | 72ms | - /// | 1000x1000 | 1M | 10ms | 297ms | + /// a cache and are free. Measured: `screen()` after a change, and the + /// first [`wait_until`](Terminal::wait_until) through one paint of + /// every cell (about cols × rows bytes) to a mark drawn last: + /// + /// | size | cells | snapshot, release | debug | paint waited through, release | debug | + /// |---|---|---|---|---|---| + /// | 80x24 | 1.9k | 0.15ms | 1.2ms | 6ms | 9ms | + /// | 200x60 | 12k | 1.0ms | 7.0ms | 17ms | 27ms | + /// | 500x500 | 250k | 18ms | 145ms | 0.3s | 0.8s | + /// | 1000x1000 | 1M | 90ms | 620ms | 1.7s | 3.3s | + /// + /// On an Intel Core i5-13500 under Linux, with other builds running. + /// A wait evaluates its predicate under the lock the reader needs, so + /// its evaluations are spaced by their own cost, and the reader keeps + /// at least half the lock's time (#854): the 1000x1000 paint took 8 to + /// 14 s to wait through before, past the default 5 s timeout. /// /// The debug column is the one most suites see, since `cargo test` - /// builds unoptimized by default. Ordinary terminal sizes are free in + /// builds unoptimized by default. Ordinary terminal sizes are cheap in /// either; a deliberately huge grid is a known trade-off rather than a /// surprise, and past 1000 per axis it stops being a trade-off — hence /// the limit. @@ -2201,9 +2223,14 @@ impl TerminalBuilder { /// scrolled rows as cells — one `Cell` per column instead of one string /// per row. Measured on 20,000 lines through an 80x24 screen with the /// default 1,000-row history, release build: about 70 ms text-only, - /// about 90 ms styled, on a workload well past what a test drives. A - /// snapshot pays one refcount per retained row either way, so the cost - /// of a wait does not grow with the depth of history. + /// about 90 ms styled, on a workload well past what a test drives. + /// + /// A snapshot shares the retained history, styled or not, rather than + /// copying it (#856): one refcount while no row has scrolled since the + /// last snapshot, and once one has, one pointer per 256 rows and a copy + /// of at most 255. So the cost of a wait barely grows with the depth of + /// history. It used to pay one refcount per retained row, about 10 µs + /// for every 1,000 rows. /// /// The attributes only the shadow parser sees — blink, conceal and /// strikethrough — are retained too: the shadow keeps the same history @@ -2250,6 +2277,13 @@ impl TerminalBuilder { /// completed, as well as its cells. Their data is bounded by /// [`capture_graphics`](Self::capture_graphics), not by this: the /// oldest frames are dropped for whichever bound is passed first. + /// + /// A frame holds the [`scrollback`](Self::scrollback) history too, + /// shared and not counted here (#856). Frames with no row scrolled + /// between them hold one copy of it; a frame after a scroll adds one + /// pointer per 256 rows of history and at most 255 rows of its own, + /// about 6 KiB at 32,000 rows. Each frame used to hold an index of the + /// whole history, 16 bytes a row. #[must_use] pub fn record_budget(mut self, cells: usize) -> Self { self.record_budget = cells; @@ -2661,11 +2695,13 @@ fn strip_paste_markers(text: &str) -> String { /// /// Ten times a normal terminal on each side, so no real test is anywhere /// near it, and low enough that the worst case stays bounded: a snapshot -/// costs O(cells), so 1000x1000 is a million cells — about 10ms per -/// snapshot in release and 300ms in debug, which `cargo test` builds by -/// default. Past this the numbers stop being slow and start being a wedge: -/// 5000x5000 was accepted and turned the first wait into a 16-second -/// timeout that blamed the predicate. +/// costs O(cells), so 1000x1000 is a million cells — about 90 ms per +/// snapshot in release and 620 ms in debug, which `cargo test` builds by +/// default, and one paint of every cell takes 1.7 s and 3.3 s to wait +/// through (`TerminalBuilder::size` has the table; #854). Past this the +/// numbers stop being slow and start being a wedge: 5000x5000 was accepted +/// and turned the first wait into a 16-second timeout that blamed the +/// predicate. pub(crate) const MAX_DIMENSION: u16 = 1000; /// The smallest grid the emulator can serve. Not 1: see `check_size`. const MIN_DIMENSION: u16 = 2; @@ -4430,11 +4466,13 @@ impl Terminal { }; let deadline = deadline_after(timeout); let mut seen_generation = None; + // When the last evaluation ended, and what it cost (#854). + let mut last: Option<(Instant, Duration)> = None; // Once the application has drawn since the resize, every screen is // asked, as `wait_until` asks them, even one that has since come // back to what the resize left: it was drawn. let mut drawn = resized.is_none(); - let outcome = self.shared.wait_until(deadline, |state| { + let outcome = self.shared.wait_paced(deadline, |state| { // Ahead of the generation check: a child that exited changes // nothing on the grid, and on Windows is the only EOF there is. self.exit_watch @@ -4442,14 +4480,34 @@ impl Terminal { // Spurious wake (poll-cap tick, unrelated notify): the state is // unchanged, so the predicate's verdict is too. if seen_generation == Some(state.generation) { - return None; + return Check::Wait; + } + // An evaluation holds the lock for as long as its snapshot and + // the predicate take, and the reader needs the lock for every + // read, so a wait that evaluated after each read let the reader + // in for one read per evaluation. At 1000x1000, about 89 ms a + // snapshot and at most 8 KiB a read, waiting through one + // full-screen paint took 8 to 13 s (#854). So the next + // evaluation waits for as long again as the last one took, + // which keeps evaluating to at most half the lock's time, and + // then looks at the screen as it is by then, whether or not + // anything else arrives. On a screen whose snapshot takes + // microseconds that is microseconds. Never past the point + // where the deadline would pass unasked: the last screen + // before it is evaluated. + if let Some((ended, cost)) = last { + let now = Instant::now(); + if now.duration_since(ended) < cost && now + cost < deadline { + return Check::WaitUntil(ended + cost); + } } seen_generation = Some(state.generation); + let began = Instant::now(); // Before the predicate: a frozen screen can still satisfy one, // and a match on a grid that stopped advancing is not an answer. if let Some(failure) = state.emulator_failure() { - return Some(Err(failure)); + return Check::Done(Err(failure)); } // A read counts once it has been processed, and the resize took // its counts under the lock that processes them, so no read falls @@ -4463,18 +4521,19 @@ impl Terminal { if drawn { let screen = state.snapshot(); if predicate(&screen) { - return Some(Ok(screen)); + return Check::Done(Ok(screen)); } } if state.eof { let screen = state.snapshot(); - return Some(Err(Error::Eof { + return Check::Done(Err(Error::Eof { waiting_for: format!("{what}{}{}", state.query_note(), history_note(&screen)), screen, } .recorded())); } - None + last = Some((Instant::now(), began.elapsed())); + Check::Wait }); match outcome { Ok(inner) => inner, diff --git a/crates/termlens/src/wait.rs b/crates/termlens/src/wait.rs index faea5db..f4425d8 100644 --- a/crates/termlens/src/wait.rs +++ b/crates/termlens/src/wait.rs @@ -43,6 +43,16 @@ pub(crate) fn deadline_after(timeout: Duration) -> Instant { } } +/// What a [`Monitor::wait_paced`] check found. +pub(crate) enum Check { + /// The wait is over. + Done(T), + /// Nothing yet: look again on the next change or poll tick. + Wait, + /// Nothing yet, and look again by this time even if nothing changes. + WaitUntil(Instant), +} + /// Marker error: the deadline expired inside [`Monitor::wait_until`]. #[derive(Debug)] pub(crate) struct Expired; @@ -101,17 +111,33 @@ impl Monitor { &self, deadline: Instant, mut check: impl FnMut(&mut S) -> Option, + ) -> Result { + self.wait_paced(deadline, |state| match check(state) { + Some(value) => Check::Done(value), + None => Check::Wait, + }) + } + + /// [`wait_until`](Self::wait_until), with a `check` that can also ask + /// to be woken by a time of its own, sooner than the poll tick, after + /// putting off a look it will want to take then (#854). + pub(crate) fn wait_paced( + &self, + deadline: Instant, + mut check: impl FnMut(&mut S) -> Check, ) -> Result { let mut guard = self.lock(); loop { - if let Some(v) = check(&mut guard) { - return Ok(v); - } + let wake = match check(&mut guard) { + Check::Done(value) => return Ok(value), + Check::Wait => deadline, + Check::WaitUntil(by) => by.min(deadline), + }; let now = Instant::now(); if now >= deadline { return Err(Expired); } - let sleep = (deadline - now).min(POLL_CAP); + let sleep = wake.saturating_duration_since(now).min(POLL_CAP); guard = self.wait_timeout(guard, sleep); } } @@ -139,6 +165,29 @@ mod tests { assert_eq!(got, Some(7)); } + /// A check that puts off a look is woken by the time it asked for, + /// sooner than the poll tick and with nothing notified (#854). + #[test] + fn a_paced_wait_wakes_by_the_time_its_check_asked_for() { + let monitor = Monitor::new(()); + let start = Instant::now(); + let by = start + Duration::from_millis(5); + let mut looks = 0; + let woke = monitor + .wait_paced(start + Duration::from_secs(5), |()| { + looks += 1; + if Instant::now() >= by { + Check::Done(Instant::now()) + } else { + Check::WaitUntil(by) + } + }) + .unwrap(); + assert!(woke >= by); + assert!(woke - start < POLL_CAP, "{:?}", woke - start); + assert!(looks >= 2); + } + #[test] fn wait_until_expires_at_the_deadline() { let monitor = Monitor::new(()); diff --git a/crates/termlens/tests/graphics.rs b/crates/termlens/tests/graphics.rs index f6a24f6..f6b117e 100644 --- a/crates/termlens/tests/graphics.rs +++ b/crates/termlens/tests/graphics.rs @@ -394,3 +394,140 @@ fn p_and_u_decide_the_cursor_move_by_value() -> termlens::Result<()> { } Ok(()) } + +/// `emit` with `steps`, on a terminal declared to speak kitty graphics with +/// a 10x20 cell, as the kitty issues' repros use. +fn kitty_emit(steps: &[&str]) -> termlens::Result { + util::spawn_emit( + Terminal::builder() + .size(20, 5) + .timeout(Duration::from_secs(30)) + .graphics(termlens::Graphics::Kitty) + .cell_size(10, 20), + steps, + ) +} + +/// A control block that repeats a key is read with the key's last value, +/// as kitty reads it (#843): `X` lands where kitty leaves it. The first +/// value was read, so the first and third were transmitted only and the +/// third taken for a query. +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY does not forward kitty or sixel payloads (#149)" +)] +fn a_repeated_kitty_key_takes_its_last_value() -> termlens::Result<()> { + let mut seen = Vec::new(); + for control in [ + "a=t,f=24,s=1,v=1,c=3,r=2,a=T", + "a=T,f=24,s=1,v=1,c=3,r=2,c=5", + "a=q,i=31,f=24,s=1,v=1,c=3,r=2,a=T", + ] { + let escape = format!(r"\e_G{control};AAAA\e\\X"); + let mut t = kitty_emit(&["--raw", escape.as_str(), "--wait"])?; + t.wait_until(|s| s.contains("X"))?; + seen.push(t.screen().find("X")); + t.send(termlens::Key::Enter)?; + t.wait_exit()?; + } + assert_eq!(seen, [Some((1, 3)), Some((1, 5)), Some((1, 3))]); + Ok(()) +} + +/// A query that repeats its id is answered with the last one, as kitty +/// answers it (#843). The first was echoed. +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY does not forward kitty or sixel payloads (#149)" +)] +fn a_repeated_kitty_id_is_echoed_by_its_last_value() -> termlens::Result<()> { + let mut t = kitty_emit(&[ + "--raw-mode", + "--raw", + r"\e_Ga=q,i=31,s=1,v=1,f=24,i=32;AAAA\e\\", + "--read", + "12", + "|", + "--wait", + ])?; + t.wait_until(|s| s.contains("|"))?; + assert_eq!(t.screen().row_text(0).trim_end(), r"E_Gi=32;OKE\|"); + t.send(termlens::Key::Enter)?; + t.wait_exit()?; + Ok(()) +} + +/// A kitty escape kitty's parser refuses is no command (#841): nothing is +/// counted as an image, and `X` stays where it was. kitty 0.49 refuses each +/// of these, the last as "Image too large"; termlens placed all six. +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY does not forward kitty or sixel payloads (#149)" +)] +fn a_command_kitty_rejects_is_not_an_image() -> termlens::Result<()> { + let mut seen = Vec::new(); + 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", + ] { + let escape = format!(r"\e_G{control};AAAA\e\\X"); + let mut t = kitty_emit(&["--raw", escape.as_str(), "--wait"])?; + t.wait_until(|s| s.contains("X"))?; + let screen = t.screen(); + seen.push((screen.graphics().total(), screen.find("X"))); + t.send(termlens::Key::Enter)?; + t.wait_exit()?; + } + assert_eq!(seen, [(0, Some((0, 0))); 6]); + Ok(()) +} + +/// A query kitty's parser refuses gets no reply (#841): a malformed one, +/// and a feature query (`e=`), whose key kitty 0.49 does not have. Both +/// were answered `OK`. A query kitty refuses as too large is answered with +/// kitty's error. +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY does not forward kitty or sixel payloads (#149)" +)] +fn a_query_kitty_rejects_is_not_answered() -> termlens::Result<()> { + let mut replies = Vec::new(); + for control in [ + "a=q,i=31,s=1,v=1,f=24,", + "a=q,i=31,e=T,U=1,C=1", + "a=q,i=31,s=20000,v=1,f=24", + ] { + let escape = format!(r"\e_G{control};AAAA\e\\"); + let mut t = kitty_emit(&[ + "--raw-mode", + "--raw", + escape.as_str(), + "--read-quiet", + "96", + "|", + "--wait", + ])?; + t.wait_until(|s| s.contains("|"))?; + // The error wraps across rows: read it with its spaces taken out. + replies.push(t.screen().text().split_whitespace().collect::()); + t.send(termlens::Key::Enter)?; + t.wait_exit()?; + } + assert_eq!( + replies, + [ + "|", + "|", + r"E_Gi=31;EINVAL:Imagetoolarge,widthorheightgreaterthan10000E\|" + ] + ); + Ok(()) +} diff --git a/crates/termlens/tests/large_grid.rs b/crates/termlens/tests/large_grid.rs new file mode 100644 index 0000000..0d0e199 --- /dev/null +++ b/crates/termlens/tests/large_grid.rs @@ -0,0 +1,41 @@ +//! The largest grid termlens accepts, painted whole, waited through within +//! the default timeout (#854). +//! +//! A file of its own, so that no other test of this binary competes with it +//! for the CPU: the claim is about what one wait costs, and the stress +//! workflow runs every binary's tests in parallel. + +/// One paint of every cell of a 1000x1000 grid, about 1 MB, then `END` over +/// the top-left corner, and the first `wait_until` on `END` under the +/// builder's default 5 s timeout. Each evaluation of the predicate snapshots +/// the grid under the state lock the reader needs for every read, about +/// 90 ms here in release, and the wait evaluated after every read: the +/// reader got one read of at most 8 KiB in per snapshot, and the wait timed +/// out, `END` showing after 8 to 14 s. Evaluations are now spaced by their +/// own cost. +/// +/// A release-build test: a debug snapshot of this grid takes 600 ms, and +/// how long the paint takes to wait through there depends on the machine. +#[test] +#[cfg(unix)] +#[cfg_attr( + debug_assertions, + ignore = "a timing claim about release builds; run with --release" +)] +fn a_full_paint_of_the_largest_grid_is_waited_through_in_time() -> termlens::Result<()> { + let n = 1000; + let script = format!( + r#"stty -echo; awk 'BEGIN {{ for (r = 1; r <= {n}; r++) {{ printf "\033[%d;1H", r; for (c = 0; c < {n}; c++) printf "%c", 97 + (r + c) % 26 }} printf "\033[1;1HEND" }}'; read done"# + ); + let mut t = termlens::Terminal::builder() + .size(n, n) + .args(["-c", script.as_str()]) + .spawn("sh")?; + t.wait_until(|s| s.contains("END"))?; + // Every row painted, the last one too: row 1000 starts at + // `97 + 1000 % 26`, an `m`. + assert!(t.screen().row_text(n - 1).starts_with("mnopqrstuv")); + t.send(termlens::Key::Enter)?; + t.wait_exit()?; + Ok(()) +} diff --git a/docs/DESIGN.md b/docs/DESIGN.md index b43e9c2..7b0d0ea 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -400,7 +400,14 @@ screen dump** — a CI log alone answers "what was the app showing?". - `wait_until(pred)` — re-evaluates `pred` on a fresh snapshot whenever the reader delivers bytes (condvar notification), with a 50ms poll cap as a - missed-wakeup backstop. Fails fast with `Error::Eof` the moment the PTY + missed-wakeup backstop. An evaluation holds the state lock the reader + needs for every read, so the next one waits for as long as the last + took, then looks at the screen as it is by then (#854): evaluating keeps + to at most half the lock's time. On an ordinary screen that is + microseconds; at 1000x1000, about 90 ms a snapshot in release, it is + what lets one full-screen paint be waited through in 1.7 s rather than + 13, when the reader got one 8 KiB read in per snapshot. The wait still + evaluates every screen it stops on, and the last before its deadline. Fails fast with `Error::Eof` the moment the PTY closes while `pred` is false: more waiting can never succeed. When rows have scrolled into history, both errors say how many and point at `full_text` — a content predicate cannot see them and neither can the diff --git a/docs/LIMITATIONS.md b/docs/LIMITATIONS.md index a096d55..8cb2499 100644 --- a/docs/LIMITATIONS.md +++ b/docs/LIMITATIONS.md @@ -220,7 +220,16 @@ CHANGELOG entry. the next transmission that carries its data. And chunks that break the protocol's rule that every chunk but the last is a multiple of four base64 characters are decoded joined, not one escape at a time as kitty decodes them (#637); a stream that keeps - the rule decodes exactly as kitty decodes it. + the rule decodes exactly as kitty decodes it. A control block is read as + kitty 0.49's parser reads it, a repeated key keeping its last value + (#843), and an escape that parser refuses is no command: an unknown key + (`e=`, kitty 0.50's feature query, among them), a flag value outside its + set, a value with no digits or past `u32`, or anything but `,` or `;` + after a value (#841). So is a transmission or a query declaring more than + 10000 pixels a side; the query gets kitty's `EINVAL`, but the + transmission's error, which kitty addresses to the command that started + its previous load, is not named. An animation frame (`a=f`) over that + size is not refused. - **Hyperlinks are captured, not attributed to cells.** `links()` reports every `OSC 8` span with its target, its `id`, and the text it wrapped, so "did it link the right place?" is assertable — but a `Cell` does not carry diff --git a/docs/STABILITY.md b/docs/STABILITY.md index 571d801..1d52704 100644 --- a/docs/STABILITY.md +++ b/docs/STABILITY.md @@ -85,8 +85,9 @@ silently degraded to text the moment the screen filled. **The measurement.** With history retained as cells, 20,000 lines through an 80x24 screen cost about 90 ms against 40 ms text-only (release build, `tests/styled_history.rs`'s ignored probe). The cost lands where a -suite feels it: every read that scrolls captures cells, and a snapshot -pays one refcount per retained row. +suite feels it: every read that scrolls captures cells. A snapshot paid +one refcount per retained row too, until #856 shared the history between +snapshots in chunks of 256 rows. **The decision.** History is text by default and cells on request: `TerminalBuilder::scrollback_styles(true)` retains the styled rows, the