From 7915a9f181b0bfa3bd5d246e5867402776ae45ce Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:42:18 +0700 Subject: [PATCH 1/8] fix(emu): list an empty CSI parameter as written, not as 0 vte hands an omitted parameter on as 0, and the record dropped that 0 only when it was the sole parameter, so `CSI 22 ; t` was listed as `^[[22;0t` and `CSI ; 5 h` as `^[[0;5h`, with a 0 the application never wrote. The tracker now notes which parameters of a CSI had nothing written in them, and the emulator tells the record so between the bytes before the final byte and that byte, fed alone, as it does for the `SP` intermediates (#764). The record leaves those parameters empty. A `0` the application wrote is still listed. Closes #827 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 5 +++ crates/termlens/src/emu/seq.rs | 36 +++++++++++++++++++ crates/termlens/src/emu/unhandled.rs | 45 ++++++++++++++++++++---- crates/termlens/src/emu/vt100.rs | 52 ++++++++++++++++++++++++++++ crates/termlens/tests/unsupported.rs | 19 ++++++++++ 5 files changed, 150 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c779de..7e6d8fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,11 @@ reads that marker. ### Fixed +- `Screen::unsupported()` lists a parameter the application left empty + as empty: `CSI 22 ; t` is `^[[22;t`, `CSI ; 5 h` is `^[[;5h`. Every + empty parameter but a sole one was listed as a `0` the application + never wrote. A `0` it wrote is still listed. A test that expected + `^[[22;0t` for `CSI 22 ; t` should expect `^[[22;t`. (#827) - An empty regex match at the end of a row is reported one past the last cell the text covers, by one rule for every row, as `find` reports a match after a wide character: on six columns `find_all_matches($)` diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index e002499..a6cab7c 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -848,6 +848,11 @@ pub(crate) struct SeqTracker { csi_param: u32, csi_has_digits: bool, csi_first_param: u32, + /// The parameters of the current CSI written with nothing in them + /// (`CSI 22 ; t`), as bits by position, the first 32: vte hands each on + /// as a 0 the application did not write — see + /// [`omitted_params`](Self::omitted_params). + csi_omitted: u32, /// The second parameter, for `DECSTBM`'s bottom margin. csi_second_param: u32, csi_param_count: u8, @@ -1092,6 +1097,7 @@ impl SeqTracker { csi_param: 0, csi_has_digits: false, csi_first_param: 0, + csi_omitted: 0, csi_second_param: 0, csi_param_count: 0, csi_frame_modes: [0; 4], @@ -1552,6 +1558,30 @@ impl SeqTracker { .then_some(self.csi_collected) } + /// The parameters of the CSI `b` ends that the application wrote + /// nothing in, as bits by position (the first 32), when there are any + /// and the sequence has more than one parameter. vte hands an omitted + /// parameter on as 0, so the record would list `CSI 22 ; t` as + /// `^[[22;0t`, with a 0 the application never wrote (#827). A sole + /// omitted parameter the record already reads as none (`CSI t`). + /// + /// Consulted **before** the byte is stepped, as + /// [`spaced_csi`](Self::spaced_csi) is. + pub(crate) fn omitted_params(&self, b: u8) -> Option { + if self.state != State::Csi || !(0x40..=0x7e).contains(&b) || self.csi_param_count == 0 { + return None; + } + let mut omitted = self.csi_omitted; + // vte keeps the parameter being written when the final byte comes, + // empty or not, as it keeps one ended by `;`. + if !self.csi_has_digits && !self.csi_in_subparam { + omitted |= 1u32 + .checked_shl(u32::from(self.csi_param_count)) + .unwrap_or(0); + } + (omitted != 0).then_some(omitted) + } + /// The glyph `b` draws in the invoked character set, when that set /// redefines `b` — the 32 bytes DEC Special Graphics redraws, or `#` in /// the UK set — or `None` when the byte draws as itself, or is not a @@ -1676,6 +1706,7 @@ impl SeqTracker { self.csi_param = 0; self.csi_has_digits = false; self.csi_first_param = 0; + self.csi_omitted = 0; self.csi_second_param = 0; self.csi_param_count = 0; self.csi_frame_mode_count = 0; @@ -1737,6 +1768,11 @@ impl SeqTracker { self.csi_frame_mode_count += 1; } } + if !self.csi_has_digits && !self.csi_in_subparam { + self.csi_omitted |= 1u32 + .checked_shl(u32::from(self.csi_param_count)) + .unwrap_or(0); + } match self.csi_param_count { 0 => self.csi_first_param = self.csi_param, 1 => self.csi_second_param = self.csi_param, diff --git a/crates/termlens/src/emu/unhandled.rs b/crates/termlens/src/emu/unhandled.rs index ffc6b33..c4d5f10 100644 --- a/crates/termlens/src/emu/unhandled.rs +++ b/crates/termlens/src/emu/unhandled.rs @@ -19,8 +19,9 @@ //! also filtered on the tracker's word, which the emulator passes on just //! before vt100 dispatches it, since vte can read a query in a shape the //! tracker does not (#763); and the same way the tracker supplies the -//! intermediates of a CSI vt100 reports without them (#764), and says which -//! `OSC` set an icon name (#760). +//! intermediates of a CSI vt100 reports without them (#764) and which of +//! its parameters were left empty, which vte reports as 0 (#827), and says +//! which `OSC` set an icon name (#760). //! //! The same callback set counts the rows vt100 drops off the front of the //! main screen's history, which is the one thing its history cannot tell @@ -81,6 +82,10 @@ pub(super) struct Unhandled { /// which it reports without the intermediates, or with another final — /// see [`expect_spaced`](Self::expect_spaced). spaced: Option<([u8; 2], u8)>, + /// The parameters of the CSI vt100 reports next that the application + /// wrote nothing in, as bits by position — see + /// [`expect_omitted`](Self::expect_omitted). + omitted: u32, /// The content length of the last OSC recorded, before its entry was /// cut: how much of a body reached vt100, which the capture-bound /// tests read now that the entry no longer shows it (#694, #695). @@ -101,6 +106,7 @@ impl Default for Unhandled { cut_osc: None, query: false, spaced: None, + omitted: 0, #[cfg(test)] last_osc_len: 0, } @@ -146,6 +152,7 @@ impl Unhandled { pub(super) fn settle(&mut self) { self.query = false; self.spaced = None; + self.omitted = 0; } /// Tell the record that the sequence vt100 reports next is a query the @@ -176,6 +183,15 @@ impl Unhandled { self.spaced = Some((intermediates, fin)); } + /// Tell the record which parameters of the CSI vt100 reports next the + /// application wrote nothing in, as bits by position. vte hands each + /// on as 0, and the entry listed `CSI 22 ; t` as `^[[22;0t`, with a 0 + /// nobody wrote (#827). The emulator says so just before it feeds the + /// final byte, alone, as for [`expect_spaced`](Self::expect_spaced). + pub(super) fn expect_omitted(&mut self, omitted: u32) { + self.omitted = omitted; + } + /// Tell the record what the tracker saw of the next `OSC` vte /// dispatches, which vte keeps only part of. The emulator says so just /// before it feeds the byte that ends the string. vte dispatches it at @@ -230,8 +246,9 @@ impl Unhandled { } /// `params` as they were written: `;` between parameters, `:` between the -/// sub-parameters of one. -fn params_text(params: &[&[u16]]) -> String { +/// sub-parameters of one, and nothing for a parameter in `omitted` (bits +/// by position), which the application left empty and vte reads as 0. +fn params_text(params: &[&[u16]], omitted: u32) -> String { // vte exposes an omitted parameter as one zeroed accumulator. Omitted // and explicit zero have the same default meaning, so keep the recorded // shape parameterless instead of inventing a `0` the application did @@ -242,7 +259,18 @@ fn params_text(params: &[&[u16]]) -> String { params .iter() - .map(|p| p.iter().map(u16::to_string).collect::>().join(":")) + .enumerate() + .map(|(i, p)| { + let empty = u32::try_from(i) + .ok() + .and_then(|i| omitted.checked_shr(i)) + .is_some_and(|bits| bits & 1 == 1); + if empty && **p == [0] { + String::new() + } else { + p.iter().map(u16::to_string).collect::>().join(":") + } + }) .collect::>() .join(";") } @@ -457,6 +485,9 @@ impl Callbacks for Unhandled { c: char, ) { let spaced = self.spaced.take(); + // Read, not taken: vt100 reports a mode list once for each mode + // it declines, all from one dispatch, and `settle` ends it. + let omitted = self.omitted; if std::mem::take(&mut self.query) { return; } @@ -464,7 +495,7 @@ impl Callbacks for Unhandled { // DECSCUSR and not with a sub-parameter, so each is on record, as // vte collected it and with the final the application wrote. if let Some((intermediates, fin)) = spaced { - let mut shape = format!("^[[{}", params_text(params)); + let mut shape = format!("^[[{}", params_text(params, omitted)); shape.extend( intermediates .into_iter() @@ -556,7 +587,7 @@ impl Callbacks for Unhandled { } let mut shape = String::from("^[["); shape.extend(prefix.map(char::from)); - shape.push_str(¶ms_text(params)); + shape.push_str(¶ms_text(params, omitted)); shape.extend(intermediate.map(char::from)); shape.push(c); self.record(shape); diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index 0587068..fe3fae9 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -966,6 +966,7 @@ impl Emulator for Vt100Emulator { // Asked before the step, which leaves the sequence, and used // after it (#764). let spaced = self.tracker.spaced_csi(byte); + let omitted = self.tracker.omitted_params(byte); // Asked before the step, because whether this byte is a character // at all depends on the state the tracker is in before it — and // a designation's own final byte must not be drawn. @@ -1105,6 +1106,21 @@ impl Emulator for Vt100Emulator { None } }; + // A CSI with a parameter the application left empty reaches the + // record with a 0 in its place, so the record is told which, + // between the bytes before the final byte and that byte (#827). + // The byte goes alone, so what the record was told ends with + // it whether or not vt100 reports the CSI: the spaced form and + // a query feed it alone below. + if let Some(omitted) = omitted.filter(|_| fed <= i) { + self.feed_staged(&bytes[fed..i]); + self.parser.callbacks_mut().expect_omitted(omitted); + fed = i; + if spaced.is_none() && stop.is_none() { + self.feed_staged(&bytes[i..=i]); + fed = i + 1; + } + } // A CSI whose first intermediate is `SP` reaches the record // without it, so the record is told what vte collected, between // the bytes before the final byte and that byte (#764). A query @@ -3428,6 +3444,42 @@ mod tests { assert_eq!(s.unsupported(), ["^[[18;0t"]); } + /// vte hands an omitted parameter on as 0, and an entry listed it as a + /// written `0` whenever it was not the only one: `CSI 22 ; t` was + /// `^[[22;0t` (#827). An entry shows what the application wrote. Whole + /// and split at every byte, behind a sequence vt100 carries out with an + /// omitted parameter of its own, which must lend the next entry + /// nothing. + #[test] + fn an_omitted_parameter_is_listed_as_written() { + for (sequence, shape) in [ + ("\x1b[22;t", "^[[22;t"), + ("\x1b[;5h", "^[[;5h"), + ("\x1b[20;h", "^[[20;h"), + ("\x1b[?;12h", "^[[?;12h"), + ("\x1b[1;;2;59m", "^[[1;;2;59m"), + ("\x1b[;2 @", "^[[;2 @"), + // Written out, a 0 is listed. + ("\x1b[22;0t", "^[[22;0t"), + ("\x1b[0;5h", "^[[0;5h"), + ] { + let stream = format!("\x1b[;3H{sequence}\x1b[1;h"); + for cut in 0..stream.len() { + let mut emu = Vt100Emulator::new(4, 10, 0, crate::graphics::DEFAULT_CAPTURE, false); + for piece in [&stream[..cut], &stream[cut..]] { + feed_all(&mut emu, piece.as_bytes()); + } + let s = emu.snapshot(); + assert_eq!( + s.unsupported(), + [shape, "^[[1;h"], + "{sequence:?} cut at {cut}" + ); + assert_eq!(s.cursor(), (0, 2, true), "{sequence:?} cut at {cut}"); + } + } + } + /// vt100 reports a CSI whose first intermediate is `SP` without it, all /// but DECSCUSR, which it carries out: SL (`CSI 2 SP @`) was listed as /// `^[[2@`, ICH, which the grid does have, SR as `^[[2A`, CUU, DECSWBV as diff --git a/crates/termlens/tests/unsupported.rs b/crates/termlens/tests/unsupported.rs index a48715f..e91bf9a 100644 --- a/crates/termlens/tests/unsupported.rs +++ b/crates/termlens/tests/unsupported.rs @@ -354,3 +354,22 @@ fn a_mixed_sgr_is_named_by_the_parameter_nobody_models() -> termlens::Result<()> assert!(t.wait_exit()?.success()); Ok(()) } + +/// An entry shows what the application wrote: a parameter it left empty +/// is listed empty, not as the 0 vte reads it as (#827), and a 0 it wrote +/// is listed as one. +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY renders what it implements and drops the rest before termlens sees a byte, so the record there is the console's, not the application's (#149)" +)] +fn an_empty_parameter_is_listed_as_written() -> termlens::Result<()> { + let mut t = emit(&[ + "--csi", "22;t", "--csi", ";5h", "--csi", "20;h", "--csi", "22;0t", "done", "--wait", + ])?; + t.wait_until(|s| s.contains("done"))?; + assert_eq!(shapes(&t), ["^[[22;t", "^[[;5h", "^[[20;h", "^[[22;0t"]); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} From f5ad28cdced257b86912766540affda58ab4f701 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:44:17 +0700 Subject: [PATCH 2/8] fix(emu): ignore an out-of-range SGR colour and apply the rest vt100 returns from the whole SGR when an extended colour's index or channel does not fit a byte, so in `CSI 38;5;256;1 m` the bold was lost, and nothing was listed in `Screen::unsupported()`. xterm's `parse_extended_colors` consumes the colour's values, leaves the colour as it was, and goes on to the next parameter. The colour normalizer in front of vt100 now drops such a colour, in the semicolon and the colon form, so the parameters after it apply. An SGR left with no parameter becomes a stand-in vte ignores, since an empty SGR would be a reset. Closes #823 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 5 ++ crates/termlens/src/emu/shadow.rs | 108 ++++++++++++++++++++++++++- crates/termlens/src/emu/unhandled.rs | 5 +- crates/termlens/src/emu/vt100.rs | 36 +++++++++ 4 files changed, 149 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e6d8fe..0d67036 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,11 @@ reads that marker. ### Fixed +- An extended colour with an index or a channel past 255 (`38;5;256`, + `48;2;300;0;0`, either form) is ignored and the rest of the SGR + applies, as xterm applies it: `CSI 38;5;256;1 m` draws bold and keeps + the colour in force. Every parameter after such a colour was lost, and + `Screen::unsupported()` named nothing. (#823) - `Screen::unsupported()` lists a parameter the application left empty as empty: `CSI 22 ; t` is `^[[22;t`, `CSI ; 5 h` is `^[[;5h`. Every empty parameter but a sole one was listed as a `0` the application diff --git a/crates/termlens/src/emu/shadow.rs b/crates/termlens/src/emu/shadow.rs index fa57536..58d8b1a 100644 --- a/crates/termlens/src/emu/shadow.rs +++ b/crates/termlens/src/emu/shadow.rs @@ -465,13 +465,26 @@ fn dispatch( /// `58;5;0` a reset. As one parameter it is skipped whole, and the /// sequence is still recorded as one nobody honoured (#579). crossterm /// writes the semicolon form for `SetUnderlineColor`. +/// +/// And an extended colour (`38`, `48`, in either form) with an index or a +/// channel past 255 is dropped. vt100 returns from the whole SGR when a +/// value does not fit a byte, so every parameter after it was lost: in +/// `38;5;256;1` the bold. xterm's `parse_extended_colors` (charproc.c +/// 2122) consumes the colour's values, leaves the colour as it was when +/// one is out of range (`okIndexedColor`, and its `< 256` checks for a +/// channel), and goes on to the next parameter (#823). An SGR with nothing +/// left becomes [`SGR_IGNORED`], which no parser carries out: an empty one +/// would be a reset. fn normalize_for_grid(seq: &[u8]) -> Option> { let params = seq.get(2..seq.len().checked_sub(1)?)?; if !params.iter().all(|&b| plain_param(b)) { return None; } - // The common case, checked without allocating: neither form is here. - if !params.contains(&b':') && !params.split(|&b| b == b';').any(|group| group == b"58") { + // The common case, checked without allocating: no form is here. + if !params.contains(&b':') + && !params.split(|&b| b == b';').any(|group| group == b"58") + && !has_wide_colour(params) + { return None; } @@ -501,6 +514,23 @@ fn normalize_for_grid(seq: &[u8]) -> Option> { continue; } } + if matches!(group, b"38" | b"48") { + let arguments = match groups.get(next).copied() { + Some(b"5") => 2, + Some(b"2") => 4, + _ => 0, + }; + let end = (next + arguments).min(groups.len()); + if groups[next.min(end)..end] + .iter() + .skip(1) + .any(|v| past_a_byte(v)) + { + next = end; + changed = true; + continue; + } + } let parts: Vec<&[u8]> = group.split(|&b| b == b':').collect(); let replacement = match parts.as_slice() { [first @ (b"38" | b"48"), b"2", b"", red, green, blue] @@ -511,7 +541,10 @@ fn normalize_for_grid(seq: &[u8]) -> Option> { _ => None, }; if let Some(replacement) = replacement { - normalized.extend(replacement.into_iter().map(<[u8]>::to_vec)); + // The values after the form, which xterm drops the colour for. + if !replacement[2..].iter().any(|v| past_a_byte(v)) { + normalized.extend(replacement.into_iter().map(<[u8]>::to_vec)); + } changed = true; } else { normalized.push(group.to_vec()); @@ -520,6 +553,9 @@ fn normalize_for_grid(seq: &[u8]) -> Option> { if !changed { return None; } + if normalized.is_empty() { + return Some(SGR_IGNORED.to_vec()); + } let mut out = Vec::with_capacity(seq.len()); out.extend_from_slice(b"\x1b["); @@ -533,6 +569,45 @@ fn normalize_for_grid(seq: &[u8]) -> Option> { Some(out) } +/// What stands in for an SGR [`normalize_for_grid`] leaves no parameter +/// of: an intermediate, then a parameter byte, which vte takes for a +/// malformed sequence and ignores up to the final byte, with no dispatch +/// and so no callback, as the emulator's stand-in for `REP` is. It begins +/// with the `ESC [` every rewritten form begins with, so its ESC still +/// does whatever structural work the original's did. +const SGR_IGNORED: &[u8] = b"\x1b[ 0m"; + +/// Whether a parameter, digits only, is past what a byte holds: an index +/// or a channel vt100 gives up on the SGR for. An empty one is 0. One with +/// a sub-parameter is not a value at all, and is left alone. +fn past_a_byte(value: &[u8]) -> bool { + value.iter().all(u8::is_ascii_digit) + && value.iter().fold(0u32, |acc, &d| { + acc.saturating_mul(10).saturating_add(u32::from(d - b'0')) + }) > u32::from(u8::MAX) +} + +/// Whether the semicolon form of an extended colour (`38;5;i`, +/// `48;2;r;g;b`) in `params` has an index or a channel past 255, checked +/// without allocating. +fn has_wide_colour(params: &[u8]) -> bool { + let mut groups = params.split(|&b| b == b';'); + while let Some(group) = groups.next() { + if !matches!(group, b"38" | b"48") { + continue; + } + let arguments = match groups.next() { + Some(b"5") => 1, + Some(b"2") => 3, + _ => continue, + }; + if groups.by_ref().take(arguments).any(past_a_byte) { + return true; + } + } + false +} + /// Rewrite one complete `ESC [ … m` into the carrier form. /// /// `None` means "not a plain SGR — emit it verbatim": a private prefix @@ -849,6 +924,33 @@ mod tests { } } + /// vt100 gives up on the whole SGR at a value past a byte, so the + /// colour is dropped and the rest kept, as xterm keeps it (#823). + #[test] + fn an_extended_colour_past_a_byte_is_dropped_and_the_rest_kept() { + assert_eq!(normalized(b"\x1b[38;5;256;1m"), "E[1m"); + assert_eq!(normalized(b"\x1b[1;38;2;0;300;0;4m"), "E[1;4m"); + assert_eq!(normalized(b"\x1b[48;5;99999;38;5;9m"), "E[38;5;9m"); + assert_eq!(normalized(b"\x1b[38:5:256;1m"), "E[1m"); + assert_eq!(normalized(b"\x1b[38:2::0:0:256;4m"), "E[4m"); + assert_eq!(normalized(b"\x1b[38;2;300m"), "E[ 0m"); + // Nothing left: no parser carries the stand-in out, where an + // empty SGR would be a reset. + assert_eq!(normalized(b"\x1b[38;5;256m"), "E[ 0m"); + // In range, at the edge, and a 5 that is no colour's argument. + for seq in [ + &b"\x1b[38;5;255;1m"[..], + b"\x1b[48;2;255;255;255m", + b"\x1b[1;5;256m", + b"\x1b[38;3;256m", + ] { + assert_eq!( + normalized(seq), + String::from_utf8_lossy(seq).replace('\x1b', "E") + ); + } + } + #[test] fn colon_colour_normalization_preserves_unrecognized_bytes() { assert_eq!(normalized(b"\x1b[38:2::10:20:30m"), "E[38;2;10;20;30m"); diff --git a/crates/termlens/src/emu/unhandled.rs b/crates/termlens/src/emu/unhandled.rs index c4d5f10..ba73e0b 100644 --- a/crates/termlens/src/emu/unhandled.rs +++ b/crates/termlens/src/emu/unhandled.rs @@ -390,8 +390,9 @@ pub(super) const SHADOW_SGR_PARAMS: &[u16] = &[5, 6, 8, 9, 25, 28, 29]; /// the extended colours vt100 reads in that form: the shadow carries none /// (#688), so `^[[5:6m` is a gap too. The extended colours are read as /// vt100 reads them, a form and its arguments together, and one vt100 -/// cannot read — no colour form, an index or a channel past 255, an -/// argument missing — is a gap. +/// cannot read — no colour form, an argument missing — is a gap. One with +/// an index or a channel past 255 does not get here: the emulator drops +/// it before vt100 reads the SGR, as xterm ignores it (#823). fn sgr_honoured(params: &[&[u16]]) -> bool { let byte = |value: u16| value <= u16::from(u8::MAX); let mut rest = params; diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index fe3fae9..dedfb26 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -1784,6 +1784,42 @@ mod tests { assert!(!y.conceal && !y.strikethrough); } + /// vt100 gives up on the whole SGR at an extended colour whose index or + /// channel does not fit a byte, so every parameter after it was lost, + /// and nothing was listed. xterm's `parse_extended_colors` + /// (charproc.c 2122) consumes the colour's values, leaves the colour as + /// it was, and goes on to the next parameter (#823). Whole and split at + /// every byte. + #[test] + fn an_out_of_range_colour_is_ignored_and_the_rest_of_the_sgr_applies() { + for (sgr, bold, underline) in [ + ("\x1b[38;5;256;1m", true, false), + ("\x1b[38;2;300;0;0;1m", true, false), + ("\x1b[48;5;999;4m", false, true), + ("\x1b[38:5:256;1m", true, false), + ("\x1b[38:2::0:0:256;4m", false, true), + ("\x1b[1;48;2;0;65535;0m", true, false), + ("\x1b[38;5;99999;4;48;5;256;1m", true, true), + // Nothing but the colour: nothing changes, not even a reset. + ("\x1b[38;5;256m", false, false), + ] { + let stream = format!("\x1b[31;42m{sgr}X"); + let (whole, bytewise) = whole_and_bytewise(2, 10, 0, stream.as_bytes()); + for emu in [whole, bytewise] { + let s = emu.snapshot(); + let style = *s.cell(0, 0).unwrap().style(); + assert_eq!( + (style.bold, style.underline), + (bold, underline), + "{sgr:?}: {style:?}" + ); + assert_eq!(style.fg, Color::Indexed(1), "{sgr:?}"); + assert_eq!(style.bg, Color::Indexed(2), "{sgr:?}"); + assert!(s.unsupported().is_empty(), "{sgr:?}: {:?}", s.unsupported()); + } + } + } + #[test] fn colon_form_rgb_colours_match_semicolon_form() { let emu = emu_with(b"\x1b[38;2;10;20;30mA\x1b[0m\x1b[38:2::10:20:30mB"); From 39574be0c9c12c860710d6c4dbdc84de0d1af724 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:46:33 +0700 Subject: [PATCH 3/8] fix(emu): carry out IND and NEL vt100 has no arm for `ESC D` or `ESC E`, and the tracker ended them as plain two-character escapes, so the text after either went on along the row it meant to leave and `Screen::unsupported()` listed both. The xterm-256color entry every child is handed advertises `nel`. xterm's `CASE_IND` is `xtermIndex`, which is what a line feed does, and `CASE_NEL` is that and a carriage return. The tracker now reports both, and the emulator hands vt100 a CSI vte ignores in place of the final byte, as it does for REP, then feeds both parsers the line feed (with a CR for NEL), which scrolls at the bottom margin. The unsupported() tests that used `ESC D` as an escape nobody honours use `ESC 6` now. Closes #816 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 5 +++ crates/termlens/src/emu/seq.rs | 16 +++++++++ crates/termlens/src/emu/unhandled.rs | 4 +-- crates/termlens/src/emu/vt100.rs | 52 ++++++++++++++++++++++++++++ crates/termlens/tests/unsupported.rs | 12 +++---- 5 files changed, 81 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d67036..1cf653f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,11 @@ reads that marker. ### Fixed +- IND (`ESC D`) and NEL (`ESC E`) are carried out, as xterm carries them + out: IND moves the cursor down a row and NEL to the start of the next, + each scrolling at the bottom margin as a line feed does. Both were + ignored, so the text after `tput nel` went on along the same row, and + `Screen::unsupported()` listed `^[D` and `^[E`. (#816) - An extended colour with an index or a channel past 255 (`38;5;256`, `48;2;300;0;0`, either form) is ignored and the rest of the SGR applies, as xterm applies it: `CSI 38;5;256;1 m` draws bold and keeps diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index a6cab7c..6fcfe4f 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -502,6 +502,13 @@ pub(crate) enum SeqEvent { /// [`printed`](SeqTracker::printed). The emulator takes the sequence /// from vt100 and draws `glyph` `count` times, or nothing for `None`. Repeat { glyph: Option, count: u16 }, + /// `IND` (`ESC D`) or, with `next_line`, `NEL` (`ESC E`) completed. + /// vt100 has no arm for either; xterm's `CASE_IND` is `xtermIndex`, + /// which is what a line feed does, scrolling at the bottom margin, and + /// `CASE_NEL` is that and a carriage return (charproc.c 5430 and 5449). + /// The emulator takes the escape from vt100 and feeds both parsers the + /// line feed, as it draws `REP`'s characters (#816). + Index { next_line: bool }, } /// A terminal query the application issued. The tracker classifies; @@ -2910,6 +2917,15 @@ impl SeqTracker { self.single_shift = Some(SingleShift::G3); State::Ground } + // IND and NEL, which the emulator carries out (#816). The + // xterm-256color entry every child is handed advertises + // `nel`, so `tput nel` is entitled to work. + b'D' | b'E' => { + event = SeqEvent::Index { + next_line: b == b'E', + }; + State::Ground + } // Final byte of a two-character sequence (ESC 7, ESC =, …). _ => State::Ground, }, diff --git a/crates/termlens/src/emu/unhandled.rs b/crates/termlens/src/emu/unhandled.rs index ba73e0b..1fb7b77 100644 --- a/crates/termlens/src/emu/unhandled.rs +++ b/crates/termlens/src/emu/unhandled.rs @@ -735,8 +735,8 @@ mod tests { #[test] fn a_sequence_nobody_honours_is_recorded_once_in_its_written_form() { assert_eq!( - shapes(b"\x1b[20h\x1b[20h\x1bD\x1b]9;hi\x07\x05\x1b[?69h"), - ["^[[20h", "^[D", "^[]9;hi", "^E", "^[[?69h"] + shapes(b"\x1b[20h\x1b[20h\x1b6\x1b]9;hi\x07\x05\x1b[?69h"), + ["^[[20h", "^[6", "^[]9;hi", "^E", "^[[?69h"] ); } diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index dedfb26..b08ddf3 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -859,6 +859,12 @@ const SPACED_STAND_IN: &[u8] = b"p"; /// it ended, and the rewriters hold and release it as ever. const REP_IGNORED: &[u8] = b" 0b"; +/// What ends `IND` or `NEL` (`ESC D`, `ESC E`) in place of its final byte, +/// whose ESC is fed already: a CSI vte ignores as it ignores +/// [`REP_IGNORED`], so vt100, which would list the escape, never sees it +/// (#816). +const ESC_IGNORED: &[u8] = b"[ 0b"; + /// U+FE0F as the bytes it arrives in. Its first byte is a UTF-8 lead byte, /// never a continuation or an ASCII byte, so matching it at a character /// boundary is enough, and no character-set glyph is ever staged from it. @@ -1096,6 +1102,18 @@ impl Emulator for Vt100Emulator { } None } + SeqEvent::Index { next_line } => { + // vt100 has no arm for either escape, so it is handed + // one vte ignores, and the line feed xterm's + // `xtermIndex` is, with a carriage return for NEL. A + // line feed is what vt100 scrolls at the bottom margin + // by, in both parsers (#816). + self.feed_staged(&bytes[fed..i]); + self.feed(ESC_IGNORED); + fed = i + 1; + self.feed(if next_line { b"\r\n" } else { b"\n" }); + None + } SeqEvent::None => None, SeqEvent::SyncBegin => { // Stamped here, at the byte that opened the update, @@ -3211,6 +3229,40 @@ mod tests { } } + /// IND (`ESC D`) and NEL (`ESC E`) were ignored: vt100 has no arm for + /// either, and the text after one went on along the row it meant to + /// leave (#816). xterm's `CASE_IND` is `xtermIndex`, which scrolls at + /// the bottom margin as a line feed does, and `CASE_NEL` is that and a + /// carriage return (charproc.c 5430 and 5449). Whole and split at + /// every byte; neither is listed. + #[test] + fn ind_and_nel_move_down_and_scroll_at_the_bottom_margin() { + for (stream, text, cursor) in [ + ("abc\x1bEdef", "abc\ndef\n", (1, 3)), + ("abc\x1bDdef", "abc\n def\n", (1, 6)), + // At the bottom row, the screen scrolls. + ("a\r\nb\r\nc\x1bEd", "b\nc\nd", (2, 1)), + ("a\r\nb\r\nc\x1bDd", "b\nc\n d", (2, 2)), + // At the bottom margin, the region scrolls and nothing below it. + ("\x1b[1;2r\x1b[3Hz\x1b[Ha\r\nb\x1bEc", "b\nc\nz", (1, 1)), + // A control inside the escape is carried out, and the escape + // goes on. + ("abc\x1b\rEdef", "abc\ndef\n", (1, 3)), + ] { + let (whole, bytewise) = whole_and_bytewise(3, 10, 0, stream.as_bytes()); + for emu in [whole, bytewise] { + let s = emu.snapshot(); + assert_eq!(s.text(), text, "{stream:?}"); + assert_eq!(s.cursor(), (cursor.0, cursor.1, true), "{stream:?}"); + assert!( + s.unsupported().is_empty(), + "{stream:?}: {:?}", + s.unsupported() + ); + } + } + } + #[test] fn rep_repeats_the_last_character_drawn() { // REP (`CSI n b`), which the xterm-256color terminfo advertises and diff --git a/crates/termlens/tests/unsupported.rs b/crates/termlens/tests/unsupported.rs index e91bf9a..cff4620 100644 --- a/crates/termlens/tests/unsupported.rs +++ b/crates/termlens/tests/unsupported.rs @@ -29,23 +29,23 @@ fn shapes(t: &Terminal) -> Vec { )] fn an_unimplemented_sequence_is_listed_once() -> termlens::Result<()> { let mut t = emit(&[ - "--csi", "20h", "--csi", "20h", "--esc", "D", "text", "--wait", + "--csi", "20h", "--csi", "20h", "--esc", "6", "text", "--wait", ])?; t.wait_until(|s| s.contains("text"))?; - assert_eq!(shapes(&t), ["^[[20h", "^[D"]); + assert_eq!(shapes(&t), ["^[[20h", "^[6"]); // The view pins the whole record in one comparison (#330): the shapes // in order, and that nothing overflowed. let s = t.screen(); - assert_eq!(s.unsupported(), ["^[[20h", "^[D"]); + assert_eq!(s.unsupported(), ["^[[20h", "^[6"]); assert_eq!(s.unsupported().overflow(), 0); assert_eq!(s.unsupported().len(), 2); assert!(!s.unsupported().is_empty()); - assert!(s.unsupported().contains("^[D")); + assert!(s.unsupported().contains("^[6")); assert!(!s.unsupported().contains("^[[20l")); - assert_eq!(format!("{:?}", s.unsupported()), r#"["^[[20h", "^[D"]"#); + assert_eq!(format!("{:?}", s.unsupported()), r#"["^[[20h", "^[6"]"#); assert_eq!( s.unsupported().into_iter().collect::>(), - ["^[[20h", "^[D"] + ["^[[20h", "^[6"] ); t.send(Key::Enter)?; assert!(t.wait_exit()?.success()); From d3f6d2c20e2721b482397d57902c11b53e2f326a Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:50:28 +0700 Subject: [PATCH 4/8] fix(emu): end origin mode on a resize, as xterm does On a change of size the tracker cleared both screens' margins and kept origin mode, following vt100. xterm's ScreenResize clears both together (`resetMargins(xw); UIntClr(*flags, ORIGIN);`), so after a resize and a new region, `CUP 1;1` drew at the region's top here and at the screen's corner in xterm. The tracker now clears origin mode on both screens with the margins and says which had it on. The emulator resets it in those vt100 grids with `CSI ? 6 l`, putting a hidden grid on display for it as the resize does, and moves the cursor back where it was, since vt100 homes it. Being bytes, the reset waits while the stream is inside a sequence and is carried out where that sequence ends. Closes #826 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 4 + crates/termlens/src/emu/seq.rs | 17 +++- crates/termlens/src/emu/vt100.rs | 139 ++++++++++++++++++++++++++++++- crates/termlens/tests/state.rs | 33 ++++++++ 4 files changed, 189 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cf653f..209f61e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,10 @@ reads that marker. ### Fixed +- A change of size ends origin mode (`DECOM`) with the scroll margins, as + xterm's resize does, and leaves the cursor where it was. Origin mode + stayed on, so once the program set a new region, `CUP 1;1` drew at + that region's top row rather than the screen's corner. (#826) - IND (`ESC D`) and NEL (`ESC E`) are carried out, as xterm carries them out: IND moves the cursor down a row and NEL to the start of the next, each scrolling at the bottom margin as a line feed does. Both were diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index 6fcfe4f..1f75f3f 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -1173,17 +1173,28 @@ impl SeqTracker { /// Follow a resize of the grid. The tab-stop set grows or shrinks with /// it — see [`TabStops::set_cols`] for what happens to the columns on /// either side of the change — and a change of size clears both - /// screens' margins, as vt100's does (xterm's too). Origin mode stays. - pub(crate) fn set_size(&mut self, rows: u16, cols: u16) { + /// screens' margins, as vt100's does, and their origin mode, which + /// vt100 keeps: xterm's `ScreenResize` does both together + /// (`resetMargins(xw); UIntClr(*flags, ORIGIN);`, screen.c 2458), and + /// with origin mode kept the next region a program set moved where + /// `CUP` counted from (#826). The origin mode a `DECSC` saved stays, as + /// xterm's saved cursor keeps its own flags. + /// + /// Returns which screens, main then alternate, had origin mode on, for + /// the emulator to clear in vt100's grids too. + pub(crate) fn set_size(&mut self, rows: u16, cols: u16) -> [bool; 2] { // vt100 makes a zero dimension one, so both are compared that way. let size = (rows.max(1), cols.max(1)); + let mut cleared = [false; 2]; if size != (self.rows, self.cols) { - for screen in &mut self.screens { + for (screen, cleared) in self.screens.iter_mut().zip(&mut cleared) { (screen.top, screen.bottom) = (0, None); + *cleared = std::mem::take(&mut screen.origin); } } (self.rows, self.cols) = size; self.tabs.set_cols(cols); + cleared } /// The frame of the screen on display. diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index b08ddf3..882b869 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -75,6 +75,11 @@ pub(crate) struct Vt100Emulator { /// the parsers see is then no longer a sub-slice of the read. Kept /// between calls only for its allocation. staged: Vec, + /// vt100's grids, main then alternate, whose origin mode a resize + /// ended in the tracker and not yet in vt100, which is told with bytes + /// and so only between sequences — see + /// [`end_origin_mode`](Self::end_origin_mode). + origin_owed: [bool; 2], } /// The images a logged kitty escape names, as its [`Placement`] carried @@ -148,6 +153,7 @@ impl Vt100Emulator { image_support: Graphics::None, cell_size: None, staged: Vec::new(), + origin_owed: [false; 2], } } @@ -617,6 +623,64 @@ impl Vt100Emulator { } } + /// End origin mode in the vt100 grids a resize ended it on in the + /// tracker, as xterm's `ScreenResize` does (#826), and leave each + /// cursor where it was: vt100 homes the cursor when origin mode is + /// reset, and xterm's resize moves none. A grid behind the one on + /// display is put on display for it, as [`set_size`] does for the + /// resize itself. + /// + /// The reset is bytes, so it waits while the stream is inside a + /// sequence, which it would break, and is carried out where that + /// sequence ends: the next byte it could change the meaning of is one + /// after it. + /// + /// [`set_size`]: Emulator::set_size + fn end_origin_mode(&mut self) { + if self.origin_owed == [false; 2] || self.tracker.mid_sequence() { + return; + } + let owed = std::mem::take(&mut self.origin_owed); + let alternate = self.parser.screen().alternate_screen(); + for (grid_is_alternate, owed) in [(false, owed[0]), (true, owed[1])] { + if !owed { + continue; + } + let behind = grid_is_alternate != alternate; + let (show, hide) = if grid_is_alternate { + (SHOW_ALTERNATE_GRID, SHOW_MAIN_GRID) + } else { + (SHOW_MAIN_GRID, SHOW_ALTERNATE_GRID) + }; + if behind { + self.parser.process(show); + self.shadow.feed_verbatim(show); + } + let (row, col) = self.parser.screen().cursor_position(); + self.feed(b"\x1b[?6l"); + self.put_cursor_back(row, col); + if behind { + self.parser.process(hide); + self.shadow.feed_verbatim(hide); + } + } + } + + /// Move the cursor to `row`, `col` of the grid on display, a column + /// past the last included, with origin mode off. `CUP` cannot address + /// the column past the margin, where vt100 keeps a cursor pending + /// wrap, so for that one the last column is drawn again, which is the + /// one way to put a cursor back there (#753). + fn put_cursor_back(&mut self, row: u16, col: u16) { + let (_, cols) = size(self.parser.screen()); + if col < cols { + self.feed(format!("\x1b[{};{}H", row + 1, col + 1).as_bytes()); + } else { + self.feed(format!("\x1b[{}d", row + 1).as_bytes()); + self.redraw_last_column(row); + } + } + /// The cursor as a snapshot should report it: a column pending wrap /// sits one past the last cell inside the backend, and no terminal /// reports a column its own width does not have (#401). Clamping here @@ -919,6 +983,13 @@ impl Emulator for Vt100Emulator { // end, so each character is looked at once. let mut run_until = 0; for (i, &byte) in bytes.iter().enumerate() { + // A resize inside a sequence ended origin mode in the tracker + // and owes it to vt100, where the sequence has ended (#826). + if self.origin_owed != [false; 2] && !self.tracker.mid_sequence() { + self.feed_staged(&bytes[fed..i]); + fed = i; + self.end_origin_mode(); + } // A character is handled at the live cursor, with everything // owed to the grid fed first, wherever it falls in the read: // the screen must not depend on where the PTY split the output @@ -1182,6 +1253,7 @@ impl Emulator for Vt100Emulator { } } self.feed_staged(&bytes[fed..]); + self.end_origin_mode(); Processed { consumed: bytes.len(), stop: None, @@ -1380,7 +1452,10 @@ impl Emulator for Vt100Emulator { // are resized the same way, so their grids stay in step. resize_as_xterm(&mut self.parser, rows, cols); self.shadow.set_size(rows, cols); - self.tracker.set_size(rows, cols); + let cleared = self.tracker.set_size(rows, cols); + for (owed, cleared) in self.origin_owed.iter_mut().zip(cleared) { + *owed |= cleared; + } // A resize can push rows into history on its own, drop rows from // its front, or pull rows back out of it. self.capture_scrolled_rows(); @@ -1388,6 +1463,7 @@ impl Emulator for Vt100Emulator { self.parser.process(SHOW_ALTERNATE_GRID); self.shadow.feed_verbatim(SHOW_ALTERNATE_GRID); } + self.end_origin_mode(); } } @@ -4387,6 +4463,67 @@ mod tests { assert_eq!(screen.text(), "hello\n"); } + /// What [`x_after_a_resize`] saw at one cut: the position reported once + /// the tail was in, and where `X` was after each later piece. + type AfterResize = ((u16, u16), Vec>); + + /// `setup`, then `tail` with a resize from 6 rows to 7 at every cut of + /// it, so the resize also comes while the stream is inside a sequence, + /// then each of `after` in turn: the position reported once `tail` is + /// all in, and where `X` is after each of `after`. + fn x_after_a_resize(setup: &str, tail: &str, after: &[&str]) -> Vec { + (0..=tail.len()) + .map(|cut| { + let mut emu = Vt100Emulator::new(6, 10, 0, crate::graphics::DEFAULT_CAPTURE, false); + feed_all(&mut emu, setup.as_bytes()); + feed_all(&mut emu, &tail.as_bytes()[..cut]); + emu.set_size(7, 10); + feed_all(&mut emu, &tail.as_bytes()[cut..]); + let at = emu.reported_position(); + let xs = after + .iter() + .map(|bytes| { + feed_all(&mut emu, bytes.as_bytes()); + emu.snapshot().find("X") + }) + .collect(); + (at, xs) + }) + .collect() + } + + /// xterm's `ScreenResize` clears origin mode with the margins + /// (`resetMargins(xw); UIntClr(*flags, ORIGIN);`, screen.c 2458), and + /// termlens cleared only the margins, as vt100 does: once the program + /// set a region again, `CUP 1;1` counted from its top (#826). The + /// cursor stays where it was, though vt100 homes it when origin mode + /// is reset. + #[test] + fn a_resize_ends_origin_mode_on_both_screens() { + // Origin mode on, the cursor at row 2, column 4 of the screen; then + // a new region, and `CUP 1;1`. + let runs = x_after_a_resize( + "\x1b[2;5r\x1b[?6h\x1b[2;5H", + "\x1b[1m", + &["\x1b[3;5r\x1b[1;1HX"], + ); + for (cut, (at, xs)) in runs.into_iter().enumerate() { + assert_eq!(xs, [Some((0, 0))], "cut at {cut}"); + // Inside the SGR, the resize is settled where the SGR ends. + assert_eq!(at, (2, 4), "cut at {cut}"); + } + // Set on the alternate screen and on the main one behind it. + let runs = x_after_a_resize( + "\x1b[2;5r\x1b[?6h\x1b[?47h\x1b[2;5r\x1b[?6h\x1b[2;5H", + "\x1b[1m", + &["\x1b[3;5r\x1b[1;1HX", "\x1b[?47l\x1b[3;5r\x1b[1;2HX"], + ); + for (cut, (at, xs)) in runs.into_iter().enumerate() { + assert_eq!(xs, [Some((0, 0)), Some((0, 1))], "cut at {cut}"); + assert_eq!(at, (2, 4), "cut at {cut}"); + } + } + /// A 24-column emulator, the width the issue's reproductions use. fn wide_emu(bytes: &[u8]) -> Vt100Emulator { let mut emu = Vt100Emulator::new(2, 24, 0, crate::graphics::DEFAULT_CAPTURE, false); diff --git a/crates/termlens/tests/state.rs b/crates/termlens/tests/state.rs index f40bdb1..35b39d0 100644 --- a/crates/termlens/tests/state.rs +++ b/crates/termlens/tests/state.rs @@ -440,3 +440,36 @@ fn an_unreadable_clipboard_payload_is_reported_as_such() -> termlens::Result<()> assert!(t.wait_exit()?.success()); Ok(()) } + +/// xterm's `ScreenResize` ends origin mode with the margins, so after a +/// resize `CUP 1;1` is the screen's corner again, whatever region the +/// program sets next. termlens kept origin mode on, and the `X` landed on +/// the new region's top row (#826). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY applies a resize on its own thread and re-renders the screen itself, so the rows termlens holds after it are conhost's layout (#149)" +)] +fn a_resize_ends_origin_mode() -> termlens::Result<()> { + let mut t = common::spawn_emit( + Terminal::builder() + .size(10, 6) + .timeout(Duration::from_secs(10)), + &[ + "--raw", + r"\e[2;5r\e[?6hready", + "--wait", + "--raw", + r"\e[3;5r\e[1;1HX", + "--wait", + ], + )?; + t.wait_until(|s| s.contains("ready"))?; + t.resize(10, 7)?; + t.send(Key::Enter)?; + let s = t.snapshot_after(|s| s.contains("X"))?; + assert_eq!(s.find("X"), Some((0, 0)), "\n{s}"); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} From 70cae966fe6ff3718edebd11758b20f256e42372 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:53:13 +0700 Subject: [PATCH 5/8] fix(emu): answer ANSI-mode DECRQM and report origin mode The tracker classified `CSI Ps $ p` as a question it cannot answer, so an application that asked for an ANSI mode got no reply and waited out its own timeout, though xterm answers every ANSI-mode request (`do_ansi_rqm`, misc.c 5408). And `CSI ? 6 $ p` reported origin mode as not recognized, though the tracker follows it per screen and the position report reads it. The request is now its own query, answered from a new emulator method: insert mode from the tracker, every other ANSI mode "not recognized", as an unknown private mode already is. `mode_state` reports mode 6 from the tracker. The responder in terminal.rs gains the one arm that writes the reply, and the shape a timeout would name. Closes #830 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 7 +++++++ crates/termlens/src/emu/mod.rs | 7 +++++++ crates/termlens/src/emu/seq.rs | 21 +++++++++++++++---- crates/termlens/src/emu/vt100.rs | 35 ++++++++++++++++++++++++++++++++ crates/termlens/src/terminal.rs | 5 +++++ crates/termlens/tests/queries.rs | 35 ++++++++++++++++++++++++++++++++ docs/DESIGN.md | 5 ++++- 7 files changed, 110 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 209f61e..a344b90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,13 @@ reads that marker. ### Changed +- ANSI-mode DECRQM (`CSI Ps $ p`) is answered, as xterm answers it: + insert mode (`CSI 4 $ p`) reports set or reset, and every other ANSI + mode `0`, not recognized. It got no reply, so a program that asked + waited out its own timeout, which named the request. And `CSI ? 6 $ p` + reports origin mode set or reset, where it reported `0` though the + mode is followed per screen. A test that expected `^[[4$p` in a + timeout's note should expect the reply. (#830) - DA1 and DA2 are answered whatever follows a first parameter of 0 (`CSI 0;1 c`, `CSI > 0;1 c`), as xterm answers them by that parameter alone. They got no reply, so a program that asked that way waited out diff --git a/crates/termlens/src/emu/mod.rs b/crates/termlens/src/emu/mod.rs index 5986610..305cc5e 100644 --- a/crates/termlens/src/emu/mod.rs +++ b/crates/termlens/src/emu/mod.rs @@ -164,6 +164,13 @@ pub(crate) trait Emulator: Send { /// Whether DEC private mode `mode` is set, for answering `DECRQM`. fn mode_state(&self, mode: u32) -> ModeState; + /// Whether ANSI mode `mode` is set, for answering the ANSI form of + /// `DECRQM` (`CSI Ps $ p`). "Not recognized" unless the emulator holds + /// the mode exactly, as for [`mode_state`](Self::mode_state). + fn ansi_mode_state(&self, _mode: u32) -> ModeState { + ModeState::NotRecognized + } + /// Resize the emulated grid to `rows` × `cols`. fn set_size(&mut self, rows: u16, cols: u16); } diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index 1f75f3f..e352620 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -539,6 +539,10 @@ pub(crate) enum Query { /// this truthfully lets an application that *probes* before using a /// mode (synchronized output above all) turn it on against termlens. RequestMode(u32), + /// ANSI-mode DECRQM: "is ANSI mode `n` set?" — `CSI n $ p`, with no + /// `?`. xterm answers every one (`do_ansi_rqm`, misc.c 5408), so a + /// program that asks waits for the reply; it went unanswered (#830). + RequestAnsiMode(u32), /// Window size in pixels: `CSI 14 t`. WindowSizePixels, /// Character cell size in pixels: `CSI 16 t`. @@ -1909,7 +1913,13 @@ impl SeqTracker { (b'?', b'p') if self.csi_param_count == 1 => { SeqEvent::Query(Query::RequestMode(self.csi_first_param)) } - // ANSI-mode DECRQM and mode *reports* we cannot answer. + // The ANSI form, which needs the `$` alone, as xterm's + // table does (#830). + (0, b'p') if self.csi_param_count == 1 && self.csi_collected == [b'$', 0] => { + SeqEvent::Query(Query::RequestAnsiMode(self.csi_first_param)) + } + // Mode *reports*, and requests of another shape, which we + // cannot answer. (_, b'p' | b'y') => SeqEvent::Query(Query::Unanswerable(self.seq_printable())), _ => SeqEvent::None, }; @@ -5338,10 +5348,13 @@ mod tests { assert_eq!(queries_of(b"\x1b[?2026$p"), vec![Query::RequestMode(2026)]); assert_eq!(queries_of(b"\x1b[?2004$p"), vec![Query::RequestMode(2004)]); assert_eq!(queries_of(b"\x1b[?1$p"), vec![Query::RequestMode(1)]); - // ANSI-mode DECRQM (no `?`) is recognized but not answerable. + // ANSI-mode DECRQM (no `?`) is answered too (#830), with one + // parameter; a request with none is still named. + assert_eq!(queries_of(b"\x1b[4$p"), vec![Query::RequestAnsiMode(4)]); + assert_eq!(queries_of(b"\x1b[20$p"), vec![Query::RequestAnsiMode(20)]); assert_eq!( - queries_of(b"\x1b[4$p"), - vec![Query::Unanswerable("^[[4$p".into())] + queries_of(b"\x1b[$p"), + vec![Query::Unanswerable("^[[$p".into())] ); // The mode written after the `$` is no request: vte ignores the // sequence, and so does xterm (`csi_dollar_table` and diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index 882b869..279cc75 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -1402,6 +1402,10 @@ impl Emulator for Vt100Emulator { 25 => on(!screen.hide_cursor()), 47 | 1047 | 1049 => on(screen.alternate_screen()), 2004 => on(screen.bracketed_paste()), + // Origin mode, which the tracker follows per screen as vt100 + // holds it, and the position report reads (#689). It was "not + // recognized" though the state was held (#830). + 6 => on(self.tracker.origin_mode()), // Tracked by termlens itself, so the state is exact — which is // what the honesty rule requires before answering. 1004 => on(self.tracker.focus_events()), @@ -1429,6 +1433,21 @@ impl Emulator for Vt100Emulator { } } + fn ansi_mode_state(&self, mode: u32) -> ModeState { + match mode { + // Insert mode, which the tracker keeps and the emulator + // carries out (#261). No other ANSI mode is modelled (#830). + 4 => { + if self.tracker.insert_mode() { + ModeState::Set + } else { + ModeState::Reset + } + } + _ => ModeState::NotRecognized, + } + } + fn set_size(&mut self, rows: u16, cols: u16) { // While the alternate screen is up the main grid is resized too, // out of sight, and every accessor reads the grid on display: the @@ -4969,6 +4988,22 @@ mod tests { assert_eq!(cursor_col(b"\x1b[3g\x1b[4G\x1bH\x1b[!p\x1b[1G\t"), 3); } + /// DECRQM reports origin mode from the screen on display, which keeps + /// its own in vt100, and the ANSI form reports insert mode; both were + /// "not recognized" or unanswered (#830). + #[test] + fn decrqm_reports_origin_mode_per_screen_and_insert_mode() { + let mut emu = emu_with(b"\x1b[?6h\x1b[4h"); + assert_eq!(emu.mode_state(6), ModeState::Set); + assert_eq!(emu.ansi_mode_state(4), ModeState::Set); + assert_eq!(emu.ansi_mode_state(20), ModeState::NotRecognized); + feed_all(&mut emu, b"\x1b[?1049h"); + assert_eq!(emu.mode_state(6), ModeState::Reset, "the alternate screen"); + feed_all(&mut emu, b"\x1b[?1049l\x1b[4l"); + assert_eq!(emu.mode_state(6), ModeState::Set, "the main screen again"); + assert_eq!(emu.ansi_mode_state(4), ModeState::Reset); + } + /// `DECSTR` clears the rendition, as xterm's soft reset does: a /// character written after it is plain (#687). #[test] diff --git a/crates/termlens/src/terminal.rs b/crates/termlens/src/terminal.rs index cf953b9..8a0dfc4 100644 --- a/crates/termlens/src/terminal.rs +++ b/crates/termlens/src/terminal.rs @@ -1608,6 +1608,10 @@ impl EmuState { let value = self.emu.mode_state(*mode).report_value(); format!("\x1b[?{mode};{value}$y").into_bytes() } + Query::RequestAnsiMode(mode) => { + let value = self.emu.ansi_mode_state(*mode).report_value(); + format!("\x1b[{mode};{value}$y").into_bytes() + } Query::RequestTermcap { names, shape } => { match termcap_reply(names, &self.term_name) { Some(reply) => reply, @@ -2737,6 +2741,7 @@ fn query_shape(query: &Query) -> String { Query::RequestTermcap { shape, .. } => shape.clone(), Query::OscColor { code, .. } => format!("^[]{code};?"), Query::RequestMode(mode) => format!("^[[?{mode}$p"), + Query::RequestAnsiMode(mode) => format!("^[[{mode}$p"), Query::Unanswerable(shape) => shape.clone(), } } diff --git a/crates/termlens/tests/queries.rs b/crates/termlens/tests/queries.rs index 599fecc..14de9be 100644 --- a/crates/termlens/tests/queries.rs +++ b/crates/termlens/tests/queries.rs @@ -581,6 +581,41 @@ fn mode_reports_are_truthful() -> termlens::Result<()> { Ok(()) } +/// ANSI-mode DECRQM (`CSI Ps $ p`) is answered, as xterm's `do_ansi_rqm` +/// answers it (misc.c 5408): insert mode from the state termlens keeps, +/// and every other ANSI mode "not recognized". It got no reply, and a +/// program that asked waited out its own timeout. Origin mode, which +/// termlens follows per screen, is reported from that, where it was "not +/// recognized" (#830). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY answers or eats the child's queries itself, so they never reach the responder (#149)" +)] +fn ansi_decrqm_and_origin_mode_are_answered() -> termlens::Result<()> { + let mut t = probe(&[ + "--raw-mode", + "--raw", + r"\e[4h\e[?6h\e[4$p\e[?6$p\e[20$p\e[4l\e[?6l\e[4$p\e[?6$p", + // ESC[4;1$y ESC[?6;1$y ESC[20;0$y ESC[4;2$y ESC[?6;2$y: + // 7 + 8 + 8 + 7 + 8 = 38 bytes. + "got:", + "--read", + "38", + " DONE", + "--wait", + ])?; + t.wait_until(|s| s.contains("DONE"))?; + let row = t.screen().row_text(0); + assert_eq!( + row.trim_end(), + "got:E[4;1$yE[?6;1$yE[20;0$yE[4;2$yE[?6;2$y DONE" + ); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + /// The families we recognize but cannot answer are now named in the /// timeout instead of hanging silently. #[test] diff --git a/docs/DESIGN.md b/docs/DESIGN.md index af71dd5..30e3e21 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -57,7 +57,10 @@ is what lets an application that *probes* before using synchronized output turn it on against termlens — so `wait_frame` can work against a program nobody modified for us. Every reply is truthful or absent: modes whose state the emulator holds exactly report set/reset, and -anything else reports "not recognized" rather than a guess. +anything else reports "not recognized" rather than a guess. The ANSI +form (`CSI Ps $ p`) follows the same rule: insert mode, which termlens +carries out, reports set/reset, and every other ANSI mode "not +recognized" (#830). The mouse tracking modes used to show where that line falls. The backend collapses `9`/`1000`/`1002`/`1003` into one mutually exclusive From 778245561a1bf46f61d401c946916b34e3a8e496 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:55:53 +0700 Subject: [PATCH 6/8] fix(emu): empty the mouse tracking set on a reset of any mode Since #693 a reset of any of 9, 1000, 1002 and 1003 turns reporting off, and click, drag, scroll and mouse_move refuse. The reset took out only the mode it named from the requested set DECRQM answers from, so after `?1003h ?1000l` DECRQM said any-event tracking was on while termlens's own input path sent nothing. xterm sets `MOUSE_OFF` on a reset of any of the four, and its DECRQM then answers each one reset. The tracker now empties the set on such a reset, so DECRQM answers 2 for every tracking mode until one is set again, and `Screen::mouse_modes()` stops listing a mode nothing reports in. The tests that pinned the old rule, and the rustdoc and DESIGN text that stated it, follow. DECRQM while two modes are both set is #151's design and is left as it is. Closes #832 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 8 +++++ crates/termlens/src/emu/seq.rs | 39 ++++++++++++++---------- crates/termlens/src/emu/vt100.rs | 51 ++++++++++++++++++-------------- crates/termlens/src/screen.rs | 16 ++++++---- crates/termlens/tests/input.rs | 5 ++-- crates/termlens/tests/queries.rs | 16 ++++++++-- crates/termlens/tests/state.rs | 26 +++++++++++----- docs/DESIGN.md | 5 +++- 8 files changed, 110 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a344b90..234f22c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,14 @@ reads that marker. ### Changed +- A reset of any mouse tracking mode (`CSI ? 9 l`, `? 1000 l`, + `? 1002 l`, `? 1003 l`) empties the set `Screen::mouse_modes()` + reports, and DECRQM answers every tracking mode reset until one is set + again, as xterm's one tracking mode is then off. The reset took out + only the mode it named, so after `CSI ? 1003 h CSI ? 1000 l` DECRQM + reported 1003 set while termlens itself sent no mouse report. A test + that expected the modes a reset did not name in `mouse_modes()` should + expect an empty set. (#832) - ANSI-mode DECRQM (`CSI Ps $ p`) is answered, as xterm answers it: insert mode (`CSI 4 $ p`) reports set or reset, and every other ANSI mode `0`, not recognized. It got no reply, so a program that asked diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index e352620..73f2f04 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -969,13 +969,17 @@ pub(crate) struct SeqTracker { /// Tracked here because vt100 does not model 1004 at all — the same /// reason the window title is tracked here. focus_events: bool, - /// The mouse tracking modes the application has enabled and not yet - /// disabled, as [`mouse_bit`]s. vt100 collapses the four into the one - /// protocol it would report in — correct for the input path, since a - /// terminal reports in one protocol — which cannot say which members - /// of the group were asked for; crossterm asks for three at once. The - /// set is kept here so `DECRQM` can answer each mode on its own - /// evidence and a snapshot can report what was requested (#151). + /// The mouse tracking modes the application has enabled since reporting + /// was last turned off, as [`mouse_bit`]s. vt100 collapses the four + /// into the one protocol it would report in — correct for the input + /// path, since a terminal reports in one protocol — which cannot say + /// which members of the group were asked for; crossterm asks for three + /// at once. The set is kept here so `DECRQM` can answer each mode on + /// its own evidence and a snapshot can report what was requested + /// (#151). A reset of any of the four empties it, as it ends reporting: + /// xterm then holds no tracking mode, and DECRQM there answers each one + /// reset. Taking out only the mode the reset named reported 1003 set + /// after `?1003h ?1000l`, though nothing reported in it (#832). mouse_tracking: u8, /// The one protocol mouse events are reported in, by xterm's rule: the /// tracking mode set last, and none once any of the four is reset, @@ -2003,10 +2007,12 @@ impl SeqTracker { // The mouse tracking modes, kept as the set the application asked // for — see `mouse_tracking`. Every mode named in one list is set - // or cleared together, which is how they arrive. And the one - // protocol reports are made in — see `mouse_protocol`: a list is - // applied in order, so a set leaves the last mode it names in - // force, and a reset naming any of them turns reporting off. + // together, which is how they arrive. And the one protocol reports + // are made in — see `mouse_protocol`: a list is applied in order, + // so a set leaves the last mode it names in force, and a reset + // naming any of them turns reporting off, and empties the set with + // it, since xterm then holds no tracking mode for DECRQM to report + // set (#832). if self.csi_prefix == b'?' && self.csi_saw_mouse != 0 { match b { b'h' => { @@ -2014,7 +2020,7 @@ impl SeqTracker { self.mouse_protocol = self.csi_last_mouse; } b'l' => { - self.mouse_tracking &= !self.csi_saw_mouse; + self.mouse_tracking = 0; self.mouse_protocol = MouseMode::None; } _ => {} @@ -4824,13 +4830,16 @@ mod tests { MouseMode::ButtonMotion ); - // The set the application asked for is a different fact: a reset - // takes out the modes it names and no others. + // A reset empties the set the application asked for too, as + // xterm's `MOUSE_OFF` leaves no mode for DECRQM to report set + // (#832); a set after it starts the set over. let tracker = fed(b"\x1b[?1002h\x1b[?1003h\x1b[?1000l"); assert_eq!(tracker.mouse_protocol(), MouseMode::None); + assert!(tracker.mouse_tracking().is_empty()); + let tracker = fed(b"\x1b[?1002h\x1b[?1003h\x1b[?1000l\x1b[?9h"); assert_eq!( tracker.mouse_tracking().iter().collect::>(), - [MouseMode::ButtonMotion, MouseMode::AnyMotion] + [MouseMode::Press] ); } diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index 279cc75..f87d3a4 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -4396,23 +4396,30 @@ mod tests { ] ); - // Releasing one member releases that member alone in the set, while - // reporting turns off, as in xterm, where a reset of any member - // ends it. Both facts are true; each is reported where it belongs. + // A reset of any member ends reporting, as in xterm, where it sets + // `MOUSE_OFF`, and with it every member of the set: DECRQM answers + // each "reset", as xterm's does, until one is set again (#832). let emu = emu_with(b"\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1003l"); - assert_eq!(emu.mode_state(1003), ModeState::Reset); - assert_eq!(emu.mode_state(1002), ModeState::Set); + for mode in [1000, 1002, 1003] { + assert_eq!(emu.mode_state(mode), ModeState::Reset, "mode {mode}"); + } let screen = emu.snapshot(); assert_eq!(screen.mouse_mode(), MouseMode::None); - assert!(screen.mouse_modes().contains(MouseMode::ButtonMotion)); + assert!(screen.mouse_modes().is_empty()); - // A list sets or clears every member it names, and a hard reset - // empties the set. - let emu = emu_with(b"\x1b[?1000;1002;1003h\x1b[?1000;1002l"); + // A set after the reset is the whole set again. + let emu = emu_with(b"\x1b[?1003h\x1b[?1000l\x1b[?1002h"); + assert_eq!(emu.mode_state(1003), ModeState::Reset); + assert_eq!(emu.mode_state(1002), ModeState::Set); assert_eq!( emu.snapshot().mouse_modes().iter().collect::>(), - [MouseMode::AnyMotion] + [MouseMode::ButtonMotion] ); + + // A list sets every member it names, a reset in a list clears all + // four, and a hard reset empties the set. + let emu = emu_with(b"\x1b[?1000;1002;1003h\x1b[?1000;1002l"); + assert!(emu.snapshot().mouse_modes().is_empty()); assert!(emu_with(b"\x1b[?1003h\x1bc") .snapshot() .mouse_modes() @@ -4432,27 +4439,27 @@ mod tests { /// of 9, 1000, 1002 or 1003 alike, and `Screen::mouse_mode` says so. /// vt100 clears its mode only when the reset names the one it holds, so /// after `?1002h ?1000l` the input path went on reporting (#693). The - /// set is a different fact and keeps what was asked for and not - /// disabled, as `DECRQM` reads it. + /// set empties with it, since xterm then holds no tracking mode, and + /// `DECRQM` reads the set: it reported the mode set while nothing + /// reported in it (#832). #[test] fn a_reset_of_another_tracking_mode_turns_reporting_off() { - for (stream, asked) in [ - (&b"\x1b[?1002h\x1b[?1000l"[..], MouseMode::ButtonMotion), - (b"\x1b[?9h\x1b[?1000l", MouseMode::Press), - (b"\x1b[?1000h\x1b[?1003h\x1b[?1000l", MouseMode::AnyMotion), + for stream in [ + &b"\x1b[?1002h\x1b[?1000l"[..], + b"\x1b[?9h\x1b[?1000l", + b"\x1b[?1000h\x1b[?1003h\x1b[?1000l", // In a list with a mode that is not a tracking mode. - (b"\x1b[?1003h\x1b[?25;1002l", MouseMode::AnyMotion), + b"\x1b[?1003h\x1b[?25;1002l", ] { let emu = emu_with(stream); let at = String::from_utf8_lossy(stream).replace('\x1b', "^["); assert_eq!(emu.input_modes().mouse, MouseMode::None, "{at}"); let screen = emu.snapshot(); assert_eq!(screen.mouse_mode(), MouseMode::None, "{at}"); - assert_eq!( - screen.mouse_modes().iter().collect::>(), - [asked], - "{at}: asked for, and not disabled" - ); + assert!(screen.mouse_modes().is_empty(), "{at}"); + for mode in [9, 1000, 1002, 1003] { + assert_eq!(emu.mode_state(mode), ModeState::Reset, "{at}: ?{mode}"); + } } // The last mode set is the one in force, in one list as across // sequences, and setting one again after a reset turns it back on. diff --git a/crates/termlens/src/screen.rs b/crates/termlens/src/screen.rs index 5fcb669..60c4517 100644 --- a/crates/termlens/src/screen.rs +++ b/crates/termlens/src/screen.rs @@ -166,9 +166,11 @@ impl MouseMode { ]; } -/// The set of mouse tracking modes an application has enabled and not yet -/// disabled — what it *asked for*, as distinct from the one protocol the -/// terminal reports in, which is [`Screen::mouse_mode`]. +/// The set of mouse tracking modes an application has enabled since +/// reporting was last turned off — what it *asked for*, as distinct from +/// the one protocol the terminal reports in, which is +/// [`Screen::mouse_mode`]. A reset of any of the four turns reporting off, +/// as in xterm, and empties the set with it. /// /// A terminal reports mouse events in exactly one protocol, so the four /// tracking modes collapse into one value on the input path: enabling @@ -1063,9 +1065,11 @@ impl Screen { self.state.mouse } - /// Every mouse tracking mode the application has enabled and not yet - /// disabled, as a set — see [`MouseModes`] for why the set and the - /// reporting protocol are two different facts. + /// Every mouse tracking mode the application has enabled since + /// reporting was last turned off, as a set — see [`MouseModes`] for why + /// the set and the reporting protocol are two different facts. A reset + /// of any of the four (`CSI ? 1000 l`) ends reporting and empties the + /// set, as xterm then holds no tracking mode (#832). /// /// `DECRQM` answers each tracking mode from this same set, so an /// application that probes `?1002` while `?1003` is also on is told diff --git a/crates/termlens/tests/input.rs b/crates/termlens/tests/input.rs index 98ac876..f8428b3 100644 --- a/crates/termlens/tests/input.rs +++ b/crates/termlens/tests/input.rs @@ -1145,8 +1145,9 @@ fn a_reset_of_another_tracking_mode_turns_reporting_off() -> termlens::Result<() t.wait_until(|s| s.contains("OFF"))?; let s = t.screen(); assert_eq!(s.mouse_mode(), MouseMode::None, "after {set} ?1000l: {s}"); - // The set is what the application asked for and has not disabled. - assert_eq!(s.mouse_modes().iter().collect::>(), [in_force]); + // The set empties with it: xterm then holds no tracking mode, and + // DECRQM reports none set (#832). + assert!(s.mouse_modes().is_empty(), "after {set} ?1000l: {s}"); let err = t .click(1, 1) .expect_err("a terminal with reporting off sends nothing"); diff --git a/crates/termlens/tests/queries.rs b/crates/termlens/tests/queries.rs index 14de9be..487d885 100644 --- a/crates/termlens/tests/queries.rs +++ b/crates/termlens/tests/queries.rs @@ -756,8 +756,20 @@ fn decrqm_answers_each_mouse_tracking_mode_on_its_own() -> termlens::Result<()> ( r"\e[?1000h\e[?1002h\e[?1003h\e[?1003l\e[?1002$p", "11", - "[?1002;1$y", - "and the others do stay set", + "[?1002;2$y", + "and the others with it, as xterm's one tracking mode is off (#832)", + ), + ( + r"\e[?1003h\e[?1000l\e[?1003$p", + "11", + "[?1003;2$y", + "a reset of another member ends the one in force (#832)", + ), + ( + r"\e[?1003h\e[?1000l\e[?1002h\e[?1003$p", + "11", + "[?1003;2$y", + "and a set after it does not bring it back (#832)", ), ] { let mut t = common::spawn_emit( diff --git a/crates/termlens/tests/state.rs b/crates/termlens/tests/state.rs index 35b39d0..46cffe4 100644 --- a/crates/termlens/tests/state.rs +++ b/crates/termlens/tests/state.rs @@ -336,8 +336,12 @@ fn mouse_modes_reports_the_set_the_application_asked_for() -> termlens::Result<( "?1003l", "minus 1003\n", "--wait", - "--raw", - r"\e[?1002l\e[?1000l", + "--csi", + "?1002h", + "1002 again\n", + "--wait", + "--csi", + "?1002l", "none\n", "--wait", ])?; @@ -366,14 +370,20 @@ fn mouse_modes_reports_the_set_the_application_asked_for() -> termlens::Result<( ); assert_eq!(s.mouse_modes().len(), 3); - // Releasing 1003 alone: the set still holds the other two, while the - // protocol collapses to none — as xterm does, and as `click` needs. + // Releasing 1003 turns reporting off, as xterm does, and as `click` + // needs, and empties the set with it: xterm then holds no tracking + // mode, and DECRQM reports none of the three set (#832). t.send(Key::Enter)?; t.wait_until(|s| { - s.contains("minus 1003") - && s.mouse_mode() == MouseMode::None - && s.mouse_modes().iter().collect::>() - == set(&[MouseMode::PressRelease, MouseMode::ButtonMotion]) + s.contains("minus 1003") && s.mouse_mode() == MouseMode::None && s.mouse_modes().is_empty() + })?; + + // A set after it starts the set over. + t.send(Key::Enter)?; + t.wait_until(|s| { + s.contains("1002 again") + && s.mouse_mode() == MouseMode::ButtonMotion + && s.mouse_modes().iter().collect::>() == set(&[MouseMode::ButtonMotion]) })?; t.send(Key::Enter)?; diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 30e3e21..af103a7 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -80,7 +80,10 @@ Both are facts; each is reported where it belongs. The one protocol is the tracker's as well (#693): the backend turns its value off only on a reset of the mode it holds, so after `?1002h ?1000l` it went on reporting, where xterm — for which a reset of any of the four ends -reporting — sends nothing. +reporting — sends nothing. The same reset empties the requested set +(#832): xterm then holds no tracking mode, and `DECRQM` there answers +each one reset, so a set that kept the modes the reset did not name +had `DECRQM` report a mode on that nothing reported in. With no tracking mode active — the state every application probes from at startup — every tracking mode reports reset, which is what lets capability detection succeed: answering "not recognized" there would From 9f9ba54fc51ef9e65fdfc19568d0b89bbb3fc531 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:00:17 +0700 Subject: [PATCH 7/8] fix(emu): answer OSC colour lists and DECID, name the rest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tracker took an OSC colour string as a query only when its whole body was `10;?`, `11;?` or `12;?`, and had no arm for `ESC Z`. So `OSC 10;?;?`, `OSC 17;?`, `OSC 10;?;rgb:…` and `ESC Z` got no reply and were not named in a timeout, though xterm answers each: OSC 10 to 19 go to `ChangeColorsRequest`, which answers each `?` for the code it stands at, and `CASE_DECID` falls through to `CASE_DA1`. An OSC 10 to 19 string is now read as a list from its code. The foreground and background are answered wherever they stand, as they were alone; from 10 or 11 they come first, so the replies are in the order asked. Any other colour asked for is named in the next timeout. `ESC Z` is answered with the DA1 reply. The record leaves these out as the responder's, and still lists a string that also sets a colour, which nobody models. The responder in terminal.rs gains the arms that write the replies and name a list's remainder. Closes #833 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 11 +++ crates/termlens/src/emu/seq.rs | 137 ++++++++++++++++++++++++--- crates/termlens/src/emu/unhandled.rs | 47 ++++++--- crates/termlens/src/terminal.rs | 29 +++++- crates/termlens/tests/queries.rs | 69 ++++++++++++++ docs/DESIGN.md | 6 +- docs/LIMITATIONS.md | 4 +- 7 files changed, 272 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 234f22c..150e1db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,17 @@ reads that marker. ### Changed +- An `OSC 10` to `OSC 19` string is read as xterm reads it, each `?` + asking for the colour of the code it stands at: `OSC 10 ; ? ; ?` gets + the foreground and the background replies, in that order, and + `OSC 10 ; ? ; rgb:…` the foreground's. The colours termlens does not + hold (12 to 19) are named in the next timeout, alone (`OSC 17 ; ?`) or + after the ones answered (`OSC 11 ; ? ; ?`). And `ESC Z` (DECID) gets + the DA1 reply, as in xterm. Each got no reply and no name, so a + program blocked on one waited out the test's timeout undiagnosed. A + test that expected one of these strings in `Screen::unsupported()` + should expect the reply or the timeout's note; a string that also sets + a colour is still listed. (#833) - A reset of any mouse tracking mode (`CSI ? 9 l`, `? 1000 l`, `? 1002 l`, `? 1003 l`) empties the set `Screen::mouse_modes()` reports, and DECRQM answers every tracking mode reset until one is set diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index 73f2f04..8b1d496 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -535,6 +535,24 @@ pub(crate) enum Query { /// True when the query used ST; the reply must mirror it. st_terminated: bool, }, + /// A list of dynamic-colour queries in one `OSC 10`–`19` string, where + /// each `?` asks for the colour of the code it stands at (`OSC 10;?;?` + /// asks for 10 and 11), as xterm's `ChangeColorsRequest` reads it + /// (misc.c 3662). `codes` are the ones the responder answers, 10 and + /// 11, in order; `named` says the list also asked for one it does not, + /// which comes after them, and `shape` names the sequence for that + /// (#833). + OscColors { + codes: Vec, + named: bool, + shape: String, + /// True when the query used ST; the replies must mirror it. + st_terminated: bool, + }, + /// DECID (`ESC Z`), which xterm answers as DA1 (`CASE_DECID` falls + /// through to `CASE_DA1`, charproc.c 4096); it went unanswered and + /// unnamed (#833). + Decid, /// DECRQM: "is private mode `n` set?" — `CSI ? n $ p`. Answering /// this truthfully lets an application that *probes* before using a /// mode (synchronized output above all) turn it on against termlens. @@ -2222,22 +2240,11 @@ impl SeqTracker { fn string_final(&mut self, was_osc: bool, st_terminated: bool) -> SeqEvent { if was_osc { // `osc_buf` holds exactly the content (`ESC ]` and terminator - // stripped). A color query is exactly `10;?` or `11;?` - // (12 = cursor color: unanswerable). + // stripped). + if let Some(query) = self.colour_query(st_terminated) { + return SeqEvent::Query(query); + } match self.osc_buf.as_slice() { - b"10;?" => { - return SeqEvent::Query(Query::OscColor { - code: 10, - st_terminated, - }) - } - b"11;?" => { - return SeqEvent::Query(Query::OscColor { - code: 11, - st_terminated, - }) - } - b"12;?" => return SeqEvent::Query(Query::Unanswerable(self.seq_printable())), content if content.ends_with(b"?") && (content.starts_with(b"4;") || content.starts_with(b"52;")) => @@ -2482,6 +2489,52 @@ impl SeqTracker { SeqEvent::None } + /// The question an `OSC 10`–`19` string asks, if it asks one. xterm + /// walks the `;`-separated list from the code the string names, one + /// code a parameter, and answers each `?` with the colour of its code + /// (`ChangeColorsRequest`, misc.c 3662-3700); any other parameter sets + /// that colour, which nothing models. Only `10;?` and `11;?` alone were + /// taken as questions, so `OSC 10;?;?` and `OSC 17;?` got no reply and + /// no name (#833). + /// + /// The foreground (10) and background (11) are answered, as they were + /// alone, and the rest named: from 10 or 11 the answered codes come + /// first, so the replies are in the order asked. The codes stop at 19, + /// the last of xterm's dynamic colours. + fn colour_query(&self, st_terminated: bool) -> Option { + let mut parts = self.osc_buf.split(|&b| b == b';'); + let first = match parts.next()? { + [b'1', digit @ b'0'..=b'9'] => 10 + (digit - b'0'), + _ => return None, + }; + let mut codes = Vec::new(); + let mut named = false; + for (code, part) in (first..=19).zip(parts) { + if part != b"?" { + continue; + } + if matches!(code, 10 | 11) { + codes.push(code); + } else { + named = true; + } + } + match (codes.as_slice(), named) { + ([], false) => None, + ([], true) => Some(Query::Unanswerable(self.seq_printable())), + (&[code], false) => Some(Query::OscColor { + code, + st_terminated, + }), + _ => Some(Query::OscColors { + codes, + named, + shape: self.seq_printable(), + st_terminated, + }), + } + } + /// A kitty query (`a=q`), taken through kitty's loader in the order /// kitty's `grman_handle_command` (`graphics.c`) takes it (#672). /// @@ -2953,6 +3006,11 @@ impl SeqTracker { }; State::Ground } + // DECID, the VT100's DA1 (#833). + b'Z' => { + event = SeqEvent::Query(Query::Decid); + State::Ground + } // Final byte of a two-character sequence (ESC 7, ESC =, …). _ => State::Ground, }, @@ -5352,6 +5410,55 @@ mod tests { } } + /// Each `?` in an `OSC 10`–`19` list asks for the colour of the code it + /// stands at, as xterm reads it; the responder answers 10 and 11 and + /// names the rest. `ESC Z` is DA1 (#833). + #[test] + fn colour_query_lists_and_decid_are_classified() { + let colours = |codes: &[u8], named: bool, shape: &str| { + vec![Query::OscColors { + codes: codes.to_vec(), + named, + shape: shape.into(), + st_terminated: false, + }] + }; + let one = |code| { + vec![Query::OscColor { + code, + st_terminated: false, + }] + }; + assert_eq!(queries_of(b"\x1b]10;?\x07"), one(10)); + assert_eq!(queries_of(b"\x1b]11;?\x07"), one(11)); + assert_eq!( + queries_of(b"\x1b]10;?;?\x07"), + colours(&[10, 11], false, "^[]10;?;?^G") + ); + assert_eq!( + queries_of(b"\x1b]11;?;?\x07"), + colours(&[11], true, "^[]11;?;?^G") + ); + // A set beside a query: the set is nobody's, the query answered. + assert_eq!(queries_of(b"\x1b]10;?;rgb:ff/00/00\x07"), one(10)); + assert_eq!(queries_of(b"\x1b]10;#ff0000;?\x07"), one(11)); + // The colours termlens does not hold are named. + for (wire, shape) in [ + (&b"\x1b]12;?\x07"[..], "^[]12;?^G"), + (b"\x1b]17;?\x07", "^[]17;?^G"), + (b"\x1b]13;?;?\x07", "^[]13;?;?^G"), + ] { + assert_eq!(queries_of(wire), vec![Query::Unanswerable(shape.into())]); + } + // Sets alone, a code past 19, and a list past 19 ask nothing more. + assert_eq!(queries_of(b"\x1b]10;#ff0000\x07"), vec![]); + assert_eq!(queries_of(b"\x1b]20;?\x07"), vec![]); + assert_eq!(queries_of(b"\x1b]19;x;?\x07"), vec![]); + assert_eq!(queries_of(b"\x1bZ"), vec![Query::Decid]); + // With an intermediate it is no DECID. + assert_eq!(queries_of(b"\x1b#Z"), vec![]); + } + #[test] fn recognizes_decrqm_mode_requests() { assert_eq!(queries_of(b"\x1b[?2026$p"), vec![Query::RequestMode(2026)]); diff --git a/crates/termlens/src/emu/unhandled.rs b/crates/termlens/src/emu/unhandled.rs index 1fb7b77..c5b0dc7 100644 --- a/crates/termlens/src/emu/unhandled.rs +++ b/crates/termlens/src/emu/unhandled.rs @@ -466,8 +466,9 @@ impl Callbacks for Unhandled { // (`ESC \`), which is not a sequence of its own but the terminator // of the OSC, DCS or APC string that came before it — the string // parser hands the ESC back and the backslash arrives here. + // DECID (`ESC Z`) is a query the responder answers (#833). let designation = matches!(i1, Some(b'(' | b')' | b'*' | b'+')) && i2.is_none(); - if designation || (i1.is_none() && matches!(b, b'H' | b'N' | b'O' | b'\\')) { + if designation || (i1.is_none() && matches!(b, b'H' | b'N' | b'O' | b'Z' | b'\\')) { return; } let mut shape = String::from("^["); @@ -604,20 +605,25 @@ impl Callbacks for Unhandled { // repainting its palette got the wrong colours with nothing saying // why (#392). // Exempt exactly what `seq.rs` claims, and in the same shapes it - // claims them in. `10;?` and `11;?` are answered, so only that - // two-operand form is the responder's: xterm also reads - // `10;#ff0000;?` as set-then-query, and since the responder does - // not answer *that*, it belongs here. A palette query is any - // `4;…?`, which is the rule `seq.rs` applies to it. + // claims them in. A dynamic-colour string is the responder's only + // when it asks and sets nothing: xterm reads `10;#ff0000;?` as a + // set of 10 and a question about 11, and the set belongs here. A + // palette query is any `4;…?`, which is the rule `seq.rs` applies + // to it. let cut = self.cut_osc.take(); // An `OSC 1` with other than one operand comes here, not to // `set_window_icon_name`, and the tracker's word for it ends with // it: left over, it would list the icon half of the next `OSC 0`. self.icon_name = false; let colour_query = match params.first() { - // `12;?`, the cursor colour, is named rather than answered, and - // in the same one shape (#691). - Some(&b"10" | &b"11" | &b"12") => params.len() == 2 && params[1] == b"?", + // The dynamic colours, 10 to 19, when every parameter after the + // code asks for one: the responder answers 10 and 11 and names + // the rest, as `seq.rs` reads the list (#691, #833). A + // parameter that sets a colour is honoured by nobody, and keeps + // the string here. + Some(&[b'1', b'0'..=b'9']) => { + params.len() >= 2 && params[1..].iter().all(|p| *p == b"?") + } Some(&b"4") => cut.map_or_else( || matches!(params.last(), Some(&b"?")), |cut| cut.palette_query, @@ -740,6 +746,12 @@ mod tests { ); } + /// DECID (`ESC Z`) is a query the responder answers as DA1 (#833). + #[test] + fn decid_is_not_recorded() { + assert_eq!(shapes(b"\x1bZ\x1b#Z"), ["^[#Z"]); + } + /// The `CSI … t` family splits three ways, and only one of them belongs /// in this record: the reports the responder answers and the ones it /// names in a timeout are already accounted for elsewhere, so listing @@ -935,10 +947,21 @@ mod tests { (&b"\x1b]4;1;?\x07"[..], Vec::<&str>::new()), // A palette query is any `4;…?`, which is what `seq.rs` names. (&b"\x1b]4;1;rgb:ff/00/00;2;?\x07"[..], Vec::<&str>::new()), - // But `10`/`11` are answered only in their two-operand form. - // xterm reads this one as set-then-query, and the responder - // does not answer it, so it belongs in the record. + // A list of dynamic-colour queries, from any of 10 to 19, is + // the responder's, answered or named (#833). + (&b"\x1b]10;?;?\x07"[..], Vec::<&str>::new()), + (&b"\x1b]17;?\x07"[..], Vec::<&str>::new()), + (&b"\x1b]13;?;?;?\x07"[..], Vec::<&str>::new()), + // xterm reads these as a set and a query, one colour each. The + // responder answers the query, and the set, honoured by + // nobody, keeps the string in the record. (&b"\x1b]10;#ff0000;?\x07"[..], vec!["^[]10;#ff0000;?"]), + ( + &b"\x1b]10;?;rgb:ff/00/00\x07"[..], + vec!["^[]10;?;rgb:ff/00/00"], + ), + // A code past xterm's dynamic colours is no colour query. + (&b"\x1b]20;?\x07"[..], vec!["^[]20;?"]), (&b"\x1b]777;x\x07"[..], vec!["^[]777;x"]), ] { assert_eq!( diff --git a/crates/termlens/src/terminal.rs b/crates/termlens/src/terminal.rs index 8a0dfc4..6c3264b 100644 --- a/crates/termlens/src/terminal.rs +++ b/crates/termlens/src/terminal.rs @@ -1471,7 +1471,8 @@ impl EmuState { // emulator cannot render; `4` (sixel) appears only when a test // declared it, which is the author stating which terminal is // being simulated rather than the harness inventing a claim. - Query::PrimaryDa => match self.graphics { + // DECID (`ESC Z`) is DA1 to xterm (#833). + Query::PrimaryDa | Query::Decid => match self.graphics { Graphics::Sixel => b"\x1b[?62;4;22c".to_vec(), _ => b"\x1b[?62;22c".to_vec(), }, @@ -1601,6 +1602,30 @@ impl EmuState { code, st_terminated, } => osc_color(*code, self.foreground, *st_terminated), + // A list: one reply per colour held, in the order asked, and + // the colours not held named (#833). + Query::OscColors { + codes, + named, + shape, + st_terminated, + } => { + if *named { + self.note_unanswered(shape.clone()); + } + let replies: Vec = codes + .iter() + .flat_map(|&code| { + let rgb = if code == 11 { + self.background + } else { + self.foreground + }; + osc_color(code, rgb, *st_terminated) + }) + .collect(); + replies + } Query::RequestMode(mode) => { // DECRPM. Reporting 0 ("not recognized") for anything we // do not track exactly is deliberate — see @@ -2733,6 +2758,7 @@ fn query_shape(query: &Query) -> String { Query::CursorPosition { private: true } => "^[[?6n".into(), Query::OperatingStatus => "^[[5n".into(), Query::PrimaryDa => "^[[c".into(), + Query::Decid => "^[Z".into(), Query::SecondaryDa => "^[[>c".into(), Query::TextAreaSize => "^[[18t".into(), Query::WindowSizePixels => "^[[14t".into(), @@ -2740,6 +2766,7 @@ fn query_shape(query: &Query) -> String { Query::KittyGraphics { shape, .. } => shape.clone(), Query::RequestTermcap { shape, .. } => shape.clone(), Query::OscColor { code, .. } => format!("^[]{code};?"), + Query::OscColors { shape, .. } => shape.clone(), Query::RequestMode(mode) => format!("^[[?{mode}$p"), Query::RequestAnsiMode(mode) => format!("^[[{mode}$p"), Query::Unanswerable(shape) => shape.clone(), diff --git a/crates/termlens/tests/queries.rs b/crates/termlens/tests/queries.rs index 487d885..25a08cf 100644 --- a/crates/termlens/tests/queries.rs +++ b/crates/termlens/tests/queries.rs @@ -151,6 +151,75 @@ fn device_attribute_probes_are_unblocked() -> termlens::Result<()> { Ok(()) } +/// xterm answers each `?` in an `OSC 10`–`19` list, for the code it +/// stands at (`ChangeColorsRequest`, misc.c 3662), and `ESC Z` (DECID) as +/// DA1 (charproc.c 4096). termlens answers the foreground and background +/// wherever they stand in such a list, and `ESC Z`; each went unanswered +/// and unnamed, so a program blocked on one waited out the test's timeout +/// with no diagnosis (#833). The replies come in the order asked. +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY answers or eats the child's queries itself, so they never reach the responder (#149)" +)] +fn colour_lists_and_decid_are_answered() -> termlens::Result<()> { + // Three OSC replies of 24 bytes each, and DA1's 10: 82 bytes. + let mut t = common::spawn_emit( + Terminal::builder() + .size(120, 4) + .timeout(Duration::from_secs(10)) + .foreground_rgb(0xcd, 0xd6, 0xf4) + .background_rgb(0x1e, 0x1e, 0x2e), + &[ + "--raw-mode", + "--raw", + r"\e]10;?;?\a\e]10;?;rgb:ff/00/00\e\\\eZ", + "got:", + "--read", + "82", + " DONE", + "--wait", + ], + )?; + t.wait_until(|s| s.contains("DONE"))?; + assert_eq!( + t.screen().row_text(0).trim_end(), + "got:E]10;rgb:cdcd/d6d6/f4f4GE]11;rgb:1e1e/1e1e/2e2eG\ + E]10;rgb:cdcd/d6d6/f4f4E\\E[?62;22c DONE" + ); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + +/// The dynamic colours termlens does not hold are named in the timeout, +/// on their own and after the ones it answers in the same list (#833); +/// `OSC 12 ; ?` was named before and still is. +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY answers or eats the child's queries itself, so they never reach the responder (#149)" +)] +fn colour_queries_termlens_cannot_answer_are_named() { + for (query, shape) in [ + (r"\e]12;?\a", "^[]12;?"), + (r"\e]17;?\a", "^[]17;?"), + (r"\e]13;?;?\a", "^[]13;?;?"), + (r"\e]11;?;?\a", "^[]11;?;?"), + ] { + let mut t = alive_then_blocked( + Terminal::builder().timeout(Duration::from_millis(400)), + &["--raw", query, "--wait", "never"], + ); + let msg = expire_until_named(&[shape], || { + t.wait_until(|s| s.contains("never")) + .unwrap_err() + .to_string() + }); + assert!(msg.contains(shape), "{query} not named in: {msg}"); + } +} + #[test] #[cfg_attr( windows, diff --git a/docs/DESIGN.md b/docs/DESIGN.md index af103a7..929e208 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -44,10 +44,12 @@ never joined: a grandchild holding the PTY open must not hang `Drop`. Applications ask their terminal questions — DSR `CSI 6 n` (cursor position), DA1/DA2 (device attributes), `CSI 18 t` (text-area size), -`OSC 10/11 ; ?` (colors) — and block on the reply. A mute harness turns +`OSC 10/11 ; ?` (colors, also as a list: `OSC 10 ; ? ; ?` asks for +both) — and block on the reply. A mute harness turns every capability probe into a hang. termlens therefore answers, by default, exactly what a real terminal answers and nothing more: the DA1 -identity is VT220-with-color (`?62;22c`), claiming no feature the +identity, which `ESC Z` (DECID) gets too, is VT220-with-color +(`?62;22c`), claiming no feature the emulator cannot render, and kitty's `CSI ? u` probe is deliberately left unanswered because its protocol resolves via the DA1 reply, exactly as on a real non-kitty terminal. diff --git a/docs/LIMITATIONS.md b/docs/LIMITATIONS.md index e47f543..b81ba7f 100644 --- a/docs/LIMITATIONS.md +++ b/docs/LIMITATIONS.md @@ -114,7 +114,9 @@ CHANGELOG entry. [DESIGN.md](DESIGN.md) §2. - Some questions stay deliberately unanswered — kitty's `CSI ? u`, DECRQSS, DA3, XTVERSION, XTSMGRAPHICS (`CSI ? Pi ; Pa ; Pv S`, which sixel programs - ask once DA1 claims sixel), the `OSC 4` palette query, `OSC 12`, + ask once DA1 claims sixel), the `OSC 4` palette query, `OSC 12` to + `OSC 19` (the dynamic colours other than the foreground and background, + alone or after them in one list, as in `OSC 11 ; ? ; ?`), `OSC 52` *reads*, and the other `CSI … t` reports, such as `11 t` and `19 t` (`18 t`, the text-area size, is answered, and the pixel sizes `14 t` and `16 t` are From c9a6a0183113fc7e3baee90227e812085a2db9cf Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:02:49 +0700 Subject: [PATCH 8/8] fix(emu): let 96-character and % designations replace the set The tracker designated a set only after a single intermediate of `(`, `)`, `*` or `+`. A second intermediate cleared it, and `-`, `.` and `/` named no slot, so `ESC ( % 5` and `ESC - A` changed nothing: a slot holding DEC Special Graphics went on drawing lines, and both were listed in `Screen::unsupported()`. xterm's `xtermDecodeSCS` replaces the slot for each designation its tables take. The tracker now reads `ESC - A`, `ESC . A` and `ESC / A` as G1 to G3, and `ESC ( % F` (and the `)`, `*`, `+` forms) for the finals xterm's `scs_pct_table` takes (`0`, `2`, `3`, `5`, `6`, `=`), each as a set read as ASCII, as LIMITATIONS says of every designation but `0` and `A`. The finals xterm does not take at its default VT420 level, and the VT5xx `"` and `&` sets, still change nothing. The record leaves out the forms the tracker takes. Closes #824 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 7 ++ crates/termlens/src/emu/seq.rs | 95 ++++++++++++++++++++++++---- crates/termlens/src/emu/unhandled.rs | 13 +++- crates/termlens/src/emu/vt100.rs | 19 ++++++ docs/LIMITATIONS.md | 7 +- 5 files changed, 126 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 150e1db..f92df22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,6 +78,13 @@ reads that marker. ### Fixed +- A 96-character designation (`ESC - A`, `ESC . A`, `ESC / A`) and a + `%` one (`ESC ( % 5` and the other finals xterm takes at its default + level) replace the set in their slot and read as ASCII, as + `docs/LIMITATIONS.md` says of every designation but `0` and `A`. They + kept the previous set, so a program that left line drawing that way + went on drawing box characters, and `Screen::unsupported()` listed + them. (#824) - A change of size ends origin mode (`DECOM`) with the scroll margins, as xterm's resize does, and leaves the cursor where it was. Origin mode stayed on, so once the program set a new region, `CUP 1;1` drew at diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index 8b1d496..b2d885b 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -1023,10 +1023,16 @@ pub(crate) struct SeqTracker { /// from every value it could have asked for. cursor_style: Option, /// The intermediate byte of the current `ESC ` - /// sequence — `(` `)` `*` `+` for a G0–G3 designation — so the final - /// byte knows which set it designates. Zero once a second intermediate - /// makes it something else. + /// sequence — `(` `)` `*` `+` for a 94-character G0–G3 designation, + /// `-` `.` `/` for a 96-character G1–G3 one — so the final byte knows + /// which set it designates. Zero once a second intermediate makes it + /// something else, but for the `%` of a 94-character one + /// ([`esc_percent`](Self::esc_percent)). esc_intermediate: u8, + /// The current designation is `ESC ( % F` (or `)`, `*`, `+`): a `%` + /// second intermediate, which xterm takes for the DEC Supplemental, + /// Portuguese, Turkish and Hebrew sets (#824). + esc_percent: bool, /// What `ESC ( ) * + Ps` last designated into G0–G3. g0: Charset, g1: Charset, @@ -1167,6 +1173,7 @@ impl SeqTracker { mouse_encoding: MouseEncoding::Legacy, cursor_style: None, esc_intermediate: 0, + esc_percent: false, g0: Charset::Ascii, g1: Charset::Ascii, g2: Charset::Ascii, @@ -1711,17 +1718,38 @@ impl SeqTracker { /// as ASCII: a designation acknowledged and left untranslated, which is /// close enough for every one of them that guessing at the odd position /// would be a worse answer than the plain one. + /// + /// A 96-character set (`ESC - A`, `ESC . A`, `ESC / A` into G1–G3) and + /// a `%` one (`ESC ( % 5`) read as ASCII too, for the finals xterm's + /// tables take at its default VT420 level: `A`, ISO Latin-1 + /// Supplemental, after `-`, `.` and `/` (`scs96table`, where the + /// others are VT5xx sets or none), and `0`, `2`, `3`, `5`, `6` and `=` + /// after `%` (`scs_pct_table`), which `xtermDecodeSCS` makes DEC + /// Supplemental Graphics for `5`, and ASCII for the rest at that + /// level, since they need a VT5xx or national-replacement mode. Each + /// replaces the set in its slot. They kept it, so a slot holding DEC + /// Special Graphics went on drawing lines (#824). A final xterm does + /// not take leaves the slot as it was, there as here. fn designate(&mut self, final_byte: u8) { - let set = match final_byte { - b'0' => Charset::DecSpecialGraphics, - b'A' => Charset::Uk, - _ => Charset::Ascii, + let set = if self.esc_percent { + matches!(final_byte, b'0' | b'2' | b'3' | b'5' | b'6' | b'=').then_some(Charset::Ascii) + } else if matches!(self.esc_intermediate, b'-' | b'.' | b'/') { + (final_byte == b'A').then_some(Charset::Ascii) + } else { + Some(match final_byte { + b'0' => Charset::DecSpecialGraphics, + b'A' => Charset::Uk, + _ => Charset::Ascii, + }) + }; + let Some(set) = set else { + return; }; match self.esc_intermediate { b'(' => self.g0 = set, - b')' => self.g1 = set, - b'*' => self.g2 = set, - b'+' => self.g3 = set, + b')' | b'-' => self.g1 = set, + b'*' | b'.' => self.g2 = set, + b'+' | b'/' => self.g3 = set, _ => {} } } @@ -2897,6 +2925,7 @@ impl SeqTracker { } 0x20..=0x2f => { self.esc_intermediate = b; + self.esc_percent = false; State::EscIntermediate } ESC => State::Esc, @@ -3016,9 +3045,19 @@ impl SeqTracker { }, State::EscIntermediate => match b { // A second intermediate makes this something other than a - // G0–G3 designation (`ESC % G` selects UTF-8, for one). + // G0–G3 designation (`ESC % G` selects UTF-8, for one), but + // for the `%` of `ESC ( % 5`, which xterm reads as one + // (`scs_pct_table`, #824). The `"` and `&` sets are VT5xx + // sets, which xterm at its default VT420 level ignores. 0x20..=0x2f => { - self.esc_intermediate = 0; + if b == b'%' + && !self.esc_percent + && matches!(self.esc_intermediate, b'(' | b')' | b'*' | b'+') + { + self.esc_percent = true; + } else { + self.esc_intermediate = 0; + } State::EscIntermediate } ESC => State::Esc, @@ -4697,6 +4736,38 @@ mod tests { assert_eq!(drawn(b"\x1b+A\x1bOq"), "q"); } + /// A 96-character designation (`ESC - A` into G1, `ESC .` G2, `ESC /` + /// G3) and a `%` one (`ESC ( % 5`) replace the set in their slot, as + /// xterm's `xtermDecodeSCS` does for each final its tables take at its + /// default VT420 level: `A` after `-`, `.` and `/` (`scs96table`), and + /// `0`, `2`, `3`, `5`, `6` and `=` after `%` (`scs_pct_table`), each + /// read as ASCII here. They kept the previous set, and a slot holding + /// DEC Special Graphics went on drawing lines (#824). The finals + /// xterm's tables do not take, and the VT5xx `"` and `&` sets, change + /// nothing, there as here. + #[test] + fn a_96_character_or_percent_designation_replaces_the_set() { + for (seq, expected) in [ + (&b"\x1b(0\x1b(%5q"[..], "q"), + (b"\x1b(0\x1b(%=q", "q"), + (b"\x1b)0\x0e\x1b-Aq", "q"), + (b"\x1b*0\x1b.A\x1bNq", "q"), + (b"\x1b+0\x1b/A\x1bOq", "q"), + (b"\x1b+0\x1b+%6\x1bOq", "q"), + // Not taken: the slot keeps its set. + (b"\x1b)0\x0e\x1b-Bq", "\u{2500}"), + (b"\x1b)0\x0e\x1b-0q", "\u{2500}"), + (b"\x1b(0\x1b(%8q", "\u{2500}"), + (b"\x1b(0\x1b(\"4q", "\u{2500}"), + (b"\x1b(0\x1b(&5q", "\u{2500}"), + (b"\x1b(0\x1b(%%5q", "\u{2500}"), + // A 96-character set names no G0, and `-` is G1's alone. + (b"\x1b(0\x1b-Aq", "\u{2500}"), + ] { + assert_eq!(drawn(seq), expected, "{seq:?}"); + } + } + #[test] fn a_designation_split_across_feeds_still_applies() { let mut t = SeqTracker::new(crate::graphics::DEFAULT_CAPTURE, TEST_ROWS, TEST_COLS); diff --git a/crates/termlens/src/emu/unhandled.rs b/crates/termlens/src/emu/unhandled.rs index c5b0dc7..348d700 100644 --- a/crates/termlens/src/emu/unhandled.rs +++ b/crates/termlens/src/emu/unhandled.rs @@ -466,8 +466,17 @@ impl Callbacks for Unhandled { // (`ESC \`), which is not a sequence of its own but the terminator // of the OSC, DCS or APC string that came before it — the string // parser hands the ESC back and the backslash arrives here. - // DECID (`ESC Z`) is a query the responder answers (#833). - let designation = matches!(i1, Some(b'(' | b')' | b'*' | b'+')) && i2.is_none(); + // DECID (`ESC Z`) is a query the responder answers (#833). The + // 96-character and `%` designations the tracker takes are the + // tracker's too, in the shapes it takes them in (#824). + let designation = match (i1, i2) { + (Some(b'(' | b')' | b'*' | b'+'), None) => true, + (Some(b'(' | b')' | b'*' | b'+'), Some(b'%')) => { + matches!(b, b'0' | b'2' | b'3' | b'5' | b'6' | b'=') + } + (Some(b'-' | b'.' | b'/'), None) => b == b'A', + _ => false, + }; if designation || (i1.is_none() && matches!(b, b'H' | b'N' | b'O' | b'Z' | b'\\')) { return; } diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index f87d3a4..c17191a 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -1974,6 +1974,25 @@ mod tests { assert!(s.cell(0, 0).unwrap().style().strikethrough, "{s}"); } + /// A 96-character or a `%` designation replaces the set in force, as + /// xterm's does, and is not listed: both rows of #824's table draw + /// `─q`, whole and split at every byte. + #[test] + fn a_96_character_or_percent_designation_ends_line_drawing() { + for stream in ["\x1b(0q\x1b(%5q\x1b(B", "\x1b)0\x0eq\x1b-Aq\x0f"] { + let (whole, bytewise) = whole_and_bytewise(2, 10, 0, stream.as_bytes()); + for emu in [whole, bytewise] { + let s = emu.snapshot(); + assert_eq!(s.row_text(0).trim_end(), "\u{2500}q", "{stream:?}"); + assert!( + s.unsupported().is_empty(), + "{stream:?}: {:?}", + s.unsupported() + ); + } + } + } + /// `ESC ( 0 l q q q k` is a box. Both parsers receive the translated /// stream — the snapshot's correspondence check would fail otherwise. #[test] diff --git a/docs/LIMITATIONS.md b/docs/LIMITATIONS.md index b81ba7f..cc2af65 100644 --- a/docs/LIMITATIONS.md +++ b/docs/LIMITATIONS.md @@ -47,7 +47,12 @@ CHANGELOG entry. the `SO`/`SI` locking shifts, and `ESC N`/`ESC O` (SS2/SS3, one character) are modelled; the DEC Special Graphics set (`0`) and the UK set (`A`, `£` at `#`) are translated, and every other designation — the alternate - ROMs, the other national sets — is acknowledged and reads as ASCII. + ROMs, the other national sets, the 96-character ISO Latin-1 set + (`ESC - A`, `ESC . A`, `ESC / A` into G1–G3) and the `%` sets + (`ESC ( % 5`, DEC Supplemental Graphics, and the others xterm takes at + its default VT420 level) — is acknowledged and reads as ASCII. A + designation xterm ignores at that level, such as the VT5xx `"` and `&` + sets, leaves the set in force. `DECSC`/`DECRC` save and restore this state with the cursor, in one slot per screen as xterm keeps it, and `?1049h`/`l` save and restore it around the alternate screen. xterm's other cursor saves, `CSI s`/`CSI u`